starknetkit
Version:
<!-- logo --> <p align="center"> <img width='300' src="https://starknetkit-website-git-blo-1541-argentlabs.vercel.app/starknetKit-logo.svg"> </p>
31 lines • 412 kB
JavaScript
"use strict";var xd=Object.defineProperty;var Id=(t,e,i)=>e in t?xd(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var W=(t,e,i)=>(Id(t,typeof e!="symbol"?e+"":e,i),i);const Mt=require("./connector-e4ffe813.cjs"),yt=require("./Modal-0ef58a76.cjs"),At=require("starknet"),hh=require("./index-7ba3f4da.cjs");var Ko={exports:{}},Gi=typeof Reflect=="object"?Reflect:null,Na=Gi&&typeof Gi.apply=="function"?Gi.apply:function(e,i,r){return Function.prototype.apply.call(e,i,r)},xs;Gi&&typeof Gi.ownKeys=="function"?xs=Gi.ownKeys:Object.getOwnPropertySymbols?xs=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:xs=function(e){return Object.getOwnPropertyNames(e)};function Sd(t){console&&console.warn&&console.warn(t)}var lh=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Ko.exports=oe;Ko.exports.once=Od;oe.EventEmitter=oe;oe.prototype._events=void 0;oe.prototype._eventsCount=0;oe.prototype._maxListeners=void 0;var ka=10;function Ys(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return ka},set:function(t){if(typeof t!="number"||t<0||lh(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");ka=t}});oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0};oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||lh(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function fh(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return fh(this)};oe.prototype.emit=function(e){for(var i=[],r=1;r<arguments.length;r++)i.push(arguments[r]);var s=e==="error",n=this._events;if(n!==void 0)s=s&&n.error===void 0;else if(!s)return!1;if(s){var o;if(i.length>0&&(o=i[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=n[e];if(c===void 0)return!1;if(typeof c=="function")Na(c,this,i);else for(var u=c.length,h=wh(c,u),r=0;r<u;++r)Na(h[r],this,i);return!0};function dh(t,e,i,r){var s,n,o;if(Ys(i),n=t._events,n===void 0?(n=t._events=Object.create(null),t._eventsCount=0):(n.newListener!==void 0&&(t.emit("newListener",e,i.listener?i.listener:i),n=t._events),o=n[e]),o===void 0)o=n[e]=i,++t._eventsCount;else if(typeof o=="function"?o=n[e]=r?[i,o]:[o,i]:r?o.unshift(i):o.push(i),s=fh(t),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,Sd(a)}return t}oe.prototype.addListener=function(e,i){return dh(this,e,i,!1)};oe.prototype.on=oe.prototype.addListener;oe.prototype.prependListener=function(e,i){return dh(this,e,i,!0)};function Dd(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function ph(t,e,i){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:i},s=Dd.bind(r);return s.listener=i,r.wrapFn=s,s}oe.prototype.once=function(e,i){return Ys(i),this.on(e,ph(this,e,i)),this};oe.prototype.prependOnceListener=function(e,i){return Ys(i),this.prependListener(e,ph(this,e,i)),this};oe.prototype.removeListener=function(e,i){var r,s,n,o,a;if(Ys(i),s=this._events,s===void 0)return this;if(r=s[e],r===void 0)return this;if(r===i||r.listener===i)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,r.listener||i));else if(typeof r!="function"){for(n=-1,o=r.length-1;o>=0;o--)if(r[o]===i||r[o].listener===i){a=r[o].listener,n=o;break}if(n<0)return this;n===0?r.shift():Ad(r,n),r.length===1&&(s[e]=r[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||i)}return this};oe.prototype.off=oe.prototype.removeListener;oe.prototype.removeAllListeners=function(e){var i,r,s;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var n=Object.keys(r),o;for(s=0;s<n.length;++s)o=n[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(i=r[e],typeof i=="function")this.removeListener(e,i);else if(i!==void 0)for(s=i.length-1;s>=0;s--)this.removeListener(e,i[s]);return this};function gh(t,e,i){var r=t._events;if(r===void 0)return[];var s=r[e];return s===void 0?[]:typeof s=="function"?i?[s.listener||s]:[s]:i?$d(s):wh(s,s.length)}oe.prototype.listeners=function(e){return gh(this,e,!0)};oe.prototype.rawListeners=function(e){return gh(this,e,!1)};oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):yh.call(t,e)};oe.prototype.listenerCount=yh;function yh(t){var e=this._events;if(e!==void 0){var i=e[t];if(typeof i=="function")return 1;if(i!==void 0)return i.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?xs(this._events):[]};function wh(t,e){for(var i=new Array(e),r=0;r<e;++r)i[r]=t[r];return i}function Ad(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function $d(t){for(var e=new Array(t.length),i=0;i<e.length;++i)e[i]=t[i].listener||t[i];return e}function Od(t,e){return new Promise(function(i,r){function s(o){t.removeListener(e,n),r(o)}function n(){typeof t.removeListener=="function"&&t.removeListener("error",s),i([].slice.call(arguments))}mh(t,e,n,{once:!0}),e!=="error"&&Td(t,s,{once:!0})})}function Td(t,e,i){typeof t.on=="function"&&mh(t,"error",e,i)}function mh(t,e,i,r){if(typeof t.on=="function")r.once?t.once(e,i):t.on(e,i);else if(typeof t.addEventListener=="function")t.addEventListener(e,function s(n){r.once&&t.removeEventListener(e,s),i(n)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}var rt=Ko.exports;const bh=Mt.getDefaultExportFromCjs(rt);var L={};/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var eo=function(t,e){return eo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var s in r)r.hasOwnProperty(s)&&(i[s]=r[s])},eo(t,e)};function Cd(t,e){eo(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}var to=function(){return to=Object.assign||function(e){for(var i,r=1,s=arguments.length;r<s;r++){i=arguments[r];for(var n in i)Object.prototype.hasOwnProperty.call(i,n)&&(e[n]=i[n])}return e},to.apply(this,arguments)};function Pd(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(i[r[s]]=t[r[s]]);return i}function Rd(t,e,i,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,i,n):o(e,i))||n);return s>3&&n&&Object.defineProperty(e,i,n),n}function Fd(t,e){return function(i,r){e(i,r,t)}}function Bd(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Ud(t,e,i,r){function s(n){return n instanceof i?n:new i(function(o){o(n)})}return new(i||(i=Promise))(function(n,o){function a(h){try{u(r.next(h))}catch(l){o(l)}}function c(h){try{u(r.throw(h))}catch(l){o(l)}}function u(h){h.done?n(h.value):s(h.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function Nd(t,e){var i={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},r,s,n,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(h){return c([u,h])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return i.label++,{value:u[1],done:!1};case 5:i.label++,s=u[1],u=[0];continue;case 7:u=i.ops.pop(),i.trys.pop();continue;default:if(n=i.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){i=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){i.label=u[1];break}if(u[0]===6&&i.label<n[1]){i.label=n[1],n=u;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(u);break}n[2]&&i.ops.pop(),i.trys.pop();continue}u=e.call(t,i)}catch(h){u=[6,h],s=0}finally{r=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function kd(t,e,i,r){r===void 0&&(r=i),t[r]=e[i]}function Ld(t,e){for(var i in t)i!=="default"&&!e.hasOwnProperty(i)&&(e[i]=t[i])}function io(t){var e=typeof Symbol=="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function vh(t,e){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return n}function Md(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(vh(arguments[e]));return t}function qd(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<i;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)r[s]=n[o];return r}function Nr(t){return this instanceof Nr?(this.v=t,this):new Nr(t)}function jd(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(d,g){n.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){l(n[0][3],d)}}function c(f){f.value instanceof Nr?Promise.resolve(f.value.v).then(u,h):l(n[0][2],f)}function u(f){a("next",f)}function h(f){a("throw",f)}function l(f,p){f(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function zd(t){var e,i;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,n){e[s]=t[s]?function(o){return(i=!i)?{value:Nr(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function Kd(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],i;return e?e.call(t):(t=typeof io=="function"?io(t):t[Symbol.iterator](),i={},r("next"),r("throw"),r("return"),i[Symbol.asyncIterator]=function(){return this},i);function r(n){i[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function Vd(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function Hd(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i in t)Object.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e.default=t,e}function Wd(t){return t&&t.__esModule?t:{default:t}}function Gd(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Yd(t,e,i){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,i),i}const Jd=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return to},__asyncDelegator:zd,__asyncGenerator:jd,__asyncValues:Kd,__await:Nr,__awaiter:Ud,__classPrivateFieldGet:Gd,__classPrivateFieldSet:Yd,__createBinding:kd,__decorate:Rd,__exportStar:Ld,__extends:Cd,__generator:Nd,__importDefault:Wd,__importStar:Hd,__makeTemplateObject:Vd,__metadata:Bd,__param:Fd,__read:vh,__rest:Pd,__spread:Md,__spreadArrays:qd,__values:io},Symbol.toStringTag,{value:"Module"})),Gr=Mt.getAugmentedNamespace(Jd);var wn={},cr={},La;function Zd(){if(La)return cr;La=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.delay=void 0;function t(e){return new Promise(i=>{setTimeout(()=>{i(!0)},e)})}return cr.delay=t,cr}var di={},mn={},pi={},Ma;function Qd(){return Ma||(Ma=1,Object.defineProperty(pi,"__esModule",{value:!0}),pi.ONE_THOUSAND=pi.ONE_HUNDRED=void 0,pi.ONE_HUNDRED=100,pi.ONE_THOUSAND=1e3),pi}var bn={},qa;function Xd(){return qa||(qa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(bn)),bn}var ja;function Eh(){return ja||(ja=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gr;e.__exportStar(Qd(),t),e.__exportStar(Xd(),t)}(mn)),mn}var za;function ep(){if(za)return di;za=1,Object.defineProperty(di,"__esModule",{value:!0}),di.fromMiliseconds=di.toMiliseconds=void 0;const t=Eh();function e(r){return r*t.ONE_THOUSAND}di.toMiliseconds=e;function i(r){return Math.floor(r/t.ONE_THOUSAND)}return di.fromMiliseconds=i,di}var Ka;function tp(){return Ka||(Ka=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gr;e.__exportStar(Zd(),t),e.__exportStar(ep(),t)}(wn)),wn}var Ui={},Va;function ip(){if(Va)return Ui;Va=1,Object.defineProperty(Ui,"__esModule",{value:!0}),Ui.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(i){if(this.timestamps.has(i))throw new Error(`Watch already started for label: ${i}`);this.timestamps.set(i,{started:Date.now()})}stop(i){const r=this.get(i);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${i}`);const s=Date.now()-r.started;this.timestamps.set(i,{started:r.started,elapsed:s})}get(i){const r=this.timestamps.get(i);if(typeof r>"u")throw new Error(`No timestamp found for label: ${i}`);return r}elapsed(i){const r=this.get(i);return r.elapsed||Date.now()-r.started}}return Ui.Watch=t,Ui.default=t,Ui}var vn={},ur={},Ha;function rp(){if(Ha)return ur;Ha=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.IWatch=void 0;class t{}return ur.IWatch=t,ur}var Wa;function sp(){return Wa||(Wa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Gr.__exportStar(rp(),t)}(vn)),vn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gr;e.__exportStar(tp(),t),e.__exportStar(ip(),t),e.__exportStar(sp(),t),e.__exportStar(Eh(),t)})(L);class Ti{}let np=class extends Ti{constructor(e){super()}};const Ga=L.FIVE_SECONDS,Ci={pulse:"heartbeat_pulse"};let op=class _h extends np{constructor(e){super(e),this.events=new rt.EventEmitter,this.interval=Ga,this.interval=e?.interval||Ga}static async init(e){const i=new _h(e);return await i.init(),i}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(Ci.pulse)}};const ap=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,cp=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,up=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function hp(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){lp(t);return}return e}function lp(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function os(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const i=t.trim();if(i.length<=9)switch(i.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!up.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(ap.test(t)||cp.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,hp)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function fp(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function _e(t,...e){try{return fp(t(...e))}catch(i){return Promise.reject(i)}}function dp(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function pp(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Is(t){if(dp(t))return String(t);if(pp(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Is(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const ro="base64:";function gp(t){return typeof t=="string"?t:ro+mp(t)}function yp(t){return typeof t!="string"||!t.startsWith(ro)?t:wp(t.slice(ro.length))}function wp(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function mp(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ve(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function bp(...t){return Ve(t.join(":"))}function as(t){return t=Ve(t),t?t+":":""}function vp(t,e){if(e===void 0)return!0;let i=0,r=t.indexOf(":");for(;r>-1;)i++,r=t.indexOf(":",r+1);return i<=e}function Ep(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const _p="memory",xp=()=>{const t=new Map;return{name:_p,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,i){t.set(e,i)},setItemRaw(e,i){t.set(e,i)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Ip(t={}){const e={mounts:{"":t.driver||xp()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=u=>{for(const h of e.mountpoints)if(u.startsWith(h))return{base:h,relativeKey:u.slice(h.length),driver:e.mounts[h]};return{base:"",relativeKey:u,driver:e.mounts[""]}},r=(u,h)=>e.mountpoints.filter(l=>l.startsWith(u)||h&&u.startsWith(l)).map(l=>({relativeBase:u.length>l.length?u.slice(l.length):void 0,mountpoint:l,driver:e.mounts[l]})),s=(u,h)=>{if(e.watching){h=Ve(h);for(const l of e.watchListeners)l(u,h)}},n=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Ya(e.mounts[u],s,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,h,l)=>{const f=new Map,p=d=>{let g=f.get(d.base);return g||(g={driver:d.driver,base:d.base,items:[]},f.set(d.base,g)),g};for(const d of u){const g=typeof d=="string",y=Ve(g?d:d.key),E=g?void 0:d.value,v=g||!d.options?h:{...h,...d.options},m=i(y);p(m).items.push({key:y,value:E,relativeKey:m.relativeKey,options:v})}return Promise.all([...f.values()].map(d=>l(d))).then(d=>d.flat())},c={hasItem(u,h={}){u=Ve(u);const{relativeKey:l,driver:f}=i(u);return _e(f.hasItem,l,h)},getItem(u,h={}){u=Ve(u);const{relativeKey:l,driver:f}=i(u);return _e(f.getItem,l,h).then(p=>os(p))},getItems(u,h={}){return a(u,h,l=>l.driver.getItems?_e(l.driver.getItems,l.items.map(f=>({key:f.relativeKey,options:f.options})),h).then(f=>f.map(p=>({key:bp(l.base,p.key),value:os(p.value)}))):Promise.all(l.items.map(f=>_e(l.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:os(p)})))))},getItemRaw(u,h={}){u=Ve(u);const{relativeKey:l,driver:f}=i(u);return f.getItemRaw?_e(f.getItemRaw,l,h):_e(f.getItem,l,h).then(p=>yp(p))},async setItem(u,h,l={}){if(h===void 0)return c.removeItem(u);u=Ve(u);const{relativeKey:f,driver:p}=i(u);p.setItem&&(await _e(p.setItem,f,Is(h),l),p.watch||s("update",u))},async setItems(u,h){await a(u,h,async l=>{if(l.driver.setItems)return _e(l.driver.setItems,l.items.map(f=>({key:f.relativeKey,value:Is(f.value),options:f.options})),h);l.driver.setItem&&await Promise.all(l.items.map(f=>_e(l.driver.setItem,f.relativeKey,Is(f.value),f.options)))})},async setItemRaw(u,h,l={}){if(h===void 0)return c.removeItem(u,l);u=Ve(u);const{relativeKey:f,driver:p}=i(u);if(p.setItemRaw)await _e(p.setItemRaw,f,h,l);else if(p.setItem)await _e(p.setItem,f,gp(h),l);else return;p.watch||s("update",u)},async removeItem(u,h={}){typeof h=="boolean"&&(h={removeMeta:h}),u=Ve(u);const{relativeKey:l,driver:f}=i(u);f.removeItem&&(await _e(f.removeItem,l,h),(h.removeMeta||h.removeMata)&&await _e(f.removeItem,l+"$",h),f.watch||s("remove",u))},async getMeta(u,h={}){typeof h=="boolean"&&(h={nativeOnly:h}),u=Ve(u);const{relativeKey:l,driver:f}=i(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await _e(f.getMeta,l,h)),!h.nativeOnly){const d=await _e(f.getItem,l+"$",h).then(g=>os(g));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,h,l={}){return this.setItem(u+"$",h,l)},removeMeta(u,h={}){return this.removeItem(u+"$",h)},async getKeys(u,h={}){u=as(u);const l=r(u,!0);let f=[];const p=[];let d=!0;for(const y of l){y.driver.flags?.maxDepth||(d=!1);const E=await _e(y.driver.getKeys,y.relativeBase,h);for(const v of E){const m=y.mountpoint+Ve(v);f.some(D=>m.startsWith(D))||p.push(m)}f=[y.mountpoint,...f.filter(v=>!v.startsWith(y.mountpoint))]}const g=h.maxDepth!==void 0&&!d;return p.filter(y=>(!g||vp(y,h.maxDepth))&&Ep(y,u))},async clear(u,h={}){u=as(u),await Promise.all(r(u,!1).map(async l=>{if(l.driver.clear)return _e(l.driver.clear,l.relativeBase,h);if(l.driver.removeItem){const f=await l.driver.getKeys(l.relativeBase||"",h);return Promise.all(f.map(p=>l.driver.removeItem(p,h)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Ja(u)))},async watch(u){return await n(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(h=>h!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,h){if(u=as(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((l,f)=>f.length-l.length)),e.mounts[u]=h,e.watching&&Promise.resolve(Ya(h,s,u)).then(l=>{e.unwatch[u]=l}).catch(console.error),c},async unmount(u,h=!0){u=as(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),h&&await Ja(e.mounts[u]),e.mountpoints=e.mountpoints.filter(l=>l!==u),delete e.mounts[u])},getMount(u=""){u=Ve(u)+":";const h=i(u);return{driver:h.driver,base:h.base}},getMounts(u="",h={}){return u=Ve(u),r(u,h.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,h={})=>c.getKeys(u,h),get:(u,h={})=>c.getItem(u,h),set:(u,h,l={})=>c.setItem(u,h,l),has:(u,h={})=>c.hasItem(u,h),del:(u,h={})=>c.removeItem(u,h),remove:(u,h={})=>c.removeItem(u,h)};return c}function Ya(t,e,i){return t.watch?t.watch((r,s)=>e(r,i+s)):()=>{}}async function Ja(t){typeof t.dispose=="function"&&await _e(t.dispose)}function Pi(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function xh(t,e){let i;const r=()=>{if(i)return i;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),i=Pi(s),i.then(n=>{n.onclose=()=>i=void 0},()=>{}),i};return(s,n)=>r().then(o=>n(o.transaction(e,s).objectStore(e)))}let En;function Yr(){return En||(En=xh("keyval-store","keyval")),En}function Za(t,e=Yr()){return e("readonly",i=>Pi(i.get(t)))}function Sp(t,e,i=Yr()){return i("readwrite",r=>(r.put(e,t),Pi(r.transaction)))}function Dp(t,e=Yr()){return e("readwrite",i=>(i.delete(t),Pi(i.transaction)))}function Ap(t=Yr()){return t("readwrite",e=>(e.clear(),Pi(e.transaction)))}function $p(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Pi(t.transaction)}function Op(t=Yr()){return t("readonly",e=>{if(e.getAllKeys)return Pi(e.getAllKeys());const i=[];return $p(e,r=>i.push(r.key)).then(()=>i)})}const Tp=t=>JSON.stringify(t,(e,i)=>typeof i=="bigint"?i.toString()+"n":i),Cp=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,i=t.replace(e,'$1"$2n"$3');return JSON.parse(i,(r,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Yi(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Cp(t)}catch{return t}}function Si(t){return typeof t=="string"?t:Tp(t)||""}const Pp="idb-keyval";var Rp=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",i=s=>e+s;let r;return t.dbName&&t.storeName&&(r=xh(t.dbName,t.storeName)),{name:Pp,options:t,async hasItem(s){return!(typeof await Za(i(s),r)>"u")},async getItem(s){return await Za(i(s),r)??null},setItem(s,n){return Sp(i(s),n,r)},removeItem(s){return Dp(i(s),r)},getKeys(){return Op(r)},clear(){return Ap(r)}}};const Fp="WALLET_CONNECT_V2_INDEXED_DB",Bp="keyvaluestorage";let Up=class{constructor(){this.indexedDb=Ip({driver:Rp({dbName:Fp,storeName:Bp})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const i=await this.indexedDb.getItem(e);if(i!==null)return i}async setItem(e,i){await this.indexedDb.setItem(e,Si(i))}async removeItem(e){await this.indexedDb.removeItem(e)}};var _n=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ss={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(i){return this.hasOwnProperty(i)?String(this[i]):null},t.prototype.setItem=function(i,r){this[i]=String(r)},t.prototype.removeItem=function(i){delete this[i]},t.prototype.clear=function(){const i=this;Object.keys(i).forEach(function(r){i[r]=void 0,delete i[r]})},t.prototype.key=function(i){return i=i||0,Object.keys(this)[i]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof _n<"u"&&_n.localStorage?Ss.exports=_n.localStorage:typeof window<"u"&&window.localStorage?Ss.exports=window.localStorage:Ss.exports=new e})();function Np(t){var e;return[t[0],Yi((e=t[1])!=null?e:"")]}let kp=class{constructor(){this.localStorage=Ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Np)}async getItem(e){const i=this.localStorage.getItem(e);if(i!==null)return Yi(i)}async setItem(e,i){this.localStorage.setItem(e,Si(i))}async removeItem(e){this.localStorage.removeItem(e)}};const Lp="wc_storage_version",Qa=1,Mp=async(t,e,i)=>{const r=Lp,s=await e.getItem(r);if(s&&s>=Qa){i(e);return}const n=await t.getKeys();if(!n.length){i(e);return}const o=[];for(;n.length;){const a=n.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(r,Qa),i(e),qp(t,o)},qp=async(t,e)=>{e.length&&e.forEach(async i=>{await t.removeItem(i)})};let jp=class{constructor(){this.initialized=!1,this.setInitialized=i=>{this.storage=i,this.initialized=!0};const e=new kp;this.storage=e;try{const i=new Up;Mp(e,i,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,i){return await this.initialize(),this.storage.setItem(e,i)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const i=setInterval(()=>{this.initialized&&(clearInterval(i),e())},20)})}};function zp(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Kp=Vp;function Vp(t,e,i){var r=i&&i.stringify||zp,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=r(t);for(var a=1;a<n;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",h=1-s,l=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(l=l>-1?l:0,t.charCodeAt(p+1)){case 100:case 102:if(h>=c||e[h]==null)break;l<p&&(u+=t.slice(l,p)),u+=Number(e[h]),l=p+2,p++;break;case 105:if(h>=c||e[h]==null)break;l<p&&(u+=t.slice(l,p)),u+=Math.floor(Number(e[h])),l=p+2,p++;break;case 79:case 111:case 106:if(h>=c||e[h]===void 0)break;l<p&&(u+=t.slice(l,p));var d=typeof e[h];if(d==="string"){u+="'"+e[h]+"'",l=p+2,p++;break}if(d==="function"){u+=e[h].name||"<anonymous>",l=p+2,p++;break}u+=r(e[h]),l=p+2,p++;break;case 115:if(h>=c)break;l<p&&(u+=t.slice(l,p)),u+=String(e[h]),l=p+2,p++;break;case 37:l<p&&(u+=t.slice(l,p)),u+="%",l=p+2,p++,h--;break}++h}++p}return l===-1?t:(l<f&&(u+=t.slice(l)),u)}const Xa=Kp;var Hi=Tt;const kr=tg().console||{},Hp={mapHttpRequest:cs,mapHttpResponse:cs,wrapRequestSerializer:xn,wrapResponseSerializer:xn,wrapErrorSerializer:xn,req:cs,res:cs,err:Zp};function Wp(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Tt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const i=t.browser.write||kr;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},s=Wp(t.browser.serialize,r);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=["error","fatal","warn","info","debug","trace"];typeof i=="function"&&(i.error=i.fatal=i.warn=i.info=i.debug=i.trace=i),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(i);c.log||(c.log=Lr),Object.defineProperty(c,"levelVal",{get:h}),Object.defineProperty(c,"level",{get:l,set:f});const u={transmit:e,serialize:s,asObject:t.browser.asObject,levels:o,timestamp:Qp(t)};c.levels=Tt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=Lr,c.serializers=r,c._serialize=s,c._stdErrSerialize=n,c.child=p,e&&(c._logEvent=so());function h(){return this.level==="silent"?1/0:this.levels.values[this.level]}function l(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,Ni(u,c,"error","log"),Ni(u,c,"fatal","error"),Ni(u,c,"warn","error"),Ni(u,c,"info","log"),Ni(u,c,"debug","log"),Ni(u,c,"trace","log")}function p(d,g){if(!d)throw new Error("missing bindings for child Pino");g=g||{},s&&d.serializers&&(g.serializers=d.serializers);const y=g.serializers;if(s&&y){var E=Object.assign({},r,y),v=t.browser.serialize===!0?Object.keys(E):s;delete d.serializers,Js([d],v,E,this._stdErrSerialize)}function m(D){this._childLevel=(D._childLevel|0)+1,this.error=ki(D,d,"error"),this.fatal=ki(D,d,"fatal"),this.warn=ki(D,d,"warn"),this.info=ki(D,d,"info"),this.debug=ki(D,d,"debug"),this.trace=ki(D,d,"trace"),E&&(this.serializers=E,this._serialize=v),e&&(this._logEvent=so([].concat(D._logEvent.bindings,d)))}return m.prototype=this,new m(this)}return c}Tt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}};Tt.stdSerializers=Hp;Tt.stdTimeFunctions=Object.assign({},{nullTime:Ih,epochTime:Sh,unixTime:Xp,isoTime:eg});function Ni(t,e,i,r){const s=Object.getPrototypeOf(e);e[i]=e.levelVal>e.levels.values[i]?Lr:s[i]?s[i]:kr[i]||kr[r]||Lr,Gp(t,e,i)}function Gp(t,e,i){!t.transmit&&e[i]===Lr||(e[i]=function(r){return function(){const n=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===kr?kr:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Js(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,Yp(this,i,o,n)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,h=Tt.levels.values[u],l=Tt.levels.values[i];if(l<h)return;Jp(this,{ts:n,methodLevel:i,methodValue:l,transmitLevel:u,transmitValue:Tt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[i]))}function Yp(t,e,i,r){t._serialize&&Js(i,t._serialize,t.serializers,t._stdErrSerialize);const s=i.slice();let n=s[0];const o={};r&&(o.time=r),o.level=Tt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),n!==null&&typeof n=="object"){for(;a--&&typeof s[0]=="object";)Object.assign(o,s.shift());n=s.length?Xa(s.shift(),s):void 0}else typeof n=="string"&&(n=Xa(s.shift(),s));return n!==void 0&&(o.msg=n),o}function Js(t,e,i,r){for(const s in t)if(r&&t[s]instanceof Error)t[s]=Tt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s]))for(const n in t[s])e&&e.indexOf(n)>-1&&n in i&&(t[s][n]=i[n](t[s][n]))}function ki(t,e,i){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var s=1;s<r.length;s++)r[s]=arguments[s-1];return t[i].apply(this,r)}}function Jp(t,e,i){const r=e.send,s=e.ts,n=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Js(i,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=i.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=n,t._logEvent.level.value=o,r(n,t._logEvent,a),t._logEvent=so(c)}function so(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Zp(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const i in t)e[i]===void 0&&(e[i]=t[i]);return e}function Qp(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ih:Sh}function cs(){return{}}function xn(t){return t}function Lr(){}function Ih(){return!1}function Sh(){return Date.now()}function Xp(){return Math.round(Date.now()/1e3)}function eg(){return new Date(Date.now()).toISOString()}function tg(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const Zs=Mt.getDefaultExportFromCjs(Hi),ig={level:"info"},Jr="custom_context",Vo=1e3*1024;let rg=class{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},ec=class{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const i=new rg(e);if(i.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${i.size}`);for(;this.size+i.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=i),this.tail=i):(this.head=i,this.tail=i),this.lengthInNodes++,this.sizeInBytes+=i.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let i=this.head;for(;i!==null;)e.push(i.value),i=i.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const i=e.value;return e=e.next,{done:!1,value:i}}}}};class Dh{constructor(e,i=Vo){this.level=e??"error",this.levelValue=Hi.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=i,this.logs=new ec(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,i){i===Hi.levels.values.error?console.error(e):i===Hi.levels.values.warn?console.warn(e):i===Hi.levels.values.debug?console.debug(e):i===Hi.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Si({timestamp:new Date().toISOString(),log:e}));const i=typeof e=="string"?JSON.parse(e).level:e.level;i>=this.levelValue&&this.forwardToConsole(e,i)}getLogs(){return this.logs}clearLogs(){this.logs=new ec(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const i=this.getLogArray();return i.push(Si({extraMetadata:e})),new Blob(i,{type:"application/json"})}}let sg=class{constructor(e,i=Vo){this.baseChunkLogger=new Dh(e,i)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const i=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=i,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(i)}},ng=class{constructor(e,i=Vo){this.baseChunkLogger=new Dh(e,i)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var og=Object.defineProperty,ag=Object.defineProperties,cg=Object.getOwnPropertyDescriptors,tc=Object.getOwnPropertySymbols,ug=Object.prototype.hasOwnProperty,hg=Object.prototype.propertyIsEnumerable,ic=(t,e,i)=>e in t?og(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Rs=(t,e)=>{for(var i in e||(e={}))ug.call(e,i)&&ic(t,i,e[i]);if(tc)for(var i of tc(e))hg.call(e,i)&&ic(t,i,e[i]);return t},Fs=(t,e)=>ag(t,cg(e));function Ho(t){return Fs(Rs({},t),{level:t?.level||ig.level})}function lg(t,e=Jr){return t[e]||""}function fg(t,e,i=Jr){return t[i]=e,t}function Qe(t,e=Jr){let i="";return typeof t.bindings>"u"?i=lg(t,e):i=t.bindings().context||"",i}function dg(t,e,i=Jr){const r=Qe(t,i);return r.trim()?`${r}/${e}`:e}function je(t,e,i=Jr){const r=dg(t,e,i),s=t.child({context:r});return fg(s,r,i)}function pg(t){var e,i;const r=new sg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Zs(Fs(Rs({},t.opts),{level:"trace",browser:Fs(Rs({},(i=t.opts)==null?void 0:i.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function gg(t){var e;const i=new ng((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Zs(Fs(Rs({},t.opts),{level:"trace"}),i),chunkLoggerController:i}}function yg(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?pg(t):gg(t)}var wg=Object.defineProperty,mg=(t,e,i)=>e in t?wg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rc=(t,e,i)=>mg(t,typeof e!="symbol"?e+"":e,i);let bg=class extends Ti{constructor(e){super(),this.opts=e,rc(this,"protocol","wc"),rc(this,"version",2)}};var vg=Object.defineProperty,Eg=(t,e,i)=>e in t?vg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,_g=(t,e,i)=>Eg(t,typeof e!="symbol"?e+"":e,i);class xg extends Ti{constructor(e,i){super(),this.core=e,this.logger=i,_g(this,"records",new Map)}}let Ig=class{constructor(e,i){this.logger=e,this.core=i}},Sg=class extends Ti{constructor(e,i){super(),this.relayer=e,this.logger=i}},Dg=class extends Ti{constructor(e){super()}},Ag=class{constructor(e,i,r,s){this.core=e,this.logger=i,this.name=r}},$g=class extends Ti{constructor(e,i){super(),this.relayer=e,this.logger=i}};class Og extends Ti{constructor(e,i){super(),this.core=e,this.logger=i}}let Tg=class{constructor(e,i,r){this.core=e,this.logger=i,this.store=r}},Cg=class{constructor(e,i){this.projectId=e,this.logger=i}},Pg=class{constructor(e,i,r){this.core=e,this.logger=i,this.telemetryEnabled=r}};var Rg=Object.defineProperty,Fg=(t,e,i)=>e in t?Rg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,sc=(t,e,i)=>Fg(t,typeof e!="symbol"?e+"":e,i);let Bg=class{constructor(e){this.opts=e,sc(this,"protocol","wc"),sc(this,"version",2)}},Ug=class{constructor(e){this.client=e}};function Ng(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ah(t,...e){if(!Ng(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function nc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function kg(t,e){Ah(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}const Li=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const In=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Lg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function $h(t){return typeof t=="string"&&(t=Lg(t)),Ah(t),t}let Mg=class{clone(){return this._cloneInto()}};function qg(t){const e=r=>t().update($h(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function Oh(t=32){if(Li&&typeof Li.getRandomValues=="function")return Li.getRandomValues(new Uint8Array(t));if(Li&&typeof Li.randomBytes=="function")return Li.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function jg(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}let zg=class extends Mg{constructor(e,i,r,s){super(),this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=In(this.buffer)}update(e){nc(this);const{view:i,buffer:r,blockLen:s}=this;e=$h(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=In(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nc(this),kg(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;i[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)i[l]=0;jg(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=In(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,h[l],n)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%i&&e.buffer.set(r),e}};const us=BigInt(2**32-1),no=BigInt(32);function Th(t,e=!1){return e?{h:Number(t&us),l:Number(t>>no&us)}:{h:Number(t>>no&us)|0,l:Number(t&us)|0}}function Kg(t,e=!1){let i=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=Th(t[s],e);[i[s],r[s]]=[n,o]}return[i,r]}const Vg=(t,e)=>BigInt(t>>>0)<<no|BigInt(e>>>0),Hg=(t,e,i)=>t>>>i,Wg=(t,e,i)=>t<<32-i|e>>>i,Gg=(t,e,i)=>t>>>i|e<<32-i,Yg=(t,e,i)=>t<<32-i|e>>>i,Jg=(t,e,i)=>t<<64-i|e>>>i-32,Zg=(t,e,i)=>t>>>i-32|e<<64-i,Qg=(t,e)=>e,Xg=(t,e)=>t,e0=(t,e,i)=>t<<i|e>>>32-i,t0=(t,e,i)=>e<<i|t>>>32-i,i0=(t,e,i)=>e<<i-32|t>>>64-i,r0=(t,e,i)=>t<<i-32|e>>>64-i;function s0(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:s|0}}const n0=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),o0=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,a0=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),c0=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,u0=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),h0=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0,Y={fromBig:Th,split:Kg,toBig:Vg,shrSH:Hg,shrSL:Wg,rotrSH:Gg,rotrSL:Yg,rotrBH:Jg,rotrBL:Zg,rotr32H:Qg,rotr32L:Xg,rotlSH:e0,rotlSL:t0,rotlBH:i0,rotlBL:r0,add:s0,add3L:n0,add3H:o0,add4L:a0,add4H:c0,add5H:h0,add5L:u0},[l0,f0]=(()=>Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))))(),Vt=new Uint32Array(80),Ht=new Uint32Array(80);let d0=class extends zg{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:i,Bh:r,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:h,Fh:l,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y]}set(e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=h|0,this.Fh=l|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,i){for(let m=0;m<16;m++,i+=4)Vt[m]=e.getUint32(i),Ht[m]=e.getUint32(i+=4);for(let m=16;m<80;m++){const D=Vt[m-15]|0,I=Ht[m-15]|0,R=Y.rotrSH(D,I,1)^Y.rotrSH(D,I,8)^Y.shrSH(D,I,7),U=Y.rotrSL(D,I,1)^Y.rotrSL(D,I,8)^Y.shrSL(D,I,7),C=Vt[m-2]|0,w=Ht[m-2]|0,O=Y.rotrSH(C,w,19)^Y.rotrBH(C,w,61)^Y.shrSH(C,w,6),_=Y.rotrSL(C,w,19)^Y.rotrBL(C,w,61)^Y.shrSL(C,w,6),$=Y.add4L(U,_,Ht[m-7],Ht[m-16]),P=Y.add4H($,R,O,Vt[m-7],Vt[m-16]);Vt[m]=P|0,Ht[m]=$|0}let{Ah:r,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:h,Eh:l,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:E,Hl:v}=this;for(let m=0;m<80;m++){const D=Y.rotrSH(l,f,14)^Y.rotrSH(l,f,18)^Y.rotrBH(l,f,41),I=Y.rotrSL(l,f,14)^Y.rotrSL(l,f,18)^Y.rotrBL(l,f,41),R=l&p^~l&g,U=f&d^~f&y,C=Y.add5L(v,I,U,f0[m],Ht[m]),w=Y.add5H(C,E,D,R,l0[m],Vt[m]),O=C|0,_=Y.rotrSH(r,s,28)^Y.rotrBH(r,s,34)^Y.rotrBH(r,s,39),$=Y.rotrSL(r,s,28)^Y.rotrBL(r,s,34)^Y.rotrBL(r,s,39),P=r&n^r&a^n&a,k=s&o^s&c^o&c;E=g|0,v=y|0,g=p|0,y=d|0,p=l|0,d=f|0,{h:l,l:f}=Y.add(u|0,h|0,w|0,O|0),u=a|0,h=c|0,a=n|0,c=o|0,n=r|0,o=s|0;const x=Y.add3L(O,$,k);r=Y.add3H(x,w,_,P),s=x|0}({h:r,l:s}=Y.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:n,l:o}=Y.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:h}=Y.add(this.Dh|0,this.Dl|0,u|0,h|0),{h:l,l:f}=Y.add(this.Eh|0,this.El|0,l|0,f|0),{h:p,l:d}=Y.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Y.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:E,l:v}=Y.add(this.Hh|0,this.Hl|0,E|0,v|0),this.set(r,s,n,o,a,c,u,h,l,f,p,d,g,y,E,v)}roundClean(){Vt.fill(0),Ht.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};const p0=qg(()=>new d0);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wo=BigInt(0),Ch=BigInt(1),g0=BigInt(2);function Go(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yo(t){if(!Go(t))throw new Error("Uint8Array expected")}function Sn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const y0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jo(t){Yo(t);let e="";for(let i=0;i<t.length;i++)e+=y0[t[i]];return e}function Ph(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Wo:BigInt("0x"+t)}const Pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function oc(t){if(t>=Pt._0&&t<=Pt._9)return t-Pt._0;if(t>=Pt.A&&t<=Pt.F)return t-(Pt.A-10);if(t>=Pt.a&&t<=Pt.f)return t-(Pt.a-10)}function Rh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let s=0,n=0;s<i;s++,n+=2){const o=oc(t.charCodeAt(n)),a=oc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[s]=o*16+a}return r}function w0(t){return Ph(Jo(t))}function Ds(t){return Yo(t),Ph(Jo(Uint8Array.from(t).reverse()))}function Fh(t,e){return Rh(t.toString(16).padStart(e*2,"0"))}function oo(t,e){return Fh(t,e).reverse()}function Rt(t,e,i){let r;if(typeof e=="string")try{r=Rh(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Go(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof i=="number"&&s!==i)throw new Error(t+" of length "+i+" expected, got "+s);return r}function ac(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Yo(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}const Dn=t=>typeof t=="bigint"&&Wo<=t;function m0(t,e,i){return Dn(t)&&Dn(e)&&Dn(i)&&e<=t&&t<i}function hr(t,e,i,r){if(!m0(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function b0(t){let e;for(e=0;t>Wo;t>>=Ch,e+=1);return e}const v0=t=>(g0<<BigInt(t-1))-Ch,E0={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Go(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Zo(t,e,i={}){const r=(s,n,o)=>{const a=E0[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))r(s,n,!1);for(const[s,n]of Object.entries(i))r(s,n,!0);return t}function cc(t){const e=new WeakMap;return(i,...r)=>{const s=e.get(i);if(s!==void 0)return s;const n=t(i,...r);return e.set(i,n),n}}const xe=BigInt(0),pe=BigInt(1),mi=BigInt(2),_0=BigInt(3),ao=BigInt(4),uc=BigInt(5),hc=BigInt(8);function be(t,e){const i=t%e;return i>=xe?i:e+i}function x0(t,e,i){if(e<xe)throw new Error("invalid exponent, negatives unsupported");if(i<=xe)throw new Error("invalid modulus");if(i===pe)return xe;let r=pe;for(;e>xe;)e&pe&&(r=r*t%i),t=t*t%i,e>>=pe;return r}function vt(t,e,i){let r=t;for(;e-- >xe;)r*=r,r%=i;return r}function lc(t,e){if(t===xe)throw new Error("invert: expected non-zero number");if(e<=xe)throw new Error("invert: expected positive modulus, got "+e);let i=be(t,e),r=e,s=xe,n=pe;for(;i!==xe;){const o=r/i,a=r%i,c=s-n*o;r=i,i=a,s=n,n=c}if(r!==pe)throw new Error("invert: does not exist");return be(s,e)}function I0(t){const e=(t-pe)/mi;let i,r,s;for(i=t-pe,r=0;i%mi===xe;i/=mi,r++);for(s=mi;s<t&&x0(s,e,t)!==t-pe;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+pe)/ao;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const n=(i+pe)/mi;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,s),i),h=o.pow(a,n),l=o.pow(a,i);for(;!o.eql(l,o.ONE);){if(o.eql(l,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(l);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,pe<<BigInt(c-f-1));u=o.sqr(p),h=o.mul(h,p),l=o.mul(l,u),c=f}return h}}function S0(t){if(t%ao===_0){const e=(t+pe)/ao;return function(i,r){const s=i.pow(r,e);if(!i.eql(i.sqr(s),r))throw new Error("Cannot find square root");return s}}if(t%hc===uc){const e=(t-uc)/hc;return function(i,r){const s=i.mul(r,mi),n=i.pow(s,e),o=i.mul(r,n),a=i.mul(i.mul(o,mi),n),c=i.mul(o,i.sub(a,i.ONE));if(!i.eql(i.sqr(c),r))throw new Error("Cannot find square root");return c}}return I0(t)}const D0=(t,e)=>(be(t,e)&pe)===pe,A0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $0(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},i=A0.reduce((r,s)=>(r[s]="function",r),e);return Zo(t,i)}function O0(t,e,i){if(i<xe)throw new Error("invalid exponent, negatives unsupported");if(i===xe)return t.ONE;if(i===pe)return e;let r=t.ONE,s=e;for(;i>xe;)i&pe&&(r=t.mul(r,s)),s=t.sqr(s),i>>=pe;return r}function T0(t,e){const i=new Array(e.length),r=e.reduce((n,o,a)=>t.is0(o)?n:(i[a]=n,t.mul(n,o)),t.ONE),s=t.inv(r);return e.reduceRight((n,o,a)=>t.is0(o)?n:(i[a]=t.mul(n,i[a]),t.mul(n,o)),s),i}function Bh(t,e){const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function Uh(t,e,i=!1,r={}){if(t<=xe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=Bh(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:i,BITS:s,BYTES:n,MASK:v0(s),ZERO:xe,ONE:pe,create:c=>be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return xe<=c&&c<t},is0:c=>c===xe,isOdd:c=>(c&pe)===pe,neg:c=>be(-c,t),eql:(c,u)=>c===u,sqr:c=>be(c*c,t),add:(c,u)=>be(c+u,t),sub:(c,u)=>be(c-u,t),mul:(c,u)=>be(c*u,t),pow:(c,u)=>O0(a,c,u),div:(c,u)=>be(c*lc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>lc(c,t),sqrt:r.sqrt||(c=>(o||(o=S0(t)),o(a,c))),invertBatch:c=>T0(a,c),cmov:(c,u,h)=>h?u:c,toBytes:c=>i?oo(c,n):Fh(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return i?Ds(c):w0(c)}});return Object.freeze(a)}const fc=BigInt(0),hs=BigInt(1);function An(t,e){const i=e.negate();return t?i:e}function Nh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $n(t,e){Nh(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1);return{windows:i,windowSize:r}}function C0(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function P0(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const On=new WeakMap,kh=new WeakMap;function Tn(t){return kh.get(t)||1}function R0(t,e){return{constTimeNegate:An,hasPrecomputes(i){return Tn(i)!==1},unsafeLadder(i,r,s=t.ZERO){let n=i;for(;r>fc;)r&hs&&(s=s.add(n)),n=n.double(),r>>=hs;return s},precomputeWindow(i,r){const{windows:s,windowSize:n}=$n(r,e),o=[];let a=i,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let h=1;h<n;h++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(i,r,s){const{windows:n,windowSize:o}=$n(i,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**i-1),h=2**i,l=BigInt(i);for(let f=0;f<n;f++){const p=f*o;let d=Number(s&u);s>>=l,d>o&&(d-=h,s+=hs);const g=p,y=p+Math.abs(d)-1,E=f%2!==0,v=d<0;d===0?c=c.add(An(E,r[g])):a=a.add(An(v,r[y]))}return{p:a,f:c}},wNAFUnsafe(i,r,s,n=t.ZERO){const{windows:o,windowSize:a}=$n(i,e),c=BigInt(2**i-1),u=2**i,h=BigInt(i);for(let l=0;l<o;l++){const f=l*a;if(s===fc)break;let p=Number(s&c);if(s>>=h,p>a&&(p-=u,s+=hs),p===0)continue;let d=r[f+Math.abs(p)-1];p<0&&(d=d.negate()),n=n.add(d)}return n},getPrecomputes(i,r,s){let n=On.get(r);return n||(n=this.precomputeWindow(r,i),i!==1&&On.set(r,s(n))),n},wNAFCached(i,r,s){const n=Tn(i);return this.wNAF(n,this.getPrecomputes(n,i,s),r)},wNAFCachedUnsafe(i,r,s,n){const o=Tn(i);return o===1?this.unsafeLadder(i,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,i,s),r,n)},setWindowSize(i,r){Nh(r,e),kh.set(i,r),On.delete(i)}}}function F0(t,e,i,r){if(C0(i,t),P0(r,e),i.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=b0(BigInt(i.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let h=s;for(let l=u;l>=0;l-=o){c.fill(s);for(let p=0;p<r.length;p++){const d=r[p],g=Number(d>>BigInt(l)&BigInt(a));c[g]=c[g].add(i[p])}let f=s;for(let p=c.length-1,d=s;p>0;p--)d=d.add(c[p]),f=f.add(d);if(h=h.add(f),l!==0)for(let p=0;p<o;p++)h=h.double()}return h}function B0(t){return $0(t.Fp),Zo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const dt=BigInt(0),ze=BigInt(1),ls=BigInt(2),U0=BigInt(8),N0={zip215:!0};function k0(t){const e=B0(t);return Zo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function L0(t){const e=k0(t),{Fp:i,n:r,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=ls<<BigInt(a*8)-ze,h=i.create,l=Uh(e.n,e.nBitLength),f=e.uvRatio||((x,b)=>{try{return{isValid:!0,value:i.sqrt(x*i.inv(b))}}catch{return{isValid:!1,value:dt}}}),p=e.adjustScalarBytes||(x=>x),d=e.domain||((x,b,S)=>{if(Sn("phflag",S),b.length||S)throw new Error("Contexts/pre-hash are not supported");return x});function g(x,b){hr("coordinate "+x,b,dt,u)}function y(x){if(!(x instanceof m))throw new Error("ExtendedPoint expected")}const E=cc((x,b)=>{const{ex:S,ey:T,ez:A}=x,B=x.is0();b==null&&(b=B?U0:i.inv(A));const N=h(S*b),j=h(T*b),z=h(A*b);if(B)return{x:dt,y:ze};if(z!==ze)throw new Error("invZ was invalid");return{x:N,y:j}}),v=cc(x=>{const{a:b,d:S}=e;if(x.is0())throw new Error("bad point: ZERO");const{ex:T,ey:A,ez:B,et:N}=x,j=h(T*T),z=h(A*A),K=h(B*B),V=h(K*K),H=h(j*b),re=h(K*h(H+z)),ie=h(V+h(S*h(j*z)));if(re!==ie)throw new Error("bad point: equation left != right (1)");const J=h(T*A),fe=h(B*N);if(J!==fe)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(b,S,T,A){this.ex=b,this.ey=S,this.ez=T,this.et=A,g("x",b),g("y",S),g("z",T),g("t",A),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof m)throw new Error("extended point not allowed");const{x:S,y:T}=b||{};return g("x",S),g("y",T),new m(S,T,ze,h(S*T))}static normalizeZ(b){const S=i.invertBatch(b.map(T=>T.ez));return b.map((T,A)=>T.toAffine(S[A])).map(m.fromAffine)}static msm(b,S){return F0(m,l,b,S)}_setWindowSize(b){R.setWindowSize(this,b)}assertValidity(){v(this)}equals(b){y(b);const{ex:S,ey:T,ez:A}=this,{ex:B,ey:N,ez:j}=b,z=h(S*j),K=h(B*A),V=h(T*j),H=h(N*A);return z===K&&V===H}is0(){return this.equals(m.ZERO)}negate(){return new m(h(-this.ex),this.ey,this.ez,h(-this.et))}double(){const{a:b}=e,{ex:S,ey:T,ez:A}=this,B=h(S*S),N=h(T*T),j=h(ls*h(A*A)),z=h(b*B),K=S+T,V=h(h(K*K)-B-N),H=z+N,re=H-j,ie=z-N,J=h(V*re),fe=h(H*ie),Ie=h(V*ie),fi=h(re*H);return new m(J,fe,fi,Ie)}add(b){y(b);const{a:S,d:T}=e,{ex:A,ey:B,ez:N,et:j}=this,{ex:z,ey:K,ez:V,et:H}=b;if(S===BigInt(-1)){const Ta=h((B-A)*(K+z)),Ca=h((B+A)*(K-z)),yn=h(Ca-Ta);if(yn===dt)return this.double();const Pa=h(N*ls*H),Ra=h(j*ls*V),Fa=Ra+Pa,Ba=Ca+Ta,Ua=Ra-Pa,bd=h(Fa*yn),vd=h(Ba*Ua),Ed=h(Fa*Ua),_d=h(yn*Ba);return new m(bd,vd,_d,Ed)}const re=h(A*z),ie=h(B*K),J=h(j*T*H),fe=h(N*V),Ie=h((A+B)*(z+K)-re-ie),fi=fe-J,ns=fe+J,Bi=h(ie-S*re),gn=h(Ie*fi),yd=h(ns*Bi),wd=h(Ie*Bi),md=h(fi*ns);return new m(gn,yd,md,wd)}subtract(b){return this.add(b.negate())}wNAF(b){return R.wNAFCached(this,b,m.normalizeZ)}multiply(b){const S=b;hr("scalar",S,ze,r);const{p:T,f:A}=this.wNAF(S);return m.normalizeZ([T,A])[0]}multiplyUnsafe(b,S=m.ZERO){const T=b;return hr("scalar",T,dt,r),T===dt?I:this.is0()||T===ze?this:R.wNAFCachedUnsafe(this,T,m.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,r).is0()}toAffine(b){return E(this,b)}clearCofactor(){const{h:b}=e;return b===ze?this:this.multiplyUnsafe(b)}static fromHex(b,S=!1){const{d:T,a:A}=e,B=i.BYTES;b=Rt("pointHex",b,B),Sn("zip215",S);const N=b.slice(),j=b[B-1];N[B-1]=j&-129;const z=Ds(N),K=S?u:i.ORDER;hr("pointHex.y",z,dt,K);const V=h(z*z),H=h(V-ze),re=h(T*V-A);let{isValid:ie,value:J}=f(H,re);if(!ie)throw new Error("Point.fromHex: invalid y coordinate");const fe=(J&ze)===ze,Ie=(j&128)!==0;if(!S&&J===dt&&Ie)throw new Error("Point.fromHex: x=0 and x_0=1");return Ie!==fe&&(J=h(-J)),m.fromAffine({x:J,y:z})}static fromPrivateKey(b){return w(b).point}toRawBytes(){const{x:b,y:S}=this.toAffine(),T=oo(S,i.BYTES);return T[T.length-1]|=b&ze?128:0,T}toHex(){return Jo(this.toRawBytes())}}m.BASE=new m(e.Gx,e.Gy,ze,h(e.Gx*e.Gy)),m.ZERO=new m(dt,ze,ze,dt);const{BASE:D,ZERO:I}=m,R=R0(m,a*8);function U(x){return be(x,r)}function C(x){return U(Ds(x))}function w(x){const b=i.BYTES;x=Rt("private key",x,b);const S=Rt("hashed private key",n(x),2*b),T=p(S.slice(0,b)),A=S.slice(b,2*b),B=C(T),N=D.multiply(B),j=N.toRawBytes();return{head:T,prefix:A,scalar:B,point:N,pointBytes:j}}function O(x){return w(x).pointBytes}function _(x=new Uint8Array,...b){const S=ac(...b);return C(n(d(S,Rt("context",x),!!s)))}function $(x,b,S={}){x=Rt("message",x),s&&(x=s(x));const{prefix:T,scalar:A,pointBytes:B}=w(b),N=_(S.context,T,x),j=D.multiply(N).toRawBytes(),z=_(S.context,j,B,x),K=U(N+z*A);hr("signature.s",K,dt,r);const V=ac(j,oo(K,i.BYTES));return Rt("result",V,i.BYTES*2)}const P=N0;function k(x,b,S,T=P){const{context:A,zip215:B}=T,N=i.BYTES;x=Rt("signature",x,2*N),b=Rt("message",b),S=Rt("publicKey",S,N),B!==void 0&&Sn("zip215",B),s&&(b=s(b));const j=Ds(x.slice(N,2*N));let z,K,V;try{z=m.fromHex(S,B),K=m.fromHex(x.slice(0,N),B),V=D.multiplyUnsafe(j)}catch{return!1}if(!B&&z.isSmallOrder())return!1;const H=_(A,K.toRawBytes(),z.toRawBytes(),b);return K.add(z.multiplyUnsafe(H)).subtract(V).clearCofactor().equals(m.ZERO)}return D._setWindowSize(8),{CURVE:e,getPublicKey:O,sign:$,verify:k,ExtendedPoint:m,utils:{getExtendedPublicKey:w,randomPrivateKey:()=>o(i.BYTES),precompute(x=8,b=m.BASE){return b._setWindowSize(x),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const Qo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),dc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const M0=BigInt(1),pc=BigInt(2);BigInt(3);const q0=BigInt(5),j0=BigInt(8);function z0(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),n=Qo,o=t*t%n*t%n,a=vt(o,pc,n)*o%n,c=vt(a,M0,n)*t%n,u=vt(c,q0,n)*c%n,h=vt(u,e,n)*u%n,l=vt(h,i,n)*h%n,f=vt(l,r,n)*l%n,p=vt(f,s,n)*f%n,d=vt(p,s,n)*f%n,g=vt(d,e,n)*u%n;return{pow_p_5_8:vt(g,pc,n)*t%n,b2:o}}function K0(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function V0(t,e){const i=Qo,r=be(e*e*e,i),s=be(r*r*e,i),n=z0(t*s).pow_p_5_8;let o=be(t*r*n,i);const a=be(e*o*o,i),c=o,u=be(o*dc,i),h=a===t,l=a===be(-t,i),f=a===be(-t*dc,i);return h&&(o=c),(l||f)&&(o=u),D0(o,i)&&(o=be(-o,i)),{isValid:h||l,value:o}}const H0=(()=>Uh(Qo,void 0,!0))(),W0=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:H0,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:j0,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:p0,randomBytes:Oh,adjustScalarBytes:K0,uvRatio:V0}))(),Lh=(()=>L0(W0))(),G0="EdDSA",Y0="JWT",Bs=".",Qs="base64url",Mh="utf8",qh="utf8",J0=":",Z0="did",Q0="key",gc="base58btc",X0="z",ey="K36",ty=32;function Xo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function jh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Xo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function zh(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const i=jh(e);let r=0;for(const s of t)i.set(s,r),r+=s.length;return Xo(i)}function iy(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,E=0,v=d.length;E!==v&&d[E]===0;)E++,g++;for(var m=(v-E)*h+1>>>0,D=new Uint8Array(m);E!==v;){for(var I=d[E],R=0,U=m-1;(I!==0||R<y)&&U!==-1;U--,R++)I+=256*D[U]>>>0,D[U]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,E++}for(var C=m-y;C!==m&&D[C]===0;)C++;for(var w=c.repeat(g);C<m;++C)w+=t.charAt(D[C]);return w}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,E=0;d[g]===c;)y++,g++;for(var v=(d.length-g)*u+1>>>0,m=new Uint8Array(v);d[g];){var D=i[d.charCodeAt(g)];if(D===255)return;for(var I=0,R=v-1;(D!==0||I<E)&&R!==-1;R--,I++)D+=a*m[R]>>>0,m[R]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");E=I,g++}if(d[g]!==" "){for(var U=v-E;U!==v&&m[U]===0;)U++;for(var C=new Uint8Array(y+(v-U)),w=y;U!==v;)C[w++]=m[U++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:p}}var ry=iy,sy=ry;const Kh=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")},ny=t=>new TextEncoder().encode(t),oy=t=>new TextDecoder().decode(t);let ay=class{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},cy=class{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Vh(this,e)}},uy=class{constructor(e){this.decoders=e}or(e){return Vh(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Vh=(t,e)=>new uy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let hy=class{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new ay(e,i,r),this.decoder=new cy(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Xs=({name:t,prefix:e,encode:i,decode:r})=>new hy(t,e,i,r),Zr=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=sy(i,e);return Xs({prefix:t,name:e,encode:r,decode:n=>Kh(s(n))})},ly=(t,e,i,r)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[t[h]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},fy=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Te=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>Xs({prefix:e,name:t,encode(s){return fy(s,r,i)},decode(s){return ly(s,r,i,t)}}),dy=Xs({prefix:"\0",name:"identity",encode:t=>oy(t),decode:t=>ny(t)});var py=Object.freeze({__proto__:null,identity:dy});const gy=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yy=Object.freeze({__proto__:null,base2:gy});const wy=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var my=Object.freeze({__proto__:null,base8:wy});const by=Zr({prefix:"9",name:"base10",alphabet:"0123456789"});var vy=Object.freeze({__proto__:null,base10:by});const Ey=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),_y=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var xy=Object.freeze({__proto__:null,base16:Ey,base16upper:_y});const Iy=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Sy=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Dy=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ay=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$y=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Oy=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Ty=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Cy=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Py=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Ry=Object.freeze({__proto__:null,base32:Iy,base32upper:Sy,base32pad:Dy,base32padupper:Ay,base32hex:$y,base32hexupper:Oy,base32hexpad:Ty,base32hexpadupper:Cy,base32z:Py});const Fy=Zr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),By=Zr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Uy=Object.freeze({__proto__:null,base36:Fy,base36upper:By});const Ny=Zr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ky=Zr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ly=Object.freeze({__proto__:null,base58btc:Ny,base58flickr:ky});const My=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qy=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jy=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zy=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Ky=Object.freeze({__proto__:null,base64:My,base64pad:qy,base64url:jy,base64urlpad:zy});const Hh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Vy=Hh.reduce((t,e,i)=>(t[i]=e,t),[]),Hy=Hh.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function Wy(t){return t.reduce((e,i)=>(e+=Vy[i],e),"")}function Gy(t){const e=[];for(const i of t){const r=Hy[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const Yy=Xs({prefix:"🚀",name:"base256emoji",encode:Wy,decode:Gy});var Jy=Object.freeze({__proto__:null,base256emoji:Yy}),Zy=Wh,yc=128,Qy=127,Xy=~Qy,e1=Math.pow(2,31);function Wh(t,e,i){e=e||[],i=i||0;for(var r=i;t>=e1;)e[i++]=t&255|yc,t/=128;for(;t&Xy;)e[i++]=t&255|yc,t>>>=7;return e[i]=t|0,Wh.bytes=i-r+1,e}var t1=co,i1=128,wc=127;function co(t,r){var i=0,r=r||0,s=0,n=r,o,a=t.length;do{if(n>=a)throw co.bytes=0,new RangeError("Could not decode varint");o=t[n++],i+=s<28?(o&wc)<<s:(o&wc)*Math.pow(2,s),s+=7}while(o>=i1);return co.bytes=n-r,i}var r1=Math.pow(2,7),s1=Math.pow(2,14),n1=Math.pow(2,21),o1=Math.pow(2,28),a1=Math.pow(2,35),c1=Math.pow(2,42),u1=Math.pow(2,49),h1=Math.pow(2,56),l1=Math.pow(2,63),f1=function(t){return t<r1?1:t<s1?2:t<n1?3:t<o1?4:t<a1?5:t<c1?6:t<u1?7:t<h1?8:t<l1?9:10},d1={encode:Zy,decode:t1,encodingLength:f1},Gh=d1;const mc=(t,e,i=0)=>(Gh.encode(t,e,i),e),bc=t=>Gh.encodingLength(t),uo=(t,e)=>{const i=e.byteLength,r=bc(t),s=r+bc(i),n=new Uint8Array(s+i);return mc(t,n,0),mc(i,n,r),n.set(e,s),new p1(t,i,e,n)};let p1=class{constructor(e,i,r,s){this.code=e,this.size=i,this.digest=r,this.bytes=s}};const Yh=({name:t,code:e,encode:i})=>new g1(t,e,i);let g1=class{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?uo(this.code,i):i.then(r=>uo(this.code,r))}else throw Error("Unknown type, must be binary type")}};const Jh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),y1=Yh({name:"sha2-256",code:18,encode:Jh("SHA-256")}),w1=Yh({name:"sha2-512",code:19,encode:Jh("SHA-512")});var m1=Object.freeze({__proto__:null,sha256:y1,sha512:w1});const Zh=0,b1="identity",Qh=Kh,v1=t=>uo(Zh,Qh(t)),E1={code:Zh,name:b1,encode:Qh,digest:v1};var _1=Object.freeze({__proto__:null,identity:E1});new TextEncoder,new TextDecoder;const vc={...py,...yy,...my,...vy,...xy,...Ry,...Uy,...Ly,...Ky,...Jy};({...m1,..._1});function Xh(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Ec=Xh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Cn=Xh("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=jh(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),el={utf8:Ec,"utf-8":Ec,hex:vc.base16,latin1:Cn,ascii:Cn,binary:Cn,...vc};function en(t,e="utf8"){const i=el[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):i.encoder.encode(t).substring(1)}function er(t,e="utf8"){const i=el[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xo(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function _c(t){return Yi(en(er(t,Qs),Mh))}function Us(t){return en(er(Si(t),Mh),Qs)}function tl(t){const e=er(ey,gc),i=X0+en(zh([e,t]),gc);return[Z0,Q0,i].join(J0)}function x1(t){return en(t,Qs)}function I1(t){return er(t,Qs)}function S1(t){return er([Us(t.header),Us(t.payload)].join(Bs),qh)}function D1(t){return[Us(t.header),Us(t.payload),x1(t.signature)].join(Bs)}function ho(t){const e=t.split(Bs),i=_c(e[0]),r=_c(e[1]),s=I1(e[2]),n=er(e.slice(0,2).join(Bs),qh);return{header:i,payload:r,signature:s,data:n}}function xc(t=Oh(ty)){const e=Lh.getPublicKey(t);return{secretKey:zh([t,e]),publicKey:e}}async function A1(t,e,i,r,s=L.fromMiliseconds(Date.now())){const n={alg:G0,typ:Y0},o=tl(r.publicKey),a=s+i,c={iss:o,sub:t,aud:e,iat:s,exp:a},u=S1({header:n,payload:c}),h=Lh.sign(u,r.secretKey.slice(0,32));return D1({header:n,payload:c,signature:h})}var ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=il=ue.getLocation=ue.getLocationOrThrow=ea=ue.getNavigator=ue.getNavigatorOrThrow=Di=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function Ri(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=Ri;function tr(t){const e=Ri(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=tr;function $1(){return tr("document")}ue.getDocumentOrThrow=$1;function O1(){return Ri("document")}var Di=ue.getDocument=O1;function T1(){return tr("navigator")}ue.getNavigatorOrThrow=T1;function C1(){return Ri("navigator")}var ea=ue.getNavigator=C1;function P1(){return tr("location")}ue.getLocationOrThrow=P1;function R1(){return Ri("location")}var il=ue.getLocation=R1;function F1(){return tr("crypto")}ue.getCryptoOrThrow=F1;function B1(){return Ri("crypto")}ue.getCrypto=B1;function U1(){return tr("localStorage")}ue.getLocalStorageOrThrow=U1;function N1(){return Ri("localStorage")}ue.getLocalStorage=N1;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});var rl=ta.getWindowMetadata=void 0;const Ic=ue;function k1(){let t,e;try{t=Ic.getDocumentOrThrow(),e=Ic.getLocationOrThrow()}catch{return null}function i(){const l=t.getElementsByTagName("link"),f=[];for(let p=0;p<l.length;p++){const d=l[p],g=d.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=d.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let E=e.protocol+"//"+e.host;if(y.indexOf("/")===0)E+=y;else{const v=e.pathname.split("/");v.pop();const m=v.join("/");E+=m+"/"+y}f.push(E)}else if(y.indexOf("//")===0){const E=e.protocol+y;f.push(E)}else f.push(y)}}return f}function r(...l){const f=t.getElementsByTagName("meta");for(let p=0;p<f.length;p++){const d=f[p],g=["itemprop","property","name"].map(y=>d.getAttribute(y)).filter(y=>y?l.includes(y):!1);if(g.length&&g){const y=d.getAttribute("content");if(y)return y}}return""}function s(){let l=r("name","og:site_name","og:title","twitter:title");return l||(l=t.title),l}function n(){return r("description","og:description","twitter:description","keywords")}const o=s(),a=n(),c=e.origin,u=i();return{description:a,url:c,icons:u,name:o}}rl=ta.getWindowMetadata=k1;function Mr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function lo(t){return Mr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const sl="2.31.0";let Pn={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:i})=>e?`${t??"https://viem.sh"}${e}${i?`#${i}`:""}`:void 0,version:`viem@${sl}`};class Ai extends Error{constructor(e,i={}){const r=(()=>i.cause instanceof Ai?i.cause.details:i.cause?.message?i.cause.message:i.details)(),s=(()=>i.cause instanceof Ai&&i.cause.docsPath||i.docsPath)(),n=Pn.getDocsUrl?.({...i,docsPath:s}),o=[e||"An error occurred.","",...i.metaMessages?[...i.metaMessages,""]:[],...n?[`Docs: ${n}`]:[],...r?[`Details: ${r}`]:[],...Pn.version?[`Version: ${Pn.version}`]:[]].join(`
`);super(o,i.cause?{cause:i.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=s,this.metaMessages=i.metaMessages,this.name=i.name??this.name,this.shortMessage=e,this.version=sl}walk(e){return nl(this,e)}}function nl(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?nl(t.cause,e):e?null:t}class ol extends Ai{constructor({size:e,targetSize:i,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${i}).`,{name:"SizeExceedsPaddingSizeError"})}}function ir(t,{dir:e,size:i=32}={}){return typeof t=="string"?L1(t,{dir:e,size:i}):M1(t,{dir:e,size:i})}function L1(t,{dir:e,size:i=32}={}){if(i===null)return t;const r=t.replace("0x","");if(r.length>i*2)throw new ol({size:Math.ceil(r.length/2),targetSize:i,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](i*2,"0")}`}function M1(t,{dir:e,size:i=32}={}){if(i===null)return t;if(t.length>i)throw new ol({size:t.length,targetSize:i,type:"bytes"});const r=new Uint8Array(i);for(let s=0;s<i;s++){const n=e==="right";r[n?s:i-s-1]=t[n?s:t.length-s-1]}return r}class q1 extends Ai{constructor({max:e,min:i,signed:r,size:s,value:n}){super(`Number "${n}" is not in safe ${s?`${s*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${i} to ${e})`:`(above ${i})`}`,{name:"IntegerOutOfRangeError"})}}class j1 extends Ai{constructor({givenSize:e,maxSize:i}){super(`Size cannot exceed ${i} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function rr(t,{size:e}){if(lo(t)>e)throw new j1({givenSize:lo(t),maxSize:e})}function fo(t,e={}){const{signed:i}=e;e.size&&rr(t,{size:e.size});const r=BigInt(t);if(!i)return r;const s=(t.length-2)/2,n=(1n<<BigInt(s)*8n-1n)-1n;return r<=n?r:r-BigInt(`0x${"f".padStart(s*2,"f")}`)-1n}function z1(t,e={}){return Number(fo(t,e))}const K1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function po(t,e={}){return typeof t=="number"||typeof t=="bigint"?cl(t,e):typeof t=="string"?W1(t,e):typeof t=="boolean"?V1(t,e):al(t,e)}function V1(t,e={}){const i=`0x${Number(t)}`;return typeof e.size=="number"?(rr(i,{size:e.size}),ir(i,{size:e.size})):i}function al(t,e={}){let i="";for(let s=0;s<t.length;s++)i+=K1[t[s]];const r=`0x${i}`;return typeof e.size=="number"?(rr(r,{size:e.size}),ir(r,{dir:"right",size:e.size})):r}function cl(t,e={}){const{signed:i,size:r}=e,s=BigInt(t);let n;r?i?n=(1n<<BigInt(r)*8n-1n)-1n:n=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&i?-n-1n:0;if(n&&s>n||s<o){const c=typeof t=="bigint"?"n":"";throw new q1({max:n?`${n}${c}`:void 0,min:`${o}${c}`,signed:i,size:r,value:`${t}${c}`})}const a=`0x${(i&&s<0?(1n<<BigInt(r*8))+BigInt(s):s).toString(16)}`;return r?ir(a,{size:r}):a}const H1=new TextEncoder;function W1(t,e={}){const i=H1.encode(t);return al(i,e)}const G1=new TextEncoder;function Y1(t,e={}){return typeof t=="number"||typeof t=="bigint"?Z1(t,e):typeof t=="boolean"?J1(t,e):Mr(t)?ul(t,e):hl(t,e)}function J1(t,e={}){const i=new Uint8Array(1);return i[0]=Number(t),typeof e.size=="number"?(rr(i,{size:e.size}),ir(i,{size:e.size})):i}const Ft={zero:48,nine:57,A:65,F:70,a:97,f:102};function Sc(t){if(t>=Ft.zero&&t<=Ft.nine)return t-Ft.zero;if(t>=Ft.A&&t<=Ft.F)return t-(Ft.A-10);if(t>=Ft.a&&t<=Ft.f)return t-(Ft.a-10)}function ul(t,e={}){let i=t;e.size&&(rr(i,{size:e.size}),i=ir(i,{dir:"right",size:e.size}));let r=i.slice(2);r.length%2&&(r=`0${r}`);const s=r.length/2,n=new Uint8Array(s);for(let o=0,a=0;o<s;o++){const c=Sc(r.charCodeAt(a++)),u=Sc(r.charCodeAt(a++));if(c===void 0||u===void 0)throw new Ai(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);n[o]=c*16+u}return n}function Z1(t,e){const i=cl(t,e);return ul(i)}function hl(t,e={}){const i=G1.encode(t);return typeof e.size=="number"?(rr(i,{size:e.size}),ir(i,{dir:"right",size:e.size})):i}const fs=BigInt(2**32-1),Dc=BigInt(32);function Q1(t,e=!1){return e?{h:Number(t&fs),l:Number(t>>Dc&fs)}:{h:Number(t>>Dc&fs)|0,l:Number(t&fs)|0}}function X1(t,e=!1){const i=t.length;let r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:o,l:a}=Q1(t[n],e);[r[n],s[n]]=[o,a]}return[r,s]}const ew=(t,e,i)=>t<<i|e>>>32-i,tw=(t,e,i)=>e<<i|t>>>32-i,iw=(t,e,i)=>e<<i-32|t>>>64-i,rw=(t,e,i)=>t<<i-32|e>>>64-i,Mi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function sw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function qr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ji(t,...e){if(!sw(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function nw(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");qr(t.outputLen),qr(t.blockLen)}function go(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ll(t,e){Ji(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function ow(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ia(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function aw(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function cw(t,e){return t<<32-e|t>>>e}const uw=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function hw(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function lw(t){for(let e=0;e<t.length;e++)t[e]=hw(t[e]);return t}const Ac=uw?t=>t:lw;function fw(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ra(t){return typeof t=="string"&&(t=fw(t)),Ji(t),t}function dw(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Ji(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}class fl{}function dl(t){const e=r=>t().update(ra(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function pw(t=32){if(Mi&&typeof Mi.getRandomValues=="function")return Mi.getRandomValues(new Uint8Array(t));if(Mi&&typeof Mi.randomBytes=="function")return Uint8Array.from(Mi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const gw=BigInt(0),lr=BigInt(1),yw=BigInt(2),ww=BigInt(7),mw=BigInt(256),bw=BigInt(113),pl=[],gl=[],yl=[];for(let t=0,e=lr,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],pl.push(2*(5*r+i)),gl.push((t+1)*(t+2)/2%64);let s=gw;for(let n=0;n<7;n++)e=(e<<lr^(e>>ww)*bw)%mw,e&yw&&(s^=lr<<(lr<<BigInt(n))-lr);yl.push(s)}const wl=X1(yl,!0),vw=wl[0],Ew=wl[1],$c=(t,e,i)=>i>32?iw(t,e,i):ew(t,e,i),Oc=(t,e,i)=>i>32?rw(t,e,i):tw(t,e,i);function _w(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=i[c],h=i[c+1],l=$c(u,h,1)^i[a],f=Oc(u,h,1)^i[a+1];for(let p=0;p<50;p+=10)t[o+p]^=l,t[o+p+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=gl[o],c=$c(s,n,a),u=Oc(s,n,a),h=pl[o];s=t[h],n=t[h+1],t[h]=c,t[h+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=vw[r],t[1]^=Ew[r]}ia(i)}class sa extends fl{constructor(e,i,r,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=i,this.outputLen=r,this.enableXOF=s,this.rounds=n,qr(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=ow(this.state)}clone(){return this._cloneInto()}keccak(){Ac(this.state32),_w(this.state32,this.rounds),Ac(this.state32),this.posOut=0,this.pos=0}update(e){go(this),e=ra(e),Ji(e);const{blockLen:i,state:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:s}=this;e[r]^=i,i&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){go(this,!1),Ji(e),this.finish();const i=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(i.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return qr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ll(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ia(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new sa(i,r,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const xw=(t,e,i)=>dl(()=>new sa(e,t,i)),Iw=(()=>xw(1,136,256/8))();function ml(t,e){const i=e||"hex",r=Iw(Mr(t,{strict:!1})?Y1(t):t);return i==="bytes"?r:po(r)}class Sw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const i=super.get(e);return super.has(e)&&i!==void 0&&(this.delete(e),super.set(e,i)),i}set(e,i){if(super.set(e,i),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Rn=new Sw(8192);function Dw(t,e){if(Rn.has(`${t}.${e}`))return Rn.get(`${t}.${e}`);const i=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=ml(hl(i),"bytes"),s=(e?i.substring(`${e}0x`.length):i).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&s[o]&&(s[o]=s[o].toUpperCase()),(r[o>>1]&15)>=8&&s[o+1]&&(s[o+1]=s[o+1].toUpperCase());const n=`0x${s.join("")}`;return Rn.set(`${t}.${e}`,n),n}function Aw(t){const e=ml(`0x${t.substring(4)}`).substring(26);return Dw(`0x${e}`)}async function $w({hash:t,signature:e}){const i=Mr(t)?t:po(t),{secp256k1:r}=await Promise.resolve().then(()=>require("./secp256k1-12f82ee1.cjs"));return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:h,v:l,yParity:f}=e,p=Number(f??l),d=Tc(p);return new r.Signature(fo(u),fo(h)).addRecoveryBit(d)}const o=Mr(e)?e:po(e);if(lo(o)!==65)throw new Error("invalid signature length");const a=z1(`0x${o.slice(130)}`),c=Tc(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(i.substring(2)).toHex(!1)}`}function Tc(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Ow({hash:t,signature:e}){return Aw(await $w({hash:t,signature:e}))}function Tw(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const h=t.charAt(u),l=h.charCodeAt(0);if(e[l]!==255)throw new TypeError(h+" is ambiguous");e[l]=u}const i=t.length,r=t.charAt(0),s=Math.log(i)/Math.log(256),n=Math.log(256)/Math.log(i);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let h=0,l=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,h++;const d=(p-f)*n+1>>>0,g=new Uint8Array(d);for(;f!==p;){let v=u[f],m=0;for(let D=d-1;(v!==0||m<l)&&D!==-1;D--,m++)v+=256*g[D]>>>0,g[D]=v%i>>>0,v=v/i>>>0;if(v!==0)throw new Error("Non-zero carry");l=m,f++}let y=d-l;for(;y!==d&&g[y]===0;)y++;let E=r.repeat(h);for(;y<d;++y)E+=t.charAt(g[y]);return E}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let h=0,l=0,f=0;for(;u[h]===r;)l++,h++;const p=(u.length-h)*s+1>>>0,d=new Uint8Array(p);for(;h<u.length;){const v=u.charCodeAt(h);if(v>255)return;let m=e[v];if(m===255)return;let D=0;for(let I=p-1;(m!==0||D<f)&&I!==-1;I--,D++)m+=i*d[I]>>>0,d[I]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");f=D,h++}let g=p-f;for(;g!==p&&d[g]===0;)g++;const y=new Uint8Array(l+(p-g));let E=l;for(;g!==p;)y[E++]=d[g++];return y}function c(u){const h=a(u);if(h)return h;throw new Error("Non-base"+i+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Cw="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const Qr=Tw(Cw);function Pw(t){const e=t.length;let i=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if(s&4294967168)if(!(s&4294965248))i+=2;else{if(s>=55296&&s<=56319&&r<e){const n=t.charCodeAt(r);(n&64512)===56320&&(++r,s=((s&1023)<<10)+(n&1023)+65536)}s&4294901760?i+=4:i+=3}else{i++;continue}}return i}function Rw(t,e,i){const r=t.length;let s=i,n=0;for(;n<r;){let o=t.charCodeAt(n++);if(o&4294967168)if(!(o&4294965248))e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&n<r){const a=t.charCodeAt(n);(a&64512)===56320&&(++n,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128):(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128)}else{e[s++]=o;continue}e[s++]=o&63|128}}const Fw=new TextEncoder,Bw=50;function Uw(t,e,i){Fw.encodeInto(t,e.subarray(i))}function Nw(t,e,i){t.length>Bw?Uw(t,e,i):Rw(t,e,i)}const kw=4096;function bl(t,e,i){let r=e;const s=r+i,n=[];let o="";for(;r<s;){const a=t[r++];if(!(a&128))n.push(a);else if((a&224)===192){const c=t[r++]&63;n.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;n.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,h=t[r++]&63;let l=(a&7)<<18|c<<12|u<<6|h;l>65535&&(l-=65536,n.push(l>>>10&1023|55296),l=56320|l&1023),n.push(l)}else n.push(a);n.length>=kw&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const Lw=new TextDecoder,Mw=200;function qw(t,e,i){const r=t.subarray(e,e+i);return Lw.decode(r)}function jw(t,e,i){return i>Mw?qw(t,e,i):bl(t,e,i)}class ds{constructor(e,i){this.type=e,this.data=i}}class tt extends Error{constructor(e){super(e);const i=Object.create(tt.prototype);Object.setPrototypeOf(this,i),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:tt.name})}}const fr=4294967295;function zw(t,e,i){const r=i/4294967296,s=i;t.setUint32(e,r),t.setUint32(e+4,s)}function vl(t,e,i){const r=Math.floor(i/4294967296),s=i;t.setUint32(e,r),t.setUint32(e+4,s)}function El(t,e){const i=t.getInt32(e),r=t.getUint32(e+4);return i*4294967296+r}function Kw(t,e){const i=t.getUint32(e),r=t.getUint32(e+4);return i*4294967296+r}const Vw=-1,Hw=4294967296-1,Ww=17179869184-1;function Gw({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Ww)if(e===0&&t<=Hw){const i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,t),i}else{const i=t/4294967296,r=t&4294967295,s=new Uint8Array(8),n=new DataView(s.buffer);return n.setUint32(0,e<<2|i&3),n.setUint32(4,r),s}else{const i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,e),vl(r,4,t),i}}function Yw(t){const e=t.getTime(),i=Math.floor(e/1e3),r=(e-i*1e3)*1e6,s=Math.floor(r/1e9);return{sec:i+s,nsec:r-s*1e9}}function Jw(t){if(t instanceof Date){const e=Yw(t);return Gw(e)}else return null}function Zw(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const i=e.getUint32(0),r=e.getUint32(4),s=(i&3)*4294967296+r,n=i>>>2;return{sec:s,nsec:n}}case 12:{const i=El(e,4),r=e.getUint32(0);return{sec:i,nsec:r}}default:throw new tt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Qw(t){const e=Zw(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Xw={type:Vw,encode:Jw,decode:Qw};class Ns{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Xw)}register({type:e,encode:i,decode:r}){if(e>=0)this.encoders[e]=i,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=i,this.builtInDecoders[s]=r}}tryToEncode(e,i){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const n=s(e,i);if(n!=null){const o=-1-r;return new ds(o,n)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const n=s(e,i);if(n!=null){const o=r;return new ds(o,n)}}}return e instanceof ds?e:null}decode(e,i,r){const s=i<0?this.builtInDecoders[-1-i]:this.decoders[i];return s?s(e,i,r):new ds(i,e)}}Ns.defaultCodec=new Ns;function em(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function yo(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):em(t)?new Uint8Array(t):Uint8Array.from(t)}const tm=100,im=2048;let rm=class _l{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Ns.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??tm,this.initialBufferSize=e?.initialBufferSize??im,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new _l({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,i){if(i>this.maxDepth)throw new Error(`Too deep objects in depth ${i}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,i)}ensureBufferSizeToWrite(e){const i=this.pos+e;this.view.byteLength<i&&this.resizeBuffer(i*2)}resizeBuffer(e){const i=new ArrayBuffer(e),r=new Uint8Array(i),s=new DataView(i);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=Pw(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Nw(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,i){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,i);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,i);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const i=e.byteLength;if(i<256)this.writeU8(196),this.writeU8(i);else if(i<65536)this.writeU8(197),this.writeU16(i);else if(i<4294967296)this.writeU8(198),this.writeU32(i);else throw new Error(`Too large binary: ${i}`);const r=yo(e);this.writeU8a(r)}encodeArray(e,i){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const s of e)this.doEncode(s,i+1)}countWithoutUndefined(e,i){let r=0;for(const s of i)e[s]!==void 0&&r++;return r}encodeMap(e,i){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const n of r){const o=e[n];this.ignoreUndefined&&o===void 0||(this.encodeString(n),this.doEncode(o,i+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const i=e.data.length;if(i===1)this.writeU8(212);else if(i===2)this.writeU8(213);else if(i===4)this.writeU8(214);else if(i===8)this.writeU8(215);else if(i===16)this.writeU8(216);else if(i<256)this.writeU8(199),this.writeU8(i);else if(i<65536)this.writeU8(200),this.writeU16(i);else if(i<4294967296)this.writeU8(201),this.writeU32(i);else throw new Error(`Too large extension object: ${i}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const i=e.length;this.ensureBufferSizeToWrite(i),this.bytes.set(e,this.pos),this.pos+=i}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),zw(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),vl(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};function sm(t,e){return new rm(e).encodeSharedRef(t)}function Fn(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const nm=16,om=16;class am{constructor(e=nm,i=om){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=i,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,i,r){const s=this.caches[r-1];e:for(const n of s){const o=n.bytes;for(let a=0;a<r;a++)if(o[a]!==e[i+a])continue e;return n.str}return null}store(e,i){const r=this.caches[e.length-1],s={bytes:e,str:i};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,i,r){const s=this.find(e,i,r);if(s!=null)return this.hit++,s;this.miss++;const n=bl(e,i,r),o=Uint8Array.prototype.slice.call(e,i,i+r);return this.store(o,n),n}}const wo="array",$r="map_key",xl="map_value",cm=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new tt("The type of key must be string or number but "+typeof t)};class um{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const i=this.getUninitializedStateFromPool();i.type=wo,i.position=0,i.size=e,i.array=new Array(e)}pushMapState(e){const i=this.getUninitializedStateFromPool();i.type=$r,i.readCount=0,i.size=e,i.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===wo){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===$r||e.type===xl){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const dr=-1,na=new DataView(new ArrayBuffer(0)),hm=new Uint8Array(na.buffer);try{na.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Cc=new RangeError("Insufficient data"),lm=new am;let fm=class Il{constructor(e){this.totalPos=0,this.pos=0,this.view=na,this.bytes=hm,this.headByte=dr,this.stack=new um,this.entered=!1,this.extensionCodec=e?.extensionCodec??Ns.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??fr,this.maxBinLength=e?.maxBinLength??fr,this.maxArrayLength=e?.maxArrayLength??fr,this.maxMapLength=e?.maxMapLength??fr,this.maxExtLength=e?.maxExtLength??fr,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:lm,this.mapKeyConverter=e?.mapKeyConverter??cm}clone(){return new Il({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=dr,this.stack.reset()}setBuffer(e){const i=yo(e);this.bytes=i,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===dr&&!this.hasRemaining(1))this.setBuffer(e);else{const i=this.bytes.subarray(this.pos),r=yo(e),s=new Uint8Array(i.length+r.length);s.set(i),s.set(r,i.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:i,pos:r}=this;return new RangeError(`Extra ${i.byteLength-r} of ${i.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const i=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return i}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let i=!1,r;for await(const a of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),i=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:s,pos:n,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Fn(s)} at ${o} (${n} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,i){if(this.entered){yield*this.clone().decodeMultiAsync(e,i);return}try{this.entered=!0;let r=i,s=-1;for await(const n of e){if(i&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let i;if(e>=224)i=e-256;else if(e<192)if(e<128)i=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else{const s=e-160;i=this.decodeString(s,0)}else if(e===192)i=null;else if(e===194)i=!1;else if(e===195)i=!0;else if(e===202)i=this.readF32();else if(e===203)i=this.readF64();else if(e===204)i=this.readU8();else if(e===205)i=this.readU16();else if(e===206)i=this.readU32();else if(e===207)this.useBigInt64?i=this.readU64AsBigInt():i=this.readU64();else if(e===208)i=this.readI8();else if(e===209)i=this.readI16();else if(e===210)i=this.readI32();else if(e===211)this.useBigInt64?i=this.readI64AsBigInt():i=this.readI64();else if(e===217){const s=this.lookU8();i=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();i=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();i=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else i=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else i={}}else if(e===196){const s=this.lookU8();i=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();i=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();i=this.decodeBinary(s,4)}else if(e===212)i=this.decodeExtension(1,0);else if(e===213)i=this.decodeExtension(2,0);else if(e===214)i=this.decodeExtension(4,0);else if(e===215)i=this.decodeExtension(8,0);else if(e===216)i=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();i=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();i=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();i=this.decodeExtension(s,4)}else throw new tt(`Unrecognized type byte: ${Fn(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===wo)if(s.array[s.position]=i,s.position++,s.position===s.size)i=s.array,r.release(s);else continue e;else if(s.type===$r){if(i==="__proto__")throw new tt("The key __proto__ is not allowed");s.key=this.mapKeyConverter(i),s.type=xl;continue e}else if(s.map[s.key]=i,s.readCount++,s.readCount===s.size)i=s.map,r.release(s);else{s.key=null,s.type=$r;continue e}}return i}}readHeadByte(){return this.headByte===dr&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=dr}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new tt(`Unrecognized array type byte: ${Fn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new tt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new tt(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,i){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,i):this.decodeBinary(e,i)}decodeUtf8String(e,i){if(e>this.maxStrLength)throw new tt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+i+e)throw Cc;const r=this.pos+i;let s;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?s=this.keyDecoder.decode(this.bytes,r,e):s=jw(this.bytes,r,e),this.pos+=i+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===$r:!1}decodeBinary(e,i){if(e>this.maxBinLength)throw new tt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+i))throw Cc;const r=this.pos+i,s=this.bytes.subarray(r,r+e);return this.pos+=i+e,s}decodeExtension(e,i){if(e>this.maxExtLength)throw new tt(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+i),s=this.decodeBinary(e,i+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Kw(this.view,this.pos);return this.pos+=8,e}readI64(){const e=El(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}};function dm(t,e){return new fm(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Sl(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(i=>typeof i=="string"):e.every(i=>Number.isSafeInteger(i)):!1}function ks(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function oa(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function mo(t){if(!Array.isArray(t))throw new Error("array expected")}function Ls(t,e){if(!Sl(!0,e))throw new Error(`${t}: array of strings expected`)}function gm(t,e){if(!Sl(!1,e))throw new Error(`${t}: array of numbers expected`)}function ym(...t){const e=n=>n,i=(n,o)=>a=>n(o(a)),r=t.map(n=>n.encode).reduceRight(i,e),s=t.map(n=>n.decode).reduce(i,e);return{encode:r,decode:s}}function wm(t){const e=typeof t=="string"?t.split(""):t,i=e.length;Ls("alphabet",e);const r=new Map(e.map((s,n)=>[s,n]));return{encode:s=>(mo(s),s.map(n=>{if(!Number.isSafeInteger(n)||n<0||n>=i)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);return e[n]})),decode:s=>(mo(s),s.map(n=>{ks("alphabet.decode",n);const o=r.get(n);if(o===void 0)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return o}))}}function mm(t=""){return ks("join",t),{encode:e=>(Ls("join.decode",e),e.join(t)),decode:e=>(ks("join.decode",e),e.split(t))}}function bm(t,e="="){return oa(t),ks("padding",e),{encode(i){for(Ls("padding.encode",i);i.length*t%8;)i.push(e);return i},decode(i){Ls("padding.decode",i);let r=i.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&i[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return i.slice(0,r)}}}const Dl=(t,e)=>e===0?t:Dl(e,t%e),Ms=(t,e)=>t+(e-Dl(t,e)),Bn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Pc(t,e,i,r){if(mo(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(i<=0||i>32)throw new Error(`convertRadix2: wrong to=${i}`);if(Ms(e,i)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${i} carryBits=${Ms(e,i)}`);let s=0,n=0;const o=Bn[e],a=Bn[i]-1,c=[];for(const u of t){if(oa(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(s=s<<e|u,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=i;n-=i)c.push((s>>n-i&a)>>>0);const h=Bn[n];if(h===void 0)throw new Error("invalid carry");s&=h-1}if(s=s<<i-n&a,!r&&n>=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&n>0&&c.push(s>>>0),c}function vm(t,e=!1){if(oa(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ms(8,t)>32||Ms(t,8)>32)throw new Error("radix2: carry overflow");return{encode:i=>{if(!pm(i))throw new Error("radix2.encode input should be Uint8Array");return Pc(Array.from(i),8,t,!e)},decode:i=>(gm("radix2.decode",i),Uint8Array.from(Pc(i,t,8,e)))}}const Em=ym(vm(5),wm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),bm(5),mm(""));function aa(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Al(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?aa(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Or(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const i=Al(e);let r=0;for(const s of t)i.set(s,r),r+=s.length;return aa(i)}function _m(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,E=0,v=d.length;E!==v&&d[E]===0;)E++,g++;for(var m=(v-E)*h+1>>>0,D=new Uint8Array(m);E!==v;){for(var I=d[E],R=0,U=m-1;(I!==0||R<y)&&U!==-1;U--,R++)I+=256*D[U]>>>0,D[U]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,E++}for(var C=m-y;C!==m&&D[C]===0;)C++;for(var w=c.repeat(g);C<m;++C)w+=t.charAt(D[C]);return w}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,E=0;d[g]===c;)y++,g++;for(var v=(d.length-g)*u+1>>>0,m=new Uint8Array(v);d[g];){var D=i[d.charCodeAt(g)];if(D===255)return;for(var I=0,R=v-1;(D!==0||I<E)&&R!==-1;R--,I++)D+=a*m[R]>>>0,m[R]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");E=I,g++}if(d[g]!==" "){for(var U=v-E;U!==v&&m[U]===0;)U++;for(var C=new Uint8Array(y+(v-U)),w=y;U!==v;)C[w++]=m[U++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:p}}var xm=_m,Im=xm;const Sm=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")},Dm=t=>new TextEncoder().encode(t),Am=t=>new TextDecoder().decode(t);class $m{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Om{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return $l(this,e)}}class Tm{constructor(e){this.decoders=e}or(e){return $l(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const $l=(t,e)=>new Tm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Cm{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new $m(e,i,r),this.decoder=new Om(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const tn=({name:t,prefix:e,encode:i,decode:r})=>new Cm(t,e,i,r),Xr=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=Im(i,e);return tn({prefix:t,name:e,encode:r,decode:n=>Sm(s(n))})},Pm=(t,e,i,r)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[t[h]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Rm=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Ce=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>tn({prefix:e,name:t,encode(s){return Rm(s,r,i)},decode(s){return Pm(s,r,i,t)}}),Fm=tn({prefix:"\0",name:"identity",encode:t=>Am(t),decode:t=>Dm(t)}),Bm=Object.freeze(Object.defineProperty({__proto__:null,identity:Fm},Symbol.toStringTag,{value:"Module"})),Um=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Nm=Object.freeze(Object.defineProperty({__proto__:null,base2:Um},Symbol.toStringTag,{value:"Module"})),km=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Lm=Object.freeze(Object.defineProperty({__proto__:null,base8:km},Symbol.toStringTag,{value:"Module"})),Mm=Xr({prefix:"9",name:"base10",alphabet:"0123456789"}),qm=Object.freeze(Object.defineProperty({__proto__:null,base10:Mm},Symbol.toStringTag,{value:"Module"})),jm=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),zm=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Km=Object.freeze(Object.defineProperty({__proto__:null,base16:jm,base16upper:zm},Symbol.toStringTag,{value:"Module"})),Vm=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Hm=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Wm=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Gm=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ym=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Jm=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Zm=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Qm=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Xm=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),eb=Object.freeze(Object.defineProperty({__proto__:null,base32:Vm,base32hex:Ym,base32hexpad:Zm,base32hexpadupper:Qm,base32hexupper:Jm,base32pad:Wm,base32padupper:Gm,base32upper:Hm,base32z:Xm},Symbol.toStringTag,{value:"Module"})),tb=Xr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ib=Xr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),rb=Object.freeze(Object.defineProperty({__proto__:null,base36:tb,base36upper:ib},Symbol.toStringTag,{value:"Module"})),sb=Xr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),nb=Xr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),ob=Object.freeze(Object.defineProperty({__proto__:null,base58btc:sb,base58flickr:nb},Symbol.toStringTag,{value:"Module"})),ab=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),cb=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),ub=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),hb=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),lb=Object.freeze(Object.defineProperty({__proto__:null,base64:ab,base64pad:cb,base64url:ub,base64urlpad:hb},Symbol.toStringTag,{value:"Module"})),Ol=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),fb=Ol.reduce((t,e,i)=>(t[i]=e,t),[]),db=Ol.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function pb(t){return t.reduce((e,i)=>(e+=fb[i],e),"")}function gb(t){const e=[];for(const i of t){const r=db[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const yb=tn({prefix:"🚀",name:"base256emoji",encode:pb,decode:gb}),wb=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:yb},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const Rc={...Bm,...Nm,...Lm,...qm,...Km,...eb,...rb,...ob,...lb,...wb};function Tl(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Fc=Tl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Un=Tl("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=Al(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),Cl={utf8:Fc,"utf-8":Fc,hex:Rc.base16,latin1:Un,ascii:Un,binary:Un,...Rc};function ht(t,e="utf8"){const i=Cl[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?aa(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function Ze(t,e="utf8"){const i=Cl[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):i.encoder.encode(t).substring(1)}const mb={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},bb="Input must be an string, Buffer or Uint8Array";function vb(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(bb);return e}function Eb(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function ps(t){return(4294967296+t).toString(16).substring(1)}function _b(t,e,i){let r=`
`+t+" = ";for(let s=0;s<e.length;s+=2){if(i===32)r+=ps(e[s]).toUpperCase(),r+=" ",r+=ps(e[s+1]).toUpperCase();else if(i===64)r+=ps(e[s+1]).toUpperCase(),r+=ps(e[s]).toUpperCase();else throw new Error("Invalid size "+i);s%6===4?r+=`
`+new Array(t.length+4).join(" "):s<e.length-2&&(r+=" ")}console.log(r)}function xb(t,e,i){let r=new Date().getTime();const s=new Uint8Array(e);for(let o=0;o<e;o++)s[o]=o%256;const n=new Date().getTime();console.log("Generated random input in "+(n-r)+"ms"),r=n;for(let o=0;o<i;o++){const a=t(s),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var Pl={normalizeInput:vb,toHex:Eb,debugPrint:_b,testSpeed:xb};const As=Pl;function gs(t,e,i){const r=t[e]+t[i];let s=t[e+1]+t[i+1];r>=4294967296&&s++,t[e]=r,t[e+1]=s}function Bc(t,e,i,r){let s=t[e]+i;i<0&&(s+=4294967296);let n=t[e+1]+r;s>=4294967296&&n++,t[e]=s,t[e+1]=n}function Rl(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Wt(t,e,i,r,s,n){const o=Ir[s],a=Ir[s+1],c=Ir[n],u=Ir[n+1];gs(G,t,e),Bc(G,t,o,a);let h=G[r]^G[t],l=G[r+1]^G[t+1];G[r]=l,G[r+1]=h,gs(G,i,r),h=G[e]^G[i],l=G[e+1]^G[i+1],G[e]=h>>>24^l<<8,G[e+1]=l>>>24^h<<8,gs(G,t,e),Bc(G,t,c,u),h=G[r]^G[t],l=G[r+1]^G[t+1],G[r]=h>>>16^l<<16,G[r+1]=l>>>16^h<<16,gs(G,i,r),h=G[e]^G[i],l=G[e+1]^G[i+1],G[e]=l>>>31^h<<1,G[e+1]=h>>>31^l<<1}const Fl=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Ib=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Re=new Uint8Array(Ib.map(function(t){return t*2})),G=new Uint32Array(32),Ir=new Uint32Array(32);function Bl(t,e){let i=0;for(i=0;i<16;i++)G[i]=t.h[i],G[i+16]=Fl[i];for(G[24]=G[24]^t.t,G[25]=G[25]^t.t/4294967296,e&&(G[28]=~G[28],G[29]=~G[29]),i=0;i<32;i++)Ir[i]=Rl(t.b,4*i);for(i=0;i<12;i++)Wt(0,8,16,24,Re[i*16+0],Re[i*16+1]),Wt(2,10,18,26,Re[i*16+2],Re[i*16+3]),Wt(4,12,20,28,Re[i*16+4],Re[i*16+5]),Wt(6,14,22,30,Re[i*16+6],Re[i*16+7]),Wt(0,10,20,30,Re[i*16+8],Re[i*16+9]),Wt(2,12,22,24,Re[i*16+10],Re[i*16+11]),Wt(4,14,16,26,Re[i*16+12],Re[i*16+13]),Wt(6,8,18,28,Re[i*16+14],Re[i*16+15]);for(i=0;i<16;i++)t.h[i]=t.h[i]^G[i]^G[i+16]}const Gt=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function Ul(t,e,i,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(i&&i.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const s={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};Gt.fill(0),Gt[0]=t,e&&(Gt[1]=e.length),Gt[2]=1,Gt[3]=1,i&&Gt.set(i,32),r&&Gt.set(r,48);for(let n=0;n<16;n++)s.h[n]=Fl[n]^Rl(Gt,n*4);return e&&(ca(s,e),s.c=128),s}function ca(t,e){for(let i=0;i<e.length;i++)t.c===128&&(t.t+=t.c,Bl(t,!1),t.c=0),t.b[t.c++]=e[i]}function Nl(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;Bl(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3);return e}function kl(t,e,i,r,s){i=i||64,t=As.normalizeInput(t),r&&(r=As.normalizeInput(r)),s&&(s=As.normalizeInput(s));const n=Ul(i,e,r,s);return ca(n,t),Nl(n)}function Sb(t,e,i,r,s){const n=kl(t,e,i,r,s);return As.toHex(n)}var Db={blake2b:kl,blake2bHex:Sb,blake2bInit:Ul,blake2bUpdate:ca,blake2bFinal:Nl};const Ll=Pl;function Ab(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Yt(t,e,i,r,s,n){te[t]=te[t]+te[e]+s,te[r]=ys(te[r]^te[t],16),te[i]=te[i]+te[r],te[e]=ys(te[e]^te[i],12),te[t]=te[t]+te[e]+n,te[r]=ys(te[r]^te[t],8),te[i]=te[i]+te[r],te[e]=ys(te[e]^te[i],7)}function ys(t,e){return t>>>e^t<<32-e}const Ml=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fe=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),te=new Uint32Array(16),Se=new Uint32Array(16);function ql(t,e){let i=0;for(i=0;i<8;i++)te[i]=t.h[i],te[i+8]=Ml[i];for(te[12]^=t.t,te[13]^=t.t/4294967296,e&&(te[14]=~te[14]),i=0;i<16;i++)Se[i]=Ab(t.b,4*i);for(i=0;i<10;i++)Yt(0,4,8,12,Se[Fe[i*16+0]],Se[Fe[i*16+1]]),Yt(1,5,9,13,Se[Fe[i*16+2]],Se[Fe[i*16+3]]),Yt(2,6,10,14,Se[Fe[i*16+4]],Se[Fe[i*16+5]]),Yt(3,7,11,15,Se[Fe[i*16+6]],Se[Fe[i*16+7]]),Yt(0,5,10,15,Se[Fe[i*16+8]],Se[Fe[i*16+9]]),Yt(1,6,11,12,Se[Fe[i*16+10]],Se[Fe[i*16+11]]),Yt(2,7,8,13,Se[Fe[i*16+12]],Se[Fe[i*16+13]]),Yt(3,4,9,14,Se[Fe[i*16+14]],Se[Fe[i*16+15]]);for(i=0;i<8;i++)t.h[i]^=te[i]^te[i+8]}function jl(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const i=e?e.length:0;if(e&&!(i>0&&i<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(Ml),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^i<<8^t,i>0&&(ua(r,e),r.c=64),r}function ua(t,e){for(let i=0;i<e.length;i++)t.c===64&&(t.t+=t.c,ql(t,!1),t.c=0),t.b[t.c++]=e[i]}function zl(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;ql(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3)&255;return e}function Kl(t,e,i){i=i||32,t=Ll.normalizeInput(t);const r=jl(i,e);return ua(r,t),zl(r)}function $b(t,e,i){const r=Kl(t,e,i);return Ll.toHex(r)}var Ob={blake2s:Kl,blake2sHex:$b,blake2sInit:jl,blake2sUpdate:ua,blake2sFinal:zl};const pr=Db,gr=Ob;var Tb={blake2b:pr.blake2b,blake2bHex:pr.blake2bHex,blake2bInit:pr.blake2bInit,blake2bUpdate:pr.blake2bUpdate,blake2bFinal:pr.blake2bFinal,blake2s:gr.blake2s,blake2sHex:gr.blake2sHex,blake2sInit:gr.blake2sInit,blake2sUpdate:gr.blake2sUpdate,blake2sFinal:gr.blake2sFinal};const ha=":";function $s(t){const[e,i]=t.split(ha);return{namespace:e,reference:i}}function Cb(t){const{namespace:e,reference:i}=t;return[e,i].join(ha)}function Pb(t){const[e,i,r]=t.split(ha);return{namespace:e,reference:i,address:r}}function Rb(t,e){const i=[];return t.forEach(r=>{const s=e(r);i.includes(s)||i.push(s)}),i}function Fb(t){const{namespace:e,reference:i}=Pb(t);return Cb({namespace:e,reference:i})}function Bb(t){return Rb(t,Fb)}function Vl(t,e=[]){const i=[];return Object.keys(t).forEach(r=>{if(e.length&&!e.includes(r))return;const s=t[r];i.push(...s.accounts)}),i}function Hl(t,e=[]){const i=[];return Object.keys(t).forEach(r=>{if(e.length&&!e.includes(r))return;const s=t[r];i.push(...Bb(s.accounts))}),i}function Ub(t,e=[]){const i=[];return Object.keys(t).forEach(r=>{if(e.length&&!e.includes(r))return;const s=t[r];i.push(...la(r,s))}),i}function la(t,e){return t.includes(":")?[t]:e.chains||[]}var Nb=Object.defineProperty,kb=Object.defineProperties,Lb=Object.getOwnPropertyDescriptors,Uc=Object.getOwnPropertySymbols,Mb=Object.prototype.hasOwnProperty,qb=Object.prototype.propertyIsEnumerable,bo=(t,e,i)=>e in t?Nb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Nc=(t,e)=>{for(var i in e||(e={}))Mb.call(e,i)&&bo(t,i,e[i]);if(Uc)for(var i of Uc(e))qb.call(e,i)&&bo(t,i,e[i]);return t},jb=(t,e)=>kb(t,Lb(e)),kc=(t,e,i)=>bo(t,typeof e!="symbol"?e+"":e,i);const zb="ReactNative",it={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Kb="js";function qs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function li(){return!Di()&&!!ea()&&navigator.product===zb}function Vb(){return li()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Hb(){return li()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function sr(){return!qs()&&!!ea()&&!!Di()}function es(){return li()?it.reactNative:qs()?it.node:sr()?it.browser:it.unknown}function Lc(){var t;try{return li()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Wb(t,e){const i=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const s=e[r];s!==void 0&&i.set(r,s)}return i.toString()}function Gb(t){var e,i;const r=Wl();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),jb(Nc(Nc({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(i=t?.icons)!=null&&i.length&&t.icons.length>0?t.icons:r.icons})}catch(s){return console.warn("Error populating app metadata",s),t||r}}function Wl(){return rl()||{name:"",description:"",url:"",icons:[""]}}function Yb(){if(es()===it.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:i,Version:r}=global.Platform;return[i,r].join("-")}const t=yt.detect();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function Jb(){var t;const e=es();return e===it.browser?[e,((t=il())==null?void 0:t.host)||"unknown"].join(":"):e}function Gl(t,e,i){const r=Yb(),s=Jb();return[[t,e].join("-"),[Kb,i].join("-"),r,s].join("/")}function Zb({protocol:t,version:e,relayUrl:i,sdkVersion:r,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=i.split("?"),h=Gl(t,e,r),l={auth:s,ua:h,projectId:n,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=Wb(u[1]||"",l);return u[0]+"?"+f}function vi(t,e){return t.filter(i=>e.includes(i)).length===t.length}function vo(t){return Object.fromEntries(t.entries())}function Eo(t){return new Map(Object.entries(t))}function wi(t=L.FIVE_MINUTES,e){const i=L.toMiliseconds(t||L.FIVE_MINUTES);let r,s,n,o;return{resolve:a=>{n&&r&&(clearTimeout(n),r(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},i),r=a,s=c})}}function Ot(t,e,i){return new Promise(async(r,s)=>{const n=setTimeout(()=>s(new Error(i)),e);try{const o=await t;r(o)}catch(o){s(o)}clearTimeout(n)})}function Yl(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Qb(t){return Yl("topic",t)}function Xb(t){return Yl("id",t)}function Jl(t){const[e,i]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof i=="string")r.topic=i;else if(e==="id"&&Number.isInteger(Number(i)))r.id=Number(i);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${i}`);return r}function me(t,e){return L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function ri(t){return Date.now()>=L.toMiliseconds(t)}function se(t,e){return`${t}${e?`:${e}`:""}`}function Ii(t=[],e=[]){return[...new Set([...t,...e])]}async function ev({id:t,topic:e,wcDeepLink:i}){var r;try{if(!i)return;const s=typeof i=="string"?JSON.parse(i):i,n=s?.href;if(typeof n!="string")return;const o=tv(n,t,e),a=es();if(a===it.browser){if(!((r=Di())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}iv(o)}else a===it.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(s){console.error(s)}}function tv(t,e,i){const r=`requestId=${e}&sessionTopic=${i}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${ov(r,!0)}`}else s=`${s}/wc?${r}`;return s}function iv(t){let e="_self";nv()?e="_top":(sv()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function rv(t,e){let i="";try{if(sr()&&(i=localStorage.getItem(e),i))return i;i=await t.getItem(e)}catch(r){console.error(r)}return i}function Mc(t,e){if(!t.includes(e))return null;const i=t.split(/([&,?,=])/),r=i.indexOf(e);return i[r+2]}function qc(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function fa(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function sv(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function nv(){try{return window.self!==window.top}catch{return!1}}function ov(t,e=!1){const i=Buffer.from(t).toString("base64");return e?i.replace(/[=]/g,""):i}function Zl(t){return Buffer.from(t,"base64").toString("utf-8")}function av(t){return new Promise(e=>setTimeout(e,t))}let cv=class{constructor({limit:e}){kc(this,"limit"),kc(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const i=this.set.values().next().value;i&&this.set.delete(i)}this.set.add(e)}}has(e){return this.set.has(e)}};const ws=BigInt(2**32-1),jc=BigInt(32);function Ql(t,e=!1){return e?{h:Number(t&ws),l:Number(t>>jc&ws)}:{h:Number(t>>jc&ws)|0,l:Number(t&ws)|0}}function Xl(t,e=!1){const i=t.length;let r=new Uint32Array(i),s=new Uint32Array(i);for(let n=0;n<i;n++){const{h:o,l:a}=Ql(t[n],e);[r[n],s[n]]=[o,a]}return[r,s]}const zc=(t,e,i)=>t>>>i,Kc=(t,e,i)=>t<<32-i|e>>>i,si=(t,e,i)=>t>>>i|e<<32-i,ni=(t,e,i)=>t<<32-i|e>>>i,Sr=(t,e,i)=>t<<64-i|e>>>i-32,Dr=(t,e,i)=>t>>>i-32|e<<64-i,uv=(t,e)=>e,hv=(t,e)=>t,lv=(t,e,i)=>t<<i|e>>>32-i,fv=(t,e,i)=>e<<i|t>>>32-i,dv=(t,e,i)=>e<<i-32|t>>>64-i,pv=(t,e,i)=>t<<i-32|e>>>64-i;function wt(t,e,i,r){const s=(e>>>0)+(r>>>0);return{h:t+i+(s/2**32|0)|0,l:s|0}}const da=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),pa=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,gv=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),yv=(t,e,i,r,s)=>e+i+r+s+(t/2**32|0)|0,wv=(t,e,i,r,s)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(s>>>0),mv=(t,e,i,r,s,n)=>e+i+r+s+n+(t/2**32|0)|0,qi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ga(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Kt(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function lt(t,...e){if(!ga(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ya(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Kt(t.outputLen),Kt(t.blockLen)}function hi(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function wa(t,e){lt(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function jr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ft(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Nn(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Et(t,e){return t<<32-e|t>>>e}const ef=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function tf(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const kt=ef?t=>t:t=>tf(t);function bv(t){for(let e=0;e<t.length;e++)t[e]=tf(t[e]);return t}const oi=ef?t=>t:bv,rf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",vv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function zr(t){if(lt(t),rf)return t.toHex();let e="";for(let i=0;i<t.length;i++)e+=vv[t[i]];return e}const Bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Vc(t){if(t>=Bt._0&&t<=Bt._9)return t-Bt._0;if(t>=Bt.A&&t<=Bt.F)return t-(Bt.A-10);if(t>=Bt.a&&t<=Bt.f)return t-(Bt.a-10)}function ma(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(rf)return Uint8Array.fromHex(t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let s=0,n=0;s<i;s++,n+=2){const o=Vc(t.charCodeAt(n)),a=Vc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}r[s]=o*16+a}return r}function Ev(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bt(t){return typeof t=="string"&&(t=Ev(t)),lt(t),t}function Ei(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];lt(s),e+=s.length}const i=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const n=t[r];i.set(n,s),s+=n.length}return i}class rn{}function ts(t){const e=r=>t().update(bt(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function _v(t){const e=(r,s)=>t(s).update(bt(r)).digest(),i=t({});return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}function nr(t=32){if(qi&&typeof qi.getRandomValues=="function")return qi.getRandomValues(new Uint8Array(t));if(qi&&typeof qi.randomBytes=="function")return Uint8Array.from(qi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const xv=BigInt(0),yr=BigInt(1),Iv=BigInt(2),Sv=BigInt(7),Dv=BigInt(256),Av=BigInt(113),sf=[],nf=[],of=[];for(let t=0,e=yr,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],sf.push(2*(5*r+i)),nf.push((t+1)*(t+2)/2%64);let s=xv;for(let n=0;n<7;n++)e=(e<<yr^(e>>Sv)*Av)%Dv,e&Iv&&(s^=yr<<(yr<<BigInt(n))-yr);of.push(s)}const af=Xl(of,!0),$v=af[0],Ov=af[1],Hc=(t,e,i)=>i>32?dv(t,e,i):lv(t,e,i),Wc=(t,e,i)=>i>32?pv(t,e,i):fv(t,e,i);function Tv(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=i[c],h=i[c+1],l=Hc(u,h,1)^i[a],f=Wc(u,h,1)^i[a+1];for(let p=0;p<50;p+=10)t[o+p]^=l,t[o+p+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=nf[o],c=Hc(s,n,a),u=Wc(s,n,a),h=sf[o];s=t[h],n=t[h+1],t[h]=c,t[h+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=$v[r],t[1]^=Ov[r]}ft(i)}let Cv=class cf extends rn{constructor(e,i,r,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=i,this.outputLen=r,this.enableXOF=s,this.rounds=n,Kt(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=jr(this.state)}clone(){return this._cloneInto()}keccak(){oi(this.state32),Tv(this.state32,this.rounds),oi(this.state32),this.posOut=0,this.pos=0}update(e){hi(this),e=bt(e),lt(e);const{blockLen:i,state:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);for(let a=0;a<o;a++)r[this.pos++]^=e[n++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:s}=this;e[r]^=i,i&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){hi(this,!1),lt(e),this.finish();const i=this.state,{blockLen:r}=this;for(let s=0,n=e.length;s<n;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,n-s);e.set(i.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(wa(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,ft(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new cf(i,r,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const Pv=(t,e,i)=>ts(()=>new Cv(e,t,i)),Rv=Pv(1,136,256/8);function Fv(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Bv(t,e,i){return t&e^~t&i}function Uv(t,e,i){return t&e^t&i^e&i}let uf=class extends rn{constructor(e,i,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Nn(this.buffer)}update(e){hi(this),e=bt(e),lt(e);const{view:i,buffer:r,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=Nn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){hi(this),wa(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:s,isLE:n}=this;let{pos:o}=this;i[o++]=128,ft(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let l=o;l<s;l++)i[l]=0;Fv(r,s-8,BigInt(this.length*8),n),this.process(r,0);const a=Nn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,h=this.get();if(u>h.length)throw new Error("_sha2: outputLen bigger than state");for(let l=0;l<u;l++)a.setUint32(4*l,h[l],n)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%i&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Jt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Be=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Ue=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Nv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Zt=new Uint32Array(64);let kv=class extends uf{constructor(e=32){super(64,e,8,!1),this.A=Jt[0]|0,this.B=Jt[1]|0,this.C=Jt[2]|0,this.D=Jt[3]|0,this.E=Jt[4]|0,this.F=Jt[5]|0,this.G=Jt[6]|0,this.H=Jt[7]|0}get(){const{A:e,B:i,C:r,D:s,E:n,F:o,G:a,H:c}=this;return[e,i,r,s,n,o,a,c]}set(e,i,r,s,n,o,a,c){this.A=e|0,this.B=i|0,this.C=r|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,i){for(let l=0;l<16;l++,i+=4)Zt[l]=e.getUint32(i,!1);for(let l=16;l<64;l++){const f=Zt[l-15],p=Zt[l-2],d=Et(f,7)^Et(f,18)^f>>>3,g=Et(p,17)^Et(p,19)^p>>>10;Zt[l]=g+Zt[l-7]+d+Zt[l-16]|0}let{A:r,B:s,C:n,D:o,E:a,F:c,G:u,H:h}=this;for(let l=0;l<64;l++){const f=Et(a,6)^Et(a,11)^Et(a,25),p=h+f+Bv(a,c,u)+Nv[l]+Zt[l]|0,d=(Et(r,2)^Et(r,13)^Et(r,22))+Uv(r,s,n)|0;h=u,u=c,c=a,a=o+p|0,o=n,n=s,s=r,r=p+d|0}r=r+this.A|0,s=s+this.B|0,n=n+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,h=h+this.H|0,this.set(r,s,n,o,a,c,u,h)}roundClean(){ft(Zt)}destroy(){this.set(0,0,0,0,0,0,0,0),ft(this.buffer)}};const hf=Xl(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Lv=hf[0],Mv=hf[1],Qt=new Uint32Array(80),Xt=new Uint32Array(80);let ba=class extends uf{constructor(e=64){super(128,e,16,!1),this.Ah=Ue[0]|0,this.Al=Ue[1]|0,this.Bh=Ue[2]|0,this.Bl=Ue[3]|0,this.Ch=Ue[4]|0,this.Cl=Ue[5]|0,this.Dh=Ue[6]|0,this.Dl=Ue[7]|0,this.Eh=Ue[8]|0,this.El=Ue[9]|0,this.Fh=Ue[10]|0,this.Fl=Ue[11]|0,this.Gh=Ue[12]|0,this.Gl=Ue[13]|0,this.Hh=Ue[14]|0,this.Hl=Ue[15]|0}get(){const{Ah:e,Al:i,Bh:r,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:h,Fh:l,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y]}set(e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=h|0,this.Fh=l|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,i){for(let m=0;m<16;m++,i+=4)Qt[m]=e.getUint32(i),Xt[m]=e.getUint32(i+=4);for(let m=16;m<80;m++){const D=Qt[m-15]|0,I=Xt[m-15]|0,R=si(D,I,1)^si(D,I,8)^zc(D,I,7),U=ni(D,I,1)^ni(D,I,8)^Kc(D,I,7),C=Qt[m-2]|0,w=Xt[m-2]|0,O=si(C,w,19)^Sr(C,w,61)^zc(C,w,6),_=ni(C,w,19)^Dr(C,w,61)^Kc(C,w,6),$=gv(U,_,Xt[m-7],Xt[m-16]),P=yv($,R,O,Qt[m-7],Qt[m-16]);Qt[m]=P|0,Xt[m]=$|0}let{Ah:r,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:h,Eh:l,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:E,Hl:v}=this;for(let m=0;m<80;m++){const D=si(l,f,14)^si(l,f,18)^Sr(l,f,41),I=ni(l,f,14)^ni(l,f,18)^Dr(l,f,41),R=l&p^~l&g,U=f&d^~f&y,C=wv(v,I,U,Mv[m],Xt[m]),w=mv(C,E,D,R,Lv[m],Qt[m]),O=C|0,_=si(r,s,28)^Sr(r,s,34)^Sr(r,s,39),$=ni(r,s,28)^Dr(r,s,34)^Dr(r,s,39),P=r&n^r&a^n&a,k=s&o^s&c^o&c;E=g|0,v=y|0,g=p|0,y=d|0,p=l|0,d=f|0,{h:l,l:f}=wt(u|0,h|0,w|0,O|0),u=a|0,h=c|0,a=n|0,c=o|0,n=r|0,o=s|0;const x=da(O,$,k);r=pa(x,w,_,P),s=x|0}({h:r,l:s}=wt(this.Ah|0,this.Al|0,r|0,s|0)),{h:n,l:o}=wt(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=wt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l:h}=wt(this.Dh|0,this.Dl|0,u|0,h|0),{h:l,l:f}=wt(this.Eh|0,this.El|0,l|0,f|0),{h:p,l:d}=wt(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=wt(this.Gh|0,this.Gl|0,g|0,y|0),{h:E,l:v}=wt(this.Hh|0,this.Hl|0,E|0,v|0),this.set(r,s,n,o,a,c,u,h,l,f,p,d,g,y,E,v)}roundClean(){ft(Qt,Xt)}destroy(){ft(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},qv=class extends ba{constructor(){super(48),this.Ah=Be[0]|0,this.Al=Be[1]|0,this.Bh=Be[2]|0,this.Bl=Be[3]|0,this.Ch=Be[4]|0,this.Cl=Be[5]|0,this.Dh=Be[6]|0,this.Dl=Be[7]|0,this.Eh=Be[8]|0,this.El=Be[9]|0,this.Fh=Be[10]|0,this.Fl=Be[11]|0,this.Gh=Be[12]|0,this.Gl=Be[13]|0,this.Hh=Be[14]|0,this.Hl=Be[15]|0}};const Ne=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class jv extends ba{constructor(){super(32),this.Ah=Ne[0]|0,this.Al=Ne[1]|0,this.Bh=Ne[2]|0,this.Bl=Ne[3]|0,this.Ch=Ne[4]|0,this.Cl=Ne[5]|0,this.Dh=Ne[6]|0,this.Dl=Ne[7]|0,this.Eh=Ne[8]|0,this.El=Ne[9]|0,this.Fh=Ne[10]|0,this.Fl=Ne[11]|0,this.Gh=Ne[12]|0,this.Gl=Ne[13]|0,this.Hh=Ne[14]|0,this.Hl=Ne[15]|0}}const sn=ts(()=>new kv),zv=ts(()=>new ba),Kv=ts(()=>new qv),Vv=ts(()=>new jv),Hv=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),we=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),q=new Uint32Array(32);function ei(t,e,i,r,s,n){const o=s[n],a=s[n+1];let c=q[2*t],u=q[2*t+1],h=q[2*e],l=q[2*e+1],f=q[2*i],p=q[2*i+1],d=q[2*r],g=q[2*r+1],y=da(c,h,o);u=pa(y,u,l,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:uv(g,d),Dl:hv(g)},{h:p,l:f}=wt(p,f,g,d),{Bh:l,Bl:h}={Bh:l^p,Bl:h^f},{Bh:l,Bl:h}={Bh:si(l,h,24),Bl:ni(l,h,24)},q[2*t]=c,q[2*t+1]=u,q[2*e]=h,q[2*e+1]=l,q[2*i]=f,q[2*i+1]=p,q[2*r]=d,q[2*r+1]=g}function ti(t,e,i,r,s,n){const o=s[n],a=s[n+1];let c=q[2*t],u=q[2*t+1],h=q[2*e],l=q[2*e+1],f=q[2*i],p=q[2*i+1],d=q[2*r],g=q[2*r+1],y=da(c,h,o);u=pa(y,u,l,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:si(g,d,16),Dl:ni(g,d,16)},{h:p,l:f}=wt(p,f,g,d),{Bh:l,Bl:h}={Bh:l^p,Bl:h^f},{Bh:l,Bl:h}={Bh:Sr(l,h,63),Bl:Dr(l,h,63)},q[2*t]=c,q[2*t+1]=u,q[2*e]=h,q[2*e+1]=l,q[2*i]=f,q[2*i+1]=p,q[2*r]=d,q[2*r+1]=g}function Wv(t,e={},i,r,s){if(Kt(i),t<0||t>i)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=e;if(n!==void 0&&(n.length<1||n.length>i))throw new Error("key length must be undefined or 1.."+i);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class Gv extends rn{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Kt(e),Kt(i),this.blockLen=e,this.outputLen=i,this.buffer=new Uint8Array(e),this.buffer32=jr(this.buffer)}update(e){hi(this),e=bt(e),lt(e);const{blockLen:i,buffer:r,buffer32:s}=this,n=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<n;){this.pos===i&&(oi(s),this.compress(s,0,!1),oi(s),this.pos=0);const u=Math.min(i-this.pos,n-c),h=o+c;if(u===i&&!(h%4)&&c+u<n){const l=new Uint32Array(a,h,Math.floor((n-c)/4));oi(l);for(let f=0;c+i<n;f+=s.length,c+=i)this.length+=i,this.compress(l,f,!1);oi(l);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){hi(this),wa(e,this);const{pos:i,buffer32:r}=this;this.finished=!0,ft(this.buffer.subarray(i)),oi(r),this.compress(r,0,!0),oi(r);const s=jr(e);this.get().forEach((n,o)=>s[o]=kt(n))}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){const{buffer:i,length:r,finished:s,destroyed:n,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(i),e.destroyed=n,e.finished=s,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Yv extends Gv{constructor(e={}){const i=e.dkLen===void 0?64:e.dkLen;super(128,i),this.v0l=we[0]|0,this.v0h=we[1]|0,this.v1l=we[2]|0,this.v1h=we[3]|0,this.v2l=we[4]|0,this.v2h=we[5]|0,this.v3l=we[6]|0,this.v3h=we[7]|0,this.v4l=we[8]|0,this.v4h=we[9]|0,this.v5l=we[10]|0,this.v5h=we[11]|0,this.v6l=we[12]|0,this.v6h=we[13]|0,this.v7l=we[14]|0,this.v7h=we[15]|0,Wv(i,e,64,16,16);let{key:r,personalization:s,salt:n}=e,o=0;if(r!==void 0&&(r=bt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,n!==void 0){n=bt(n);const a=jr(n);this.v4l^=kt(a[0]),this.v4h^=kt(a[1]),this.v5l^=kt(a[2]),this.v5h^=kt(a[3])}if(s!==void 0){s=bt(s);const a=jr(s);this.v6l^=kt(a[0]),this.v6h^=kt(a[1]),this.v7l^=kt(a[2]),this.v7h^=kt(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:i,v1l:r,v1h:s,v2l:n,v2h:o,v3l:a,v3h:c,v4l:u,v4h:h,v5l:l,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y]}set(e,i,r,s,n,o,a,c,u,h,l,f,p,d,g,y){this.v0l=e|0,this.v0h=i|0,this.v1l=r|0,this.v1h=s|0,this.v2l=n|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=h|0,this.v5l=l|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=g|0,this.v7h=y|0}compress(e,i,r){this.get().forEach((c,u)=>q[u]=c),q.set(we,16);let{h:s,l:n}=Ql(BigInt(this.length));q[24]=we[8]^n,q[25]=we[9]^s,r&&(q[28]=~q[28],q[29]=~q[29]);let o=0;const a=Hv;for(let c=0;c<12;c++)ei(0,4,8,12,e,i+2*a[o++]),ti(0,4,8,12,e,i+2*a[o++]),ei(1,5,9,13,e,i+2*a[o++]),ti(1,5,9,13,e,i+2*a[o++]),ei(2,6,10,14,e,i+2*a[o++]),ti(2,6,10,14,e,i+2*a[o++]),ei(3,7,11,15,e,i+2*a[o++]),ti(3,7,11,15,e,i+2*a[o++]),ei(0,5,10,15,e,i+2*a[o++]),ti(0,5,10,15,e,i+2*a[o++]),ei(1,6,11,12,e,i+2*a[o++]),ti(1,6,11,12,e,i+2*a[o++]),ei(2,7,8,13,e,i+2*a[o++]),ti(2,7,8,13,e,i+2*a[o++]),ei(3,4,9,14,e,i+2*a[o++]),ti(3,4,9,14,e,i+2*a[o++]);this.v0l^=q[0]^q[16],this.v0h^=q[1]^q[17],this.v1l^=q[2]^q[18],this.v1h^=q[3]^q[19],this.v2l^=q[4]^q[20],this.v2h^=q[5]^q[21],this.v3l^=q[6]^q[22],this.v3h^=q[7]^q[23],this.v4l^=q[8]^q[24],this.v4h^=q[9]^q[25],this.v5l^=q[10]^q[26],this.v5h^=q[11]^q[27],this.v6l^=q[12]^q[28],this.v6h^=q[13]^q[29],this.v7l^=q[14]^q[30],this.v7h^=q[15]^q[31],ft(q)}destroy(){this.destroyed=!0,ft(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Jv=_v(t=>new Yv(t)),Zv="https://rpc.walletconnect.org/v1";function lf(t){const e=`Ethereum Signed Message:
${t.length}`,i=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Rv(i)).toString("hex")}async function Qv(t,e,i,r,s,n){switch(i.t){case"eip191":return await Xv(t,e,i.s);case"eip1271":return await e2(t,e,i.s,r,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}async function Xv(t,e,i){return(await Ow({hash:lf(e),signature:i})).toLowerCase()===t.toLowerCase()}async function e2(t,e,i,r,s,n){const o=$s(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=i.substring(2),h=(u.length/2).toString(16).padStart(64,"0"),l=(e.startsWith("0x")?e:lf(e)).substring(2),f=a+l+c+h+u,p=await fetch(`${n||Zv}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:t2(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:d}=await p.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function t2(){return Date.now()+Math.floor(Math.random()*1e3)}function i2(t){const e=atob(t),i=new Uint8Array(e.length);for(let o=0;o<e.length;o++)i[o]=e.charCodeAt(o);const r=i[0];if(r===0)throw new Error("No signatures found");const s=1+r*64;if(i.length<s)throw new Error("Transaction data too short for claimed signature count");if(i.length<100)throw new Error("Transaction too short");const n=Buffer.from(t,"base64").slice(1,65);return Qr.encode(n)}function r2(t){const e=new Uint8Array(Buffer.from(t,"base64")),i=Array.from("TransactionData::").map(n=>n.charCodeAt(0)),r=new Uint8Array(i.length+e.length);r.set(i),r.set(e,i.length);const s=Jv(r,{dkLen:32});return Qr.encode(s)}function Gc(t){const e=new Uint8Array(sn(s2(t)));return Qr.encode(e)}function s2(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Yc(t){const e=Buffer.from(t,"base64"),i=dm(e).txn;if(!i)throw new Error("Invalid signed transaction: missing 'txn' field");const r=sm(i),s=Buffer.from("TX"),n=Buffer.concat([s,Buffer.from(r)]),o=Vv(n);return Em.encode(o).replace(/=+$/,"")}function kn(t){const e=[];let i=BigInt(t);for(;i>=BigInt(128);)e.push(Number(i&BigInt(127)|BigInt(128))),i>>=BigInt(7);return e.push(Number(i)),Buffer.from(e)}function n2(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),i=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),s=[];s.push(Buffer.from([10])),s.push(kn(e.length)),s.push(e),s.push(Buffer.from([18])),s.push(kn(i.length)),s.push(i),s.push(Buffer.from([26])),s.push(kn(r.length)),s.push(r);const n=Buffer.concat(s),o=sn(n);return Buffer.from(o).toString("hex").toUpperCase()}var o2=Object.defineProperty,a2=Object.defineProperties,c2=Object.getOwnPropertyDescriptors,Jc=Object.getOwnPropertySymbols,u2=Object.prototype.hasOwnProperty,h2=Object.prototype.propertyIsEnumerable,Zc=(t,e,i)=>e in t?o2(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,l2=(t,e)=>{for(var i in e||(e={}))u2.call(e,i)&&Zc(t,i,e[i]);if(Jc)for(var i of Jc(e))h2.call(e,i)&&Zc(t,i,e[i]);return t},f2=(t,e)=>a2(t,c2(e));const d2="did:pkh:",va=t=>t?.split(":"),p2=t=>{const e=t&&va(t);if(e)return t.includes(d2)?e[3]:e[1]},_o=t=>{const e=t&&va(t);if(e)return e[2]+":"+e[3]},js=t=>{const e=t&&va(t);if(e)return e.pop()};async function Qc(t){const{cacao:e,projectId:i}=t,{s:r,p:s}=e,n=ff(s,s.iss),o=js(s.iss);return await Qv(o,n,r,_o(s.iss),i)}const ff=(t,e)=>{const i=`${t.domain} wants you to sign in with your Ethereum account:`,r=js(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const n=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${p2(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,l=t.nbf?`Not Before: ${t.nbf}`:void 0,f=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(g=>`
- ${g}`).join("")}`:void 0,d=Os(t.resources);if(d){const g=Kr(d);s=x2(s,g)}return[i,r,"",s,"",n,o,a,c,u,h,l,f,p].filter(g=>g!=null).join(`
`)};function g2(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function y2(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function $i(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(i=>{const r=t.att[i];if(Array.isArray(r))throw new Error(`Resource must be an object: ${i}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${i}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${i}`);Object.keys(r).forEach(s=>{const n=r[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function w2(t,e,i,r={}){return i?.sort((s,n)=>s.localeCompare(n)),{att:{[t]:m2(e,i,r)}}}function m2(t,e,i={}){e=e?.sort((s,n)=>s.localeCompare(n));const r=e.map(s=>({[`${t}/${s}`]:[i]}));return Object.assign({},...r)}function df(t){return $i(t),`urn:recap:${g2(t).replace(/=/g,"")}`}function Kr(t){const e=y2(t.replace("urn:recap:",""));return $i(e),e}function b2(t,e,i){const r=w2(t,e,i);return df(r)}function v2(t){return t&&t.includes("urn:recap:")}function E2(t,e){const i=Kr(t),r=Kr(e),s=_2(i,r);return df(s)}function _2(t,e){$i(t),$i(e);const i=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),r={att:{}};return i.forEach(s=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;r.att[s]=f2(l2({},r.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((u=e.att[s])==null?void 0:u[a])})})}),r}function x2(t="",e){$i(e);const i="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(i))return t;const r=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(l=>({ability:l.split("/")[0],action:l.split("/")[1]}));c.sort((l,f)=>l.action.localeCompare(f.action));const u={};c.forEach(l=>{u[l.ability]||(u[l.ability]=[]),u[l.ability].push(l.action)});const h=Object.keys(u).map(l=>(s++,`(${s}) '${l}': '${u[l].join("', '")}' for '${a}'.`));r.push(h.join(", ").replace(".,","."))});const n=r.join(" "),o=`${i}${n}`;return`${t?t+" ":""}${o}`}function Xc(t){var e;const i=Kr(t);$i(i);const r=(e=i.att)==null?void 0:e.eip155;return r?Object.keys(r).map(s=>s.split("/")[1]):[]}function eu(t){const e=Kr(t);$i(e);const i=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{var n;(n=s?.[0])!=null&&n.chains&&i.push(s[0].chains)})}),[...new Set(i.flat())]}function Os(t){if(!t)return;const e=t?.[t.length-1];return v2(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function pf(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Ln(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ge(t,...e){if(!pf(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function tu(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function I2(t,e){Ge(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function ui(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Zi(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function S2(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const D2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function A2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Io(t){if(typeof t=="string")t=A2(t);else if(pf(t))t=So(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function $2(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function O2(t,e){if(t.length!==e.length)return!1;let i=0;for(let r=0;r<t.length;r++)i|=t[r]^e[r];return i===0}const T2=(t,e)=>{function i(r,...s){if(Ge(r),!D2)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?Ge(u):Ge(u,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&Ge(s[1]);const o=e(r,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");Ge(h)}};let c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ge(u),a(o.encrypt.length,h),o.encrypt(u,h)},decrypt(u,h){if(Ge(u),n&&u.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,h),o.decrypt(u,h)}}}return Object.assign(i,t),i};function iu(t,e,i=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(i&&!P2(e))throw new Error("invalid output, must be aligned");return e}function ru(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const s=BigInt(32),n=BigInt(4294967295),o=Number(i>>s&n),a=Number(i&n),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function C2(t,e,i){xo(i);const r=new Uint8Array(16),s=S2(r);return ru(s,0,BigInt(e),i),ru(s,8,BigInt(t),i),r}function P2(t){return t.byteOffset%4===0}function So(t){return Uint8Array.from(t)}const gf=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),R2=gf("expand 16-byte k"),F2=gf("expand 32-byte k"),B2=ui(R2),U2=ui(F2);function X(t,e){return t<<e|t>>>32-e}function Do(t){return t.byteOffset%4===0}const ms=64,N2=16,yf=2**32-1,su=new Uint32Array;function k2(t,e,i,r,s,n,o,a){const c=s.length,u=new Uint8Array(ms),h=ui(u),l=Do(s)&&Do(n),f=l?ui(s):su,p=l?ui(n):su;for(let d=0;d<c;o++){if(t(e,i,r,h,o,a),o>=yf)throw new Error("arx: counter overflow");const g=Math.min(ms,c-d);if(l&&g===ms){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let E=0,v;E<N2;E++)v=y+E,p[v]=f[v]^h[E];d+=ms;continue}for(let y=0,E;y<g;y++)E=d+y,n[E]=s[E]^u[y];d+=g}}function L2(t,e){const{allowShortKeys:i,extendNonceFn:r,counterLength:s,counterRight:n,rounds:o}=$2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Ln(s),Ln(o),xo(n),xo(i),(a,c,u,h,l=0)=>{Ge(a),Ge(c),Ge(u);const f=u.length;if(h===void 0&&(h=new Uint8Array(f)),Ge(h),Ln(l),l<0||l>=yf)throw new Error("arx: counter overflow");if(h.length<f)throw new Error(`arx: output (${h.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=So(a)),y=U2;else if(d===16&&i)g=new Uint8Array(32),g.set(a),g.set(a,16),y=B2,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);Do(c)||p.push(c=So(c));const E=ui(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,E,ui(c.subarray(0,16)),E),c=c.subarray(16)}const v=16-s;if(v!==c.length)throw new Error(`arx: nonce must be ${v} or 16 bytes`);if(v!==12){const D=new Uint8Array(12);D.set(c,n?0:12-c.length),c=D,p.push(c)}const m=ui(c);return k2(t,y,E,m,u,h,l,o),Zi(...p),h}}const De=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class M2{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=Io(e),Ge(e,32);const i=De(e,0),r=De(e,2),s=De(e,4),n=De(e,6),o=De(e,8),a=De(e,10),c=De(e,12),u=De(e,14);this.r[0]=i&8191,this.r[1]=(i>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let h=0;h<8;h++)this.pad[h]=De(e,16+2*h)}process(e,i,r=!1){const s=r?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],u=o[2],h=o[3],l=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],E=De(e,i+0),v=De(e,i+2),m=De(e,i+4),D=De(e,i+6),I=De(e,i+8),R=De(e,i+10),U=De(e,i+12),C=De(e,i+14);let w=n[0]+(E&8191),O=n[1]+((E>>>13|v<<3)&8191),_=n[2]+((v>>>10|m<<6)&8191),$=n[3]+((m>>>7|D<<9)&8191),P=n[4]+((D>>>4|I<<12)&8191),k=n[5]+(I>>>1&8191),x=n[6]+((I>>>14|R<<2)&8191),b=n[7]+((R>>>11|U<<5)&8191),S=n[8]+((U>>>8|C<<8)&8191),T=n[9]+(C>>>5|s),A=0,B=A+w*a+O*(5*y)+_*(5*g)+$*(5*d)+P*(5*p);A=B>>>13,B&=8191,B+=k*(5*f)+x*(5*l)+b*(5*h)+S*(5*u)+T*(5*c),A+=B>>>13,B&=8191;let N=A+w*c+O*a+_*(5*y)+$*(5*g)+P*(5*d);A=N>>>13,N&=8191,N+=k*(5*p)+x*(5*f)+b*(5*l)+S*(5*h)+T*(5*u),A+=N>>>13,N&=8191;let j=A+w*u+O*c+_*a+$*(5*y)+P*(5*g);A=j>>>13,j&=8191,j+=k*(5*d)+x*(5*p)+b*(5*f)+S*(5*l)+T*(5*h),A+=j>>>13,j&=8191;let z=A+w*h+O*u+_*c+$*a+P*(5*y);A=z>>>13,z&=8191,z+=k*(5*g)+x*(5*d)+b*(5*p)+S*(5*f)+T*(5*l),A+=z>>>13,z&=8191;let K=A+w*l+O*h+_*u+$*c+P*a;A=K>>>13,K&=8191,K+=k*(5*y)+x*(5*g)+b*(5*d)+S*(5*p)+T*(5*f),A+=K>>>13,K&=8191;let V=A+w*f+O*l+_*h+$*u+P*c;A=V>>>13,V&=8191,V+=k*a+x*(5*y)+b*(5*g)+S*(5*d)+T*(5*p),A+=V>>>13,V&=8191;let H=A+w*p+O*f+_*l+$*h+P*u;A=H>>>13,H&=8191,H+=k*c+x*a+b*(5*y)+S*(5*g)+T*(5*d),A+=H>>>13,H&=8191;let re=A+w*d+O*p+_*f+$*l+P*h;A=re>>>13,re&=8191,re+=k*u+x*c+b*a+S*(5*y)+T*(5*g),A+=re>>>13,re&=8191;let ie=A+w*g+O*d+_*p+$*f+P*l;A=ie>>>13,ie&=8191,ie+=k*h+x*u+b*c+S*a+T*(5*y),A+=ie>>>13,ie&=8191;let J=A+w*y+O*g+_*d+$*p+P*f;A=J>>>13,J&=8191,J+=k*l+x*h+b*u+S*c+T*a,A+=J>>>13,J&=8191,A=(A<<2)+A|0,A=A+B|0,B=A&8191,A=A>>>13,N+=A,n[0]=B,n[1]=N,n[2]=j,n[3]=z,n[4]=K,n[5]=V,n[6]=H,n[7]=re,n[8]=ie,n[9]=J}finalize(){const{h:e,pad:i}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)r[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+i[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+i[a]|0)+(o>>>16)|0,e[a]=o&65535;Zi(r)}update(e){tu(this),e=Io(e),Ge(e);const{buffer:i,blockLen:r}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);if(o===r){for(;r<=s-n;n+=r)this.process(e,n);continue}i.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===r&&(this.process(i,0,!1),this.pos=0)}return this}destroy(){Zi(this.h,this.r,this.buffer,this.pad)}digestInto(e){tu(this),I2(e,this),this.finished=!0;const{buffer:i,h:r}=this;let{pos:s}=this;if(s){for(i[s++]=1;s<16;s++)i[s]=0;this.process(i,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=r[o]>>>0,e[n++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}}function q2(t){const e=(r,s)=>t(s).update(Io(r)).digest(),i=t(new Uint8Array(32));return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}const j2=q2(t=>new M2(t));function z2(t,e,i,r,s,n=20){let o=t[0],a=t[1],c=t[2],u=t[3],h=e[0],l=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],E=e[7],v=s,m=i[0],D=i[1],I=i[2],R=o,U=a,C=c,w=u,O=h,_=l,$=f,P=p,k=d,x=g,b=y,S=E,T=v,A=m,B=D,N=I;for(let z=0;z<n;z+=2)R=R+O|0,T=X(T^R,16),k=k+T|0,O=X(O^k,12),R=R+O|0,T=X(T^R,8),k=k+T|0,O=X(O^k,7),U=U+_|0,A=X(A^U,16),x=x+A|0,_=X(_^x,12),U=U+_|0,A=X(A^U,8),x=x+A|0,_=X(_^x,7),C=C+$|0,B=X(B^C,16),b=b+B|0,$=X($^b,12),C=C+$|0,B=X(B^C,8),b=b+B|0,$=X($^b,7),w=w+P|0,N=X(N^w,16),S=S+N|0,P=X(P^S,12),w=w+P|0,N=X(N^w,8),S=S+N|0,P=X(P^S,7),R=R+_|0,N=X(N^R,16),b=b+N|0,_=X(_^b,12),R=R+_|0,N=X(N^R,8),b=b+N|0,_=X(_^b,7),U=U+$|0,T=X(T^U,16),S=S+T|0,$=X($^S,12),U=U+$|0,T=X(T^U,8),S=S+T|0,$=X($^S,7),C=C+P|0,A=X(A^C,16),k=k+A|0,P=X(P^k,12),C=C+P|0,A=X(A^C,8),k=k+A|0,P=X(P^k,7),w=w+O|0,B=X(B^w,16),x=x+B|0,O=X(O^x,12),w=w+O|0,B=X(B^w,8),x=x+B|0,O=X(O^x,7);let j=0;r[j++]=o+R|0,r[j++]=a+U|0,r[j++]=c+C|0,r[j++]=u+w|0,r[j++]=h+O|0,r[j++]=l+_|0,r[j++]=f+$|0,r[j++]=p+P|0,r[j++]=d+k|0,r[j++]=g+x|0,r[j++]=y+b|0,r[j++]=E+S|0,r[j++]=v+T|0,r[j++]=m+A|0,r[j++]=D+B|0,r[j++]=I+N|0}const K2=L2(z2,{counterRight:!1,counterLength:4,allowShortKeys:!1}),V2=new Uint8Array(16),nu=(t,e)=>{t.update(e);const i=e.length%16;i&&t.update(V2.subarray(i))},H2=new Uint8Array(32);function ou(t,e,i,r,s){const n=t(e,i,H2),o=j2.create(n);s&&nu(o,s),nu(o,r);const a=C2(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Zi(n,a),c}const W2=t=>(e,i,r)=>({encrypt(s,n){const o=s.length;n=iu(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,i,a,a,1);const c=ou(t,e,i,a,r);return n.set(c,o),Zi(c),n},decrypt(s,n){n=iu(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=ou(t,e,i,o,r);if(!O2(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,i,n,n,1),Zi(c),n}}),wf=T2({blockSize:64,nonceLength:12,tagLength:16},W2(K2));let mf=class extends rn{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,ya(e);const r=bt(i);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(r.length>s?e.create().update(r).digest():r);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),ft(n)}update(e){return hi(this),this.iHash.update(e),this}digestInto(e){hi(this),lt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:i,iHash:r,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=i._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const nn=(t,e,i)=>new mf(t,e).update(i).digest();nn.create=(t,e)=>new mf(t,e);function G2(t,e,i){return ya(t),i===void 0&&(i=new Uint8Array(t.outputLen)),nn(t,bt(i),bt(e))}const Mn=Uint8Array.from([0]),au=Uint8Array.of();function Y2(t,e,i,r=32){ya(t),Kt(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(r/s);i===void 0&&(i=au);const o=new Uint8Array(n*s),a=nn.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let h=0;h<n;h++)Mn[0]=h+1,c.update(h===0?au:u).update(i).update(Mn).digestInto(u),o.set(u,s*h),a._cloneInto(c);return a.destroy(),c.destroy(),ft(u,Mn),o.slice(0,r)}const J2=(t,e,i,r,s)=>Y2(t,G2(t,e,i),r,s),on=sn,Ea=BigInt(0),Ao=BigInt(1);function zs(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function bs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function bf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ea:BigInt("0x"+t)}function an(t){return bf(zr(t))}function Ks(t){return lt(t),bf(zr(Uint8Array.from(t).reverse()))}function _a(t,e){return ma(t.toString(16).padStart(e*2,"0"))}function xa(t,e){return _a(t,e).reverse()}function We(t,e,i){let r;if(typeof e=="string")try{r=ma(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(ga(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof i=="number"&&s!==i)throw new Error(t+" of length "+i+" expected, got "+s);return r}const qn=t=>typeof t=="bigint"&&Ea<=t;function Z2(t,e,i){return qn(t)&&qn(e)&&qn(i)&&e<=t&&t<i}function $o(t,e,i,r){if(!Z2(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function Q2(t){let e;for(e=0;t>Ea;t>>=Ao,e+=1);return e}const cn=t=>(Ao<<BigInt(t))-Ao;function X2(t,e,i){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof i!="function")throw new Error("hmacFn must be a function");const r=f=>new Uint8Array(f),s=f=>Uint8Array.of(f);let n=r(t),o=r(t),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},u=(...f)=>i(o,n,...f),h=(f=r(0))=>{o=u(s(0),f),n=u(),f.length!==0&&(o=u(s(1),f),n=u())},l=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){n=u();const d=n.slice();p.push(d),f+=n.length}return Ei(...p)};return(f,p)=>{c(),h(f);let d;for(;!(d=p(l()));)h();return c(),d}}function un(t,e,i={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,n,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==n||a===null)throw new Error(`param "${s}" is invalid: expected ${n}, got ${c}`)}Object.entries(e).forEach(([s,n])=>r(s,n,!1)),Object.entries(i).forEach(([s,n])=>r(s,n,!0))}function cu(t){const e=new WeakMap;return(i,...r)=>{const s=e.get(i);if(s!==void 0)return s;const n=t(i,...r);return e.set(i,n),n}}const Je=BigInt(0),Me=BigInt(1),_i=BigInt(2),eE=BigInt(3),vf=BigInt(4),Ef=BigInt(5),_f=BigInt(8);function ut(t,e){const i=t%e;return i>=Je?i:e+i}function gt(t,e,i){let r=t;for(;e-- >Je;)r*=r,r%=i;return r}function uu(t,e){if(t===Je)throw new Error("invert: expected non-zero number");if(e<=Je)throw new Error("invert: expected positive modulus, got "+e);let i=ut(t,e),r=e,s=Je,n=Me;for(;i!==Je;){const o=r/i,a=r%i,c=s-n*o;r=i,i=a,s=n,n=c}if(r!==Me)throw new Error("invert: does not exist");return ut(s,e)}function xf(t,e){const i=(t.ORDER+Me)/vf,r=t.pow(e,i);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function tE(t,e){const i=(t.ORDER-Ef)/_f,r=t.mul(e,_i),s=t.pow(r,i),n=t.mul(e,s),o=t.mul(t.mul(n,_i),s),a=t.mul(n,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function iE(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Me,i=0;for(;e%_i===Je;)e/=_i,i++;let r=_i;const s=or(t);for(;hu(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(i===1)return xf;let n=s.pow(r,e);const o=(e+Me)/_i;return function(a,c){if(a.is0(c))return c;if(hu(a,c)!==1)throw new Error("Cannot find square root");let u=i,h=a.mul(a.ONE,n),l=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(l,a.ONE);){if(a.is0(l))return a.ZERO;let p=1,d=a.sqr(l);for(;!a.eql(d,a.ONE);)if(p++,d=a.sqr(d),p===u)throw new Error("Cannot find square root");const g=Me<<BigInt(u-p-1),y=a.pow(h,g);u=p,h=a.sqr(y),l=a.mul(l,h),f=a.mul(f,y)}return f}}function rE(t){return t%vf===eE?xf:t%_f===Ef?tE:iE(t)}const sE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nE(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},i=sE.reduce((r,s)=>(r[s]="function",r),e);return un(t,i),t}function oE(t,e,i){if(i<Je)throw new Error("invalid exponent, negatives unsupported");if(i===Je)return t.ONE;if(i===Me)return e;let r=t.ONE,s=e;for(;i>Je;)i&Me&&(r=t.mul(r,s)),s=t.sqr(s),i>>=Me;return r}function If(t,e,i=!1){const r=new Array(e.length).fill(i?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),n),r}function hu(t,e){const i=(t.ORDER-Me)/_i,r=t.pow(e,i),s=t.eql(r,t.ONE),n=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function aE(t,e){e!==void 0&&Kt(e);const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function or(t,e,i=!1,r={}){if(t<=Je)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,n;if(typeof e=="object"&&e!=null){if(r.sqrt||i)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(s=h.BITS),h.sqrt&&(n=h.sqrt),typeof h.isLE=="boolean"&&(i=h.isLE)}else typeof e=="number"&&(s=e),r.sqrt&&(n=r.sqrt);const{nBitLength:o,nByteLength:a}=aE(t,s);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const u=Object.freeze({ORDER:t,isLE:i,BITS:o,BYTES:a,MASK:cn(o),ZERO:Je,ONE:Me,create:h=>ut(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return Je<=h&&h<t},is0:h=>h===Je,isValidNot0:h=>!u.is0(h)&&u.isValid(h),isOdd:h=>(h&Me)===Me,neg:h=>ut(-h,t),eql:(h,l)=>h===l,sqr:h=>ut(h*h,t),add:(h,l)=>ut(h+l,t),sub:(h,l)=>ut(h-l,t),mul:(h,l)=>ut(h*l,t),pow:(h,l)=>oE(u,h,l),div:(h,l)=>ut(h*uu(l,t),t),sqrN:h=>h*h,addN:(h,l)=>h+l,subN:(h,l)=>h-l,mulN:(h,l)=>h*l,inv:h=>uu(h,t),sqrt:n||(h=>(c||(c=rE(t)),c(u,h))),toBytes:h=>i?xa(h,a):_a(h,a),fromBytes:h=>{if(h.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);return i?Ks(h):an(h)},invertBatch:h=>If(u,h),cmov:(h,l,f)=>f?l:h});return Object.freeze(u)}function Sf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Df(t){const e=Sf(t);return e+Math.ceil(e/2)}function cE(t,e,i=!1){const r=t.length,s=Sf(e),n=Df(e);if(r<16||r<n||r>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+r);const o=i?Ks(t):an(t),a=ut(o,e-Me)+Me;return i?xa(a,s):_a(a,s)}const Qi=BigInt(0),xi=BigInt(1);function Tr(t,e){const i=e.negate();return t?i:e}function uE(t,e,i){const r=e==="pz"?n=>n.pz:n=>n.ez,s=If(t.Fp,i.map(r));return i.map((n,o)=>n.toAffine(s[o])).map(t.fromAffine)}function Af(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jn(t,e){Af(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,n=cn(t),o=BigInt(t);return{windows:i,windowSize:r,mask:n,maxNumber:s,shiftBy:o}}function lu(t,e,i){const{windowSize:r,mask:s,maxNumber:n,shiftBy:o}=i;let a=Number(t&s),c=t>>o;a>r&&(a-=n,c+=xi);const u=e*r,h=u+Math.abs(a)-1,l=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:h,isZero:l,isNeg:f,isNegF:p,offsetF:u}}function hE(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function lE(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const zn=new WeakMap,$f=new WeakMap;function Kn(t){return $f.get(t)||1}function fu(t){if(t!==Qi)throw new Error("invalid wNAF")}function fE(t,e){return{constTimeNegate:Tr,hasPrecomputes(i){return Kn(i)!==1},unsafeLadder(i,r,s=t.ZERO){let n=i;for(;r>Qi;)r&xi&&(s=s.add(n)),n=n.double(),r>>=xi;return s},precomputeWindow(i,r){const{windows:s,windowSize:n}=jn(r,e),o=[];let a=i,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let h=1;h<n;h++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(i,r,s){let n=t.ZERO,o=t.BASE;const a=jn(i,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:h,isZero:l,isNeg:f,isNegF:p,offsetF:d}=lu(s,c,a);s=u,l?o=o.add(Tr(p,r[d])):n=n.add(Tr(f,r[h]))}return fu(s),{p:n,f:o}},wNAFUnsafe(i,r,s,n=t.ZERO){const o=jn(i,e);for(let a=0;a<o.windows&&s!==Qi;a++){const{nextN:c,offset:u,isZero:h,isNeg:l}=lu(s,a,o);if(s=c,!h){const f=r[u];n=n.add(l?f.negate():f)}}return fu(s),n},getPrecomputes(i,r,s){let n=zn.get(r);return n||(n=this.precomputeWindow(r,i),i!==1&&(typeof s=="function"&&(n=s(n)),zn.set(r,n))),n},wNAFCached(i,r,s){const n=Kn(i);return this.wNAF(n,this.getPrecomputes(n,i,s),r)},wNAFCachedUnsafe(i,r,s,n){const o=Kn(i);return o===1?this.unsafeLadder(i,r,n):this.wNAFUnsafe(o,this.getPrecomputes(o,i,s),r,n)},setWindowSize(i,r){Af(r,e),$f.set(i,r),zn.delete(i)}}}function dE(t,e,i,r){let s=e,n=t.ZERO,o=t.ZERO;for(;i>Qi||r>Qi;)i&xi&&(n=n.add(s)),r&xi&&(o=o.add(s)),s=s.double(),i>>=xi,r>>=xi;return{p1:n,p2:o}}function pE(t,e,i,r){hE(i,t),lE(r,e);const s=i.length,n=r.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Q2(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=cn(c),h=new Array(Number(u)+1).fill(o),l=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=l;p>=0;p-=c){h.fill(o);for(let g=0;g<n;g++){const y=r[g],E=Number(y>>BigInt(p)&u);h[E]=h[E].add(i[g])}let d=o;for(let g=h.length-1,y=o;g>0;g--)y=y.add(h[g]),d=d.add(y);if(f=f.add(d),p!==0)for(let g=0;g<c;g++)f=f.double()}return f}function du(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return nE(e),e}else return or(t)}function gE(t,e,i={}){if(!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const o of["p","n","h"]){const a=e[o];if(!(typeof a=="bigint"&&a>Qi))throw new Error(`CURVE.${o} must be positive bigint`)}const r=du(e.p,i.Fp),s=du(e.n,i.Fn),n=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const o of n)if(!r.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const wr=BigInt(0),ji=BigInt(1),vs=BigInt(2);function yE(t){return un(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function wE(t){const e=yE(t),{P:i,type:r,adjustScalarBytes:s,powPminus2:n,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||nr,u=a?255:448,h=a?32:56,l=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?vs**BigInt(254):vs**BigInt(447),d=a?BigInt(8)*vs**BigInt(251)-ji:BigInt(4)*vs**BigInt(445)-ji,g=p+d+ji,y=w=>ut(w,i),E=v(l);function v(w){return xa(y(w),h)}function m(w){const O=We("u coordinate",w,h);return a&&(O[31]&=127),y(Ks(O))}function D(w){return Ks(s(We("scalar",w,h)))}function I(w,O){const _=C(m(O),D(w));if(_===wr)throw new Error("invalid private or public key received");return v(_)}function R(w){return I(w,E)}function U(w,O,_){const $=y(w*(O-_));return O=y(O-$),_=y(_+$),{x_2:O,x_3:_}}function C(w,O){$o("u",w,wr,i),$o("scalar",O,p,g);const _=O,$=w;let P=ji,k=wr,x=w,b=ji,S=wr;for(let A=BigInt(u-1);A>=wr;A--){const B=_>>A&ji;S^=B,{x_2:P,x_3:x}=U(S,P,x),{x_2:k,x_3:b}=U(S,k,b),S=B;const N=P+k,j=y(N*N),z=P-k,K=y(z*z),V=j-K,H=x+b,re=x-b,ie=y(re*N),J=y(H*z),fe=ie+J,Ie=ie-J;x=y(fe*fe),b=y($*y(Ie*Ie)),P=y(j*K),k=y(V*(j+y(f*V)))}({x_2:P,x_3:x}=U(S,P,x)),{x_2:k,x_3:b}=U(S,k,b);const T=n(k);return y(P*T)}return{scalarMult:I,scalarMultBase:R,getSharedSecret:(w,O)=>I(w,O),getPublicKey:w=>R(w),utils:{randomPrivateKey:()=>c(h)},GuBytes:E.slice()}}BigInt(0);const mE=BigInt(1),pu=BigInt(2),bE=BigInt(3),vE=BigInt(5),EE=BigInt(8),Of={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:EE,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _E(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),s=BigInt(80),n=Of.p,o=t*t%n*t%n,a=gt(o,pu,n)*o%n,c=gt(a,mE,n)*t%n,u=gt(c,vE,n)*c%n,h=gt(u,e,n)*u%n,l=gt(h,i,n)*h%n,f=gt(l,r,n)*l%n,p=gt(f,s,n)*f%n,d=gt(p,s,n)*f%n,g=gt(d,e,n)*u%n;return{pow_p_5_8:gt(g,pu,n)*t%n,b2:o}}function xE(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Oo=(()=>{const t=Of.p;return wE({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:i,b2:r}=_E(e);return ut(gt(i,bE,t)*r,t)},adjustScalarBytes:xE})})();function gu(t){t.lowS!==void 0&&zs("lowS",t.lowS),t.prehash!==void 0&&zs("prehash",t.prehash)}class IE extends Error{constructor(e=""){super(e)}}const qt={Err:IE,_tlv:{encode:(t,e)=>{const{Err:i}=qt;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length&1)throw new i("tlv.encode: unpadded data");const r=e.length/2,s=bs(r);if(s.length/2&128)throw new i("tlv.encode: long form length too big");const n=r>127?bs(s.length/2|128):"";return bs(t)+n+s+e},decode(t,e){const{Err:i}=qt;let r=0;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new i("tlv.decode: wrong tlv");const s=e[r++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new i("tlv.decode(long): indefinite length not supported");if(c>4)throw new i("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new i("tlv.decode: length bytes not complete");if(u[0]===0)throw new i("tlv.decode(long): zero leftmost byte");for(const h of u)o=o<<8|h;if(r+=c,o<128)throw new i("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new i("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=qt;if(t<Cr)throw new e("integer: negative integers are not allowed");let i=bs(t);if(Number.parseInt(i[0],16)&8&&(i="00"+i),i.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return i},decode(t){const{Err:e}=qt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return an(t)}},toSig(t){const{Err:e,_int:i,_tlv:r}=qt,s=We("signature",t),{v:n,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,n),{v:u,l:h}=r.decode(2,c);if(h.length)throw new e("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(u)}},hexFromSig(t){const{_tlv:e,_int:i}=qt,r=e.encode(2,i.encode(t.r)),s=e.encode(2,i.encode(t.s)),n=r+s;return e.encode(48,n)}},Cr=BigInt(0),Pr=BigInt(1),SE=BigInt(2),Es=BigInt(3),DE=BigInt(4);function AE(t,e,i){function r(s){const n=t.sqr(s),o=t.mul(n,s);return t.add(t.add(o,t.mul(s,e)),i)}return r}function Tf(t,e,i){const{BYTES:r}=t;function s(n){let o;if(typeof n=="bigint")o=n;else{let a=We("private key",n);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{o=t.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof n}`)}}if(i&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return s}function $E(t,e={}){const{Fp:i,Fn:r}=gE("weierstrass",t,e),{h:s,n}=t;un(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!i.is0(t.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(C,w,O){const{x:_,y:$}=w.toAffine(),P=i.toBytes(_);if(zs("isCompressed",O),O){a();const k=!i.isOdd($);return Ei(Cf(k),P)}else return Ei(Uint8Array.of(4),P,i.toBytes($))}function u(C){lt(C);const w=i.BYTES,O=w+1,_=2*w+1,$=C.length,P=C[0],k=C.subarray(1);if($===O&&(P===2||P===3)){const x=i.fromBytes(k);if(!i.isValid(x))throw new Error("bad point: is not on curve, wrong x");const b=f(x);let S;try{S=i.sqrt(b)}catch(A){const B=A instanceof Error?": "+A.message:"";throw new Error("bad point: is not on curve, sqrt error"+B)}a();const T=i.isOdd(S);return(P&1)===1!==T&&(S=i.neg(S)),{x,y:S}}else if($===_&&P===4){const x=i.fromBytes(k.subarray(w*0,w*1)),b=i.fromBytes(k.subarray(w*1,w*2));if(!p(x,b))throw new Error("bad point: is not on curve");return{x,y:b}}else throw new Error(`bad point: got length ${$}, expected compressed=${O} or uncompressed=${_}`)}const h=e.toBytes||c,l=e.fromBytes||u,f=AE(i,t.a,t.b);function p(C,w){const O=i.sqr(w),_=f(C);return i.eql(O,_)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const d=i.mul(i.pow(t.a,Es),DE),g=i.mul(i.sqr(t.b),BigInt(27));if(i.is0(i.add(d,g)))throw new Error("bad curve params: a or b");function y(C,w,O=!1){if(!i.isValid(w)||O&&i.is0(w))throw new Error(`bad point coordinate ${C}`);return w}function E(C){if(!(C instanceof I))throw new Error("ProjectivePoint expected")}const v=cu((C,w)=>{const{px:O,py:_,pz:$}=C;if(i.eql($,i.ONE))return{x:O,y:_};const P=C.is0();w==null&&(w=P?i.ONE:i.inv($));const k=i.mul(O,w),x=i.mul(_,w),b=i.mul($,w);if(P)return{x:i.ZERO,y:i.ZERO};if(!i.eql(b,i.ONE))throw new Error("invZ was invalid");return{x:k,y:x}}),m=cu(C=>{if(C.is0()){if(e.allowInfinityPoint&&!i.is0(C.py))return;throw new Error("bad point: ZERO")}const{x:w,y:O}=C.toAffine();if(!i.isValid(w)||!i.isValid(O))throw new Error("bad point: x or y not field elements");if(!p(w,O))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function D(C,w,O,_,$){return O=new I(i.mul(O.px,C),O.py,O.pz),w=Tr(_,w),O=Tr($,O),w.add(O)}class I{constructor(w,O,_){this.px=y("x",w),this.py=y("y",O,!0),this.pz=y("z",_),Object.freeze(this)}static fromAffine(w){const{x:O,y:_}=w||{};if(!w||!i.isValid(O)||!i.isValid(_))throw new Error("invalid affine point");if(w instanceof I)throw new Error("projective point not allowed");return i.is0(O)&&i.is0(_)?I.ZERO:new I(O,_,i.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(w){return uE(I,"pz",w)}static fromBytes(w){return lt(w),I.fromHex(w)}static fromHex(w){const O=I.fromAffine(l(We("pointHex",w)));return O.assertValidity(),O}static fromPrivateKey(w){const O=Tf(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return I.BASE.multiply(O(w))}static msm(w,O){return pE(I,r,w,O)}precompute(w=8,O=!0){return U.setWindowSize(this,w),O||this.multiply(Es),this}_setWindowSize(w){this.precompute(w)}assertValidity(){m(this)}hasEvenY(){const{y:w}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(w)}equals(w){E(w);const{px:O,py:_,pz:$}=this,{px:P,py:k,pz:x}=w,b=i.eql(i.mul(O,x),i.mul(P,$)),S=i.eql(i.mul(_,x),i.mul(k,$));return b&&S}negate(){return new I(this.px,i.neg(this.py),this.pz)}double(){const{a:w,b:O}=t,_=i.mul(O,Es),{px:$,py:P,pz:k}=this;let x=i.ZERO,b=i.ZERO,S=i.ZERO,T=i.mul($,$),A=i.mul(P,P),B=i.mul(k,k),N=i.mul($,P);return N=i.add(N,N),S=i.mul($,k),S=i.add(S,S),x=i.mul(w,S),b=i.mul(_,B),b=i.add(x,b),x=i.sub(A,b),b=i.add(A,b),b=i.mul(x,b),x=i.mul(N,x),S=i.mul(_,S),B=i.mul(w,B),N=i.sub(T,B),N=i.mul(w,N),N=i.add(N,S),S=i.add(T,T),T=i.add(S,T),T=i.add(T,B),T=i.mul(T,N),b=i.add(b,T),B=i.mul(P,k),B=i.add(B,B),T=i.mul(B,N),x=i.sub(x,T),S=i.mul(B,A),S=i.add(S,S),S=i.add(S,S),new I(x,b,S)}add(w){E(w);const{px:O,py:_,pz:$}=this,{px:P,py:k,pz:x}=w;let b=i.ZERO,S=i.ZERO,T=i.ZERO;const A=t.a,B=i.mul(t.b,Es);let N=i.mul(O,P),j=i.mul(_,k),z=i.mul($,x),K=i.add(O,_),V=i.add(P,k);K=i.mul(K,V),V=i.add(N,j),K=i.sub(K,V),V=i.add(O,$);let H=i.add(P,x);return V=i.mul(V,H),H=i.add(N,z),V=i.sub(V,H),H=i.add(_,$),b=i.add(k,x),H=i.mul(H,b),b=i.add(j,z),H=i.sub(H,b),T=i.mul(A,V),b=i.mul(B,z),T=i.add(b,T),b=i.sub(j,T),T=i.add(j,T),S=i.mul(b,T),j=i.add(N,N),j=i.add(j,N),z=i.mul(A,z),V=i.mul(B,V),j=i.add(j,z),z=i.sub(N,z),z=i.mul(A,z),V=i.add(V,z),N=i.mul(j,V),S=i.add(S,N),N=i.mul(H,V),b=i.mul(K,b),b=i.sub(b,N),N=i.mul(K,j),T=i.mul(H,T),T=i.add(T,N),new I(b,S,T)}subtract(w){return this.add(w.negate())}is0(){return this.equals(I.ZERO)}multiply(w){const{endo:O}=e;if(!r.isValidNot0(w))throw new Error("invalid scalar: out of range");let _,$;const P=k=>U.wNAFCached(this,k,I.normalizeZ);if(O){const{k1neg:k,k1:x,k2neg:b,k2:S}=O.splitScalar(w),{p:T,f:A}=P(x),{p:B,f:N}=P(S);$=A.add(N),_=D(O.beta,T,B,k,b)}else{const{p:k,f:x}=P(w);_=k,$=x}return I.normalizeZ([_,$])[0]}multiplyUnsafe(w){const{endo:O}=e,_=this;if(!r.isValid(w))throw new Error("invalid scalar: out of range");if(w===Cr||_.is0())return I.ZERO;if(w===Pr)return _;if(U.hasPrecomputes(this))return this.multiply(w);if(O){const{k1neg:$,k1:P,k2neg:k,k2:x}=O.splitScalar(w),{p1:b,p2:S}=dE(I,_,P,x);return D(O.beta,b,S,$,k)}else return U.wNAFCachedUnsafe(_,w)}multiplyAndAddUnsafe(w,O,_){const $=this.multiplyUnsafe(O).add(w.multiplyUnsafe(_));return $.is0()?void 0:$}toAffine(w){return v(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return s===Pr?!0:w?w(I,this):U.wNAFCachedUnsafe(this,n).is0()}clearCofactor(){const{clearCofactor:w}=e;return s===Pr?this:w?w(I,this):this.multiplyUnsafe(s)}toBytes(w=!0){return zs("isCompressed",w),this.assertValidity(),h(I,this,w)}toRawBytes(w=!0){return this.toBytes(w)}toHex(w=!0){return zr(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}I.BASE=new I(t.Gx,t.Gy,i.ONE),I.ZERO=new I(i.ZERO,i.ONE,i.ZERO),I.Fp=i,I.Fn=r;const R=r.BITS,U=fE(I,e.endo?Math.ceil(R/2):R);return I}function Cf(t){return Uint8Array.of(t?2:3)}function OE(t,e,i={}){un(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=e.randomBytes||nr,s=e.hmac||((_,...$)=>nn(e.hash,_,Ei(...$))),{Fp:n,Fn:o}=t,{ORDER:a,BITS:c}=o;function u(_){const $=a>>Pr;return _>$}function h(_){return u(_)?o.neg(_):_}function l(_,$){if(!o.isValidNot0($))throw new Error(`invalid signature ${_}: out of range 1..CURVE.n`)}class f{constructor($,P,k){l("r",$),l("s",P),this.r=$,this.s=P,k!=null&&(this.recovery=k),Object.freeze(this)}static fromCompact($){const P=o.BYTES,k=We("compactSignature",$,P*2);return new f(o.fromBytes(k.subarray(0,P)),o.fromBytes(k.subarray(P,P*2)))}static fromDER($){const{r:P,s:k}=qt.toSig(We("DER",$));return new f(P,k)}assertValidity(){}addRecoveryBit($){return new f(this.r,this.s,$)}recoverPublicKey($){const P=n.ORDER,{r:k,s:x,recovery:b}=this;if(b==null||![0,1,2,3].includes(b))throw new Error("recovery id invalid");if(a*SE<P&&b>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=b===2||b===3?k+a:k;if(!n.isValid(S))throw new Error("recovery id 2 or 3 invalid");const T=n.toBytes(S),A=t.fromHex(Ei(Cf((b&1)===0),T)),B=o.inv(S),N=m(We("msgHash",$)),j=o.create(-N*B),z=o.create(x*B),K=t.BASE.multiplyUnsafe(j).add(A.multiplyUnsafe(z));if(K.is0())throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o.neg(this.s),this.recovery):this}toBytes($){if($==="compact")return Ei(o.toBytes(this.r),o.toBytes(this.s));if($==="der")return ma(qt.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return zr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return zr(this.toBytes("compact"))}}const p=Tf(o,i.allowedPrivateKeyLengths,i.wrapPrivateKey),d={isValidPrivateKey(_){try{return p(_),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const _=a;return cE(r(Df(_)),_)},precompute(_=8,$=t.BASE){return $.precompute(_,!1)}};function g(_,$=!0){return t.fromPrivateKey(_).toBytes($)}function y(_){if(typeof _=="bigint")return!1;if(_ instanceof t)return!0;const $=We("key",_).length,P=n.BYTES,k=P+1,x=2*P+1;if(!(i.allowedPrivateKeyLengths||o.BYTES===k))return $===k||$===x}function E(_,$,P=!0){if(y(_)===!0)throw new Error("first arg must be private key");if(y($)===!1)throw new Error("second arg must be public key");return t.fromHex($).multiply(p(_)).toBytes(P)}const v=e.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const $=an(_),P=_.length*8-c;return P>0?$>>BigInt(P):$},m=e.bits2int_modN||function(_){return o.create(v(_))},D=cn(c);function I(_){return $o("num < 2^"+c,_,Cr,D),o.toBytes(_)}function R(_,$,P=U){if(["recovered","canonical"].some(K=>K in P))throw new Error("sign() legacy options not supported");const{hash:k}=e;let{lowS:x,prehash:b,extraEntropy:S}=P;x==null&&(x=!0),_=We("msgHash",_),gu(P),b&&(_=We("prehashed msgHash",k(_)));const T=m(_),A=p($),B=[I(A),I(T)];if(S!=null&&S!==!1){const K=S===!0?r(n.BYTES):S;B.push(We("extraEntropy",K))}const N=Ei(...B),j=T;function z(K){const V=v(K);if(!o.isValidNot0(V))return;const H=o.inv(V),re=t.BASE.multiply(V).toAffine(),ie=o.create(re.x);if(ie===Cr)return;const J=o.create(H*o.create(j+ie*A));if(J===Cr)return;let fe=(re.x===ie?0:2)|Number(re.y&Pr),Ie=J;return x&&u(J)&&(Ie=h(J),fe^=1),new f(ie,Ie,fe)}return{seed:N,k2sig:z}}const U={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function w(_,$,P=U){const{seed:k,k2sig:x}=R(_,$,P);return X2(e.hash.outputLen,o.BYTES,s)(k,x)}t.BASE.precompute(8);function O(_,$,P,k=C){const x=_;$=We("msgHash",$),P=We("publicKey",P),gu(k);const{lowS:b,prehash:S,format:T}=k;if("strict"in k)throw new Error("options.strict was renamed to lowS");if(T!==void 0&&!["compact","der","js"].includes(T))throw new Error('format must be "compact", "der" or "js"');const A=typeof x=="string"||ga(x),B=!A&&!T&&typeof x=="object"&&x!==null&&typeof x.r=="bigint"&&typeof x.s=="bigint";if(!A&&!B)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,j;try{if(B)if(T===void 0||T==="js")N=new f(x.r,x.s);else throw new Error("invalid format");if(A){try{T!=="compact"&&(N=f.fromDER(x))}catch(fe){if(!(fe instanceof qt.Err))throw fe}!N&&T!=="der"&&(N=f.fromCompact(x))}j=t.fromHex(P)}catch{return!1}if(!N||b&&N.hasHighS())return!1;S&&($=e.hash($));const{r:z,s:K}=N,V=m($),H=o.inv(K),re=o.create(V*H),ie=o.create(z*H),J=t.BASE.multiplyUnsafe(re).add(j.multiplyUnsafe(ie));return J.is0()?!1:o.create(J.x)===z}return Object.freeze({getPublicKey:g,getSharedSecret:E,sign:w,verify:O,utils:d,Point:t,Signature:f})}function TE(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},i=t.Fp,r=or(e.n,t.nBitLength),s={Fp:i,Fn:r,allowedPrivateKeyLengths:t.allowedPrivateKeyLengths,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,wrapPrivateKey:t.wrapPrivateKey,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function CE(t){const{CURVE:e,curveOpts:i}=TE(t),r={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:i,ecdsaOpts:r}}function PE(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function RE(t){const{CURVE:e,curveOpts:i,ecdsaOpts:r}=CE(t),s=$E(e,i),n=OE(s,r,i);return PE(t,n)}function To(t,e){const i=r=>RE({...t,hash:r});return{...i(e),create:i}}const Pf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Rf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ff={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},FE=or(Pf.p),BE=or(Rf.p),UE=or(Ff.p),NE=To({...Pf,Fp:FE,lowS:!1},sn);To({...Rf,Fp:BE,lowS:!1},Kv),To({...Ff,Fp:UE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},zv);const kE=NE,Bf="base10",qe="base16",Ye="base64pad",ai="base64url",is="utf8",Uf=0,zt=1,rs=2,LE=0,yu=1,Rr=12,Ia=32;function ME(){const t=Oo.utils.randomPrivateKey(),e=Oo.getPublicKey(t);return{privateKey:Ze(t,qe),publicKey:Ze(e,qe)}}function Co(){const t=nr(Ia);return Ze(t,qe)}function qE(t,e){const i=Oo.getSharedSecret(ht(t,qe),ht(e,qe)),r=J2(on,i,void 0,void 0,Ia);return Ze(r,qe)}function Ts(t){const e=on(ht(t,qe));return Ze(e,qe)}function at(t){const e=on(ht(t,is));return Ze(e,qe)}function Nf(t){return ht(`${t}`,Bf)}function Oi(t){return Number(Ze(t,Bf))}function kf(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Lf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),i=(4-e.length%4)%4;return e+"=".repeat(i)}function jE(t){const e=Nf(typeof t.type<"u"?t.type:Uf);if(Oi(e)===zt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof t.senderPublicKey<"u"?ht(t.senderPublicKey,qe):void 0,r=typeof t.iv<"u"?ht(t.iv,qe):nr(Rr),s=ht(t.symKey,qe),n=wf(s,r).encrypt(ht(t.message,is)),o=Mf({type:e,sealed:n,iv:r,senderPublicKey:i});return t.encoding===ai?kf(o):o}function zE(t){const e=ht(t.symKey,qe),{sealed:i,iv:r}=Vr({encoded:t.encoded,encoding:t.encoding}),s=wf(e,r).decrypt(i);if(s===null)throw new Error("Failed to decrypt");return Ze(s,is)}function KE(t,e){const i=Nf(rs),r=nr(Rr),s=ht(t,is),n=Mf({type:i,sealed:s,iv:r});return e===ai?kf(n):n}function VE(t,e){const{sealed:i}=Vr({encoded:t,encoding:e});return Ze(i,is)}function Mf(t){if(Oi(t.type)===rs)return Ze(Or([t.type,t.sealed]),Ye);if(Oi(t.type)===zt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ze(Or([t.type,t.senderPublicKey,t.iv,t.sealed]),Ye)}return Ze(Or([t.type,t.iv,t.sealed]),Ye)}function Vr(t){const e=(t.encoding||Ye)===ai?Lf(t.encoded):t.encoded,i=ht(e,Ye),r=i.slice(LE,yu),s=yu;if(Oi(r)===zt){const c=s+Ia,u=c+Rr,h=i.slice(s,c),l=i.slice(c,u),f=i.slice(u);return{type:r,sealed:f,iv:l,senderPublicKey:h}}if(Oi(r)===rs){const c=i.slice(s),u=nr(Rr);return{type:r,sealed:c,iv:u}}const n=s+Rr,o=i.slice(s,n),a=i.slice(n);return{type:r,sealed:a,iv:o}}function HE(t,e){const i=Vr({encoded:t,encoding:e?.encoding});return qf({type:Oi(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?Ze(i.senderPublicKey,qe):void 0,receiverPublicKey:e?.receiverPublicKey})}function qf(t){const e=t?.type||Uf;if(e===zt){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function wu(t){return t.type===zt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function mu(t){return t.type===rs}function WE(t){const e=Buffer.from(t.x,"base64"),i=Buffer.from(t.y,"base64");return Or([new Uint8Array([4]),e,i])}function GE(t,e){const[i,r,s]=t.split("."),n=Buffer.from(Lf(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${i}.${r}`,u=on(c),h=WE(e);if(!kE.verify(Or([o,a]),u,h))throw new Error("Invalid signature");return ho(t).payload}const YE="irn";function Vs(t){return t?.relay||{protocol:YE}}function Wi(t){const e=mb[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function JE(t,e="-"){const i={},r="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(r)){const n=s.replace(r,""),o=t[s];i[n]=o}}),i}function bu(t){if(!t.includes("wc:")){const u=Zl(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),i=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),s=t.substring(e+1,i).split("@"),n=typeof i<"u"?t.substring(i):"",o=new URLSearchParams(n),a={};o.forEach((u,h)=>{a[h]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:ZE(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:JE(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function ZE(t){return t.startsWith("//")?t.substring(2):t}function QE(t,e="-"){const i="relay",r={};return Object.keys(t).forEach(s=>{const n=s,o=i+e+n;t[n]&&(r[o]=t[n])}),r}function vu(t){const e=new URLSearchParams,i=QE(t.relay);Object.keys(i).sort().forEach(s=>{e.set(s,i[s])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function _s(t,e,i){return`${t}?wc_ev=${i}&topic=${e}`}var XE=Object.defineProperty,e3=Object.defineProperties,t3=Object.getOwnPropertyDescriptors,Eu=Object.getOwnPropertySymbols,i3=Object.prototype.hasOwnProperty,r3=Object.prototype.propertyIsEnumerable,_u=(t,e,i)=>e in t?XE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,s3=(t,e)=>{for(var i in e||(e={}))i3.call(e,i)&&_u(t,i,e[i]);if(Eu)for(var i of Eu(e))r3.call(e,i)&&_u(t,i,e[i]);return t},n3=(t,e)=>e3(t,t3(e));function ar(t){const e=[];return t.forEach(i=>{const[r,s]=i.split(":");e.push(`${r}:${s}`)}),e}function o3(t){const e=[];return Object.values(t).forEach(i=>{e.push(...ar(i.accounts))}),e}function a3(t,e){const i=[];return Object.values(t).forEach(r=>{ar(r.accounts).includes(e)&&i.push(...r.methods)}),i}function c3(t,e){const i=[];return Object.values(t).forEach(r=>{ar(r.accounts).includes(e)&&i.push(...r.events)}),i}function jf(t){return t.includes(":")}function u3(t){return jf(t)?t.split(":")[0]:t}function xu(t){var e,i,r;const s={};if(!Hr(t))return s;for(const[n,o]of Object.entries(t)){const a=jf(n)?[n]:o.chains,c=o.methods||[],u=o.events||[],h=u3(n);s[h]=n3(s3({},s[h]),{chains:Ii(a,(e=s[h])==null?void 0:e.chains),methods:Ii(c,(i=s[h])==null?void 0:i.methods),events:Ii(u,(r=s[h])==null?void 0:r.events)})}return s}function h3(t){const e={};return t?.forEach(i=>{var r;const[s,n]=i.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(i),(r=e[s].chains)==null||r.push(`${s}:${n}`)}),e}function Iu(t,e){e=e.map(r=>r.replace("did:pkh:",""));const i=h3(e);for(const[r,s]of Object.entries(i))s.methods?s.methods=Ii(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return i}function l3(t,e){var i,r,s,n,o,a;const c=xu(t),u=xu(e),h={},l=Object.keys(c).concat(Object.keys(u));for(const f of l)h[f]={chains:Ii((i=c[f])==null?void 0:i.chains,(r=u[f])==null?void 0:r.chains),methods:Ii((s=c[f])==null?void 0:s.methods,(n=u[f])==null?void 0:n.methods),events:Ii((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return h}const f3={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},d3={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function M(t,e){const{message:i,code:r}=d3[t];return{message:e?`${i} ${e}`:i,code:r}}function le(t,e){const{message:i,code:r}=f3[t];return{message:e?`${i} ${e}`:i,code:r}}function Xi(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Hr(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function ve(t){return typeof t>"u"}function ye(t,e){return e&&ve(t)?!0:typeof t=="string"&&!!t.trim().length}function Sa(t,e){return e&&ve(t)?!0:typeof t=="number"&&!isNaN(t)}function p3(t,e){const{requiredNamespaces:i}=e,r=Object.keys(t.namespaces),s=Object.keys(i);let n=!0;return vi(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],h=ar(a),l=i[o];(!vi(la(o,l),h)||!vi(l.methods,c)||!vi(l.events,u))&&(n=!1)}),n):!1}function Hs(t){return ye(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function g3(t){if(ye(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const i=e[0]+":"+e[1];return!!e[2]&&Hs(i)}}return!1}function y3(t){function e(i){try{return typeof new URL(i)<"u"}catch{return!1}}try{if(ye(t,!1)){if(e(t))return!0;const i=Zl(t);return e(i)}}catch{}return!1}function w3(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function m3(t){return t?.topic}function b3(t,e){let i=null;return ye(t?.publicKey,!1)||(i=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),i}function Su(t){let e=!0;return Xi(t)?t.length&&(e=t.every(i=>ye(i,!1))):e=!1,e}function v3(t,e,i){let r=null;return Xi(e)&&e.length?e.forEach(s=>{r||Hs(s)||(r=le("UNSUPPORTED_CHAINS",`${i}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Hs(t)||(r=le("UNSUPPORTED_CHAINS",`${i}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function E3(t,e,i){let r=null;return Object.entries(t).forEach(([s,n])=>{if(r)return;const o=v3(s,la(s,n),`${e} ${i}`);o&&(r=o)}),r}function _3(t,e){let i=null;return Xi(t)?t.forEach(r=>{i||g3(r)||(i=le("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):i=le("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function x3(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const s=_3(r?.accounts,`${e} namespace`);s&&(i=s)}),i}function I3(t,e){let i=null;return Su(t?.methods)?Su(t?.events)||(i=le("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):i=le("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),i}function zf(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const s=I3(r,`${e}, namespace`);s&&(i=s)}),i}function S3(t,e,i){let r=null;if(t&&Hr(t)){const s=zf(t,e);s&&(r=s);const n=E3(t,e,i);n&&(r=n)}else r=M("MISSING_OR_INVALID",`${e}, ${i} should be an object with data`);return r}function Vn(t,e){let i=null;if(t&&Hr(t)){const r=zf(t,e);r&&(i=r);const s=x3(t,e);s&&(i=s)}else i=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return i}function Kf(t){return ye(t.protocol,!0)}function D3(t,e){let i=!1;return e&&!t?i=!0:t&&Xi(t)&&t.length&&t.forEach(r=>{i=Kf(r)}),i}function A3(t){return typeof t=="number"}function He(t){return typeof t<"u"&&typeof t!==null}function $3(t){return!(!t||typeof t!="object"||!t.code||!Sa(t.code,!1)||!t.message||!ye(t.message,!1))}function O3(t){return!(ve(t)||!ye(t.method,!1))}function T3(t){return!(ve(t)||ve(t.result)&&ve(t.error)||!Sa(t.id,!1)||!ye(t.jsonrpc,!1))}function C3(t){return!(ve(t)||!ye(t.name,!1))}function Du(t,e){return!(!Hs(e)||!o3(t).includes(e))}function P3(t,e,i){return ye(i,!1)?a3(t,e).includes(i):!1}function R3(t,e,i){return ye(i,!1)?c3(t,e).includes(i):!1}function Au(t,e,i){let r=null;const s=F3(t),n=B3(e),o=Object.keys(s),a=Object.keys(n),c=$u(Object.keys(t)),u=$u(Object.keys(e)),h=c.filter(l=>!u.includes(l));return h.length&&(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.
Required: ${h.toString()}
Received: ${Object.keys(e).toString()}`)),vi(o,a)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.
Required: ${o.toString()}
Approved: ${a.toString()}`)),Object.keys(e).forEach(l=>{if(!l.includes(":")||r)return;const f=ar(e[l].accounts);f.includes(l)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${l}
Required: ${l}
Approved: ${f.toString()}`))}),o.forEach(l=>{r||(vi(s[l].methods,n[l].methods)?vi(s[l].events,n[l].events)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${l}`)):r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${l}`))}),r}function F3(t){const e={};return Object.keys(t).forEach(i=>{var r;i.includes(":")?e[i]=t[i]:(r=t[i].chains)==null||r.forEach(s=>{e[s]={methods:t[i].methods,events:t[i].events}})}),e}function $u(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function B3(t){const e={};return Object.keys(t).forEach(i=>{i.includes(":")?e[i]=t[i]:ar(t[i].accounts)?.forEach(s=>{e[s]={accounts:t[i].accounts.filter(n=>n.includes(`${s}:`)),methods:t[i].methods,events:t[i].events}})}),e}function U3(t,e){return Sa(t,!1)&&t<=e.max&&t>=e.min}function Ou(){const t=es();return new Promise(e=>{switch(t){case it.browser:e(N3());break;case it.reactNative:e(k3());break;case it.node:e(L3());break;default:e(!0)}})}function N3(){return sr()&&navigator?.onLine}async function k3(){return li()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function L3(){return!0}function M3(t){switch(es()){case it.browser:q3(t);break;case it.reactNative:j3(t);break}}function q3(t){!li()&&sr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function j3(t){li()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function z3(){var t;return sr()&&Di()?((t=Di())==null?void 0:t.visibilityState)==="visible":!0}const Hn={};class mr{static get(e){return Hn[e]}static set(e,i){Hn[e]=i}static delete(e){delete Hn[e]}}function K3(t){const e=Qr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function V3({publicKey:t,signature:e,payload:i}){var r;const s=Po(i.method),n=128|parseInt(((r=i.version)==null?void 0:r.toString())||"4"),o=G3(i.address),a=i.era==="00"?new Uint8Array([0]):Po(i.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(i.nonce,16),u=new Uint8Array([c&255,c>>8&255]),h=BigInt(`0x${W3(i.tip)}`),l=J3(h),f=new Uint8Array([0,...t,o,...e,...a,...u,...l,...s]),p=Y3(f.length+1);return new Uint8Array([...p,n,...f])}function H3(t){const e=Po(t),i=Tb.blake2b(e,void 0,32);return"0x"+Buffer.from(i).toString("hex")}function Po(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function W3(t){return t.startsWith("0x")?t.slice(2):t}function G3(t){const e=Qr.decode(t)[0];return e===42?0:e===60?2:1}function Y3(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function J3(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function Z3(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),i=K3(t.transaction.address),r=V3({publicKey:i,signature:e,payload:t.transaction}),s=Buffer.from(r).toString("hex");return H3(s)}const Q3="PARSE_ERROR",X3="INVALID_REQUEST",e_="METHOD_NOT_FOUND",t_="INVALID_PARAMS",Vf="INTERNAL_ERROR",Da="SERVER_ERROR",i_=[-32700,-32600,-32601,-32602,-32603],Fr={[Q3]:{code:-32700,message:"Parse error"},[X3]:{code:-32600,message:"Invalid Request"},[e_]:{code:-32601,message:"Method not found"},[t_]:{code:-32602,message:"Invalid params"},[Vf]:{code:-32603,message:"Internal error"},[Da]:{code:-32e3,message:"Server error"}},Hf=Da;function r_(t){return i_.includes(t)}function Tu(t){return Object.keys(Fr).includes(t)?Fr[t]:Fr[Hf]}function s_(t){const e=Object.values(Fr).find(i=>i.code===t);return e||Fr[Hf]}function n_(t,e,i){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${e}`):t}var Wf={},Ut={},Cu;function o_(){if(Cu)return Ut;Cu=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.isBrowserCryptoAvailable=Ut.getSubtleCrypto=Ut.getBrowerCrypto=void 0;function t(){return(Mt.commonjsGlobal===null||Mt.commonjsGlobal===void 0?void 0:Mt.commonjsGlobal.crypto)||(Mt.commonjsGlobal===null||Mt.commonjsGlobal===void 0?void 0:Mt.commonjsGlobal.msCrypto)||{}}Ut.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Ut.getSubtleCrypto=e;function i(){return!!t()&&!!e()}return Ut.isBrowserCryptoAvailable=i,Ut}var Nt={},Pu;function a_(){if(Pu)return Nt;Pu=1,Object.defineProperty(Nt,"__esModule",{value:!0}),Nt.isBrowser=Nt.isNode=Nt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Nt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Nt.isNode=e;function i(){return!t()&&!e()}return Nt.isBrowser=i,Nt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gr;e.__exportStar(o_(),t),e.__exportStar(a_(),t)})(Wf);function St(t=3){const e=Date.now()*Math.pow(10,t),i=Math.floor(Math.random()*Math.pow(10,t));return e+i}function ci(t=6){return BigInt(St(t))}function jt(t,e,i){return{id:i||St(),jsonrpc:"2.0",method:t,params:e}}function Wr(t,e){return{id:t,jsonrpc:"2.0",result:e}}function hn(t,e,i){return{id:t,jsonrpc:"2.0",error:c_(e,i)}}function c_(t,e){return typeof t>"u"?Tu(Vf):(typeof t=="string"&&(t=Object.assign(Object.assign({},Tu(Da)),{message:t})),typeof e<"u"&&(t.data=e),r_(t.code)&&(t=s_(t.code)),t)}class Gf{}let u_=class extends Gf{constructor(e){super()}},h_=class extends Gf{constructor(){super()}};class l_ extends h_{constructor(e){super()}}const f_="^wss?:";function d_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function p_(t,e){const i=d_(t);return typeof i>"u"?!1:new RegExp(e).test(i)}function Ru(t){return p_(t,f_)}function g_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Yf(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Aa(t){return Yf(t)&&"method"in t}function ln(t){return Yf(t)&&(Dt(t)||ct(t))}function Dt(t){return"result"in t}function ct(t){return"error"in t}let Jf=class extends l_{constructor(e){super(e),this.events=new rt.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async request(e,i){return this.requestStrict(jt(e.method,e.params||[],e.id||ci().toString()),i)}async requestStrict(e,i){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{ct(n)?s(n.error):r(n.result)});try{await this.connection.send(e,i)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ln(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}};const y_=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),w_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Fu=t=>t.split("?")[0],Bu=10,m_=y_();let b_=class{constructor(e){if(this.url=e,this.events=new rt.EventEmitter,this.registering=!1,!Ru(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,i)=>{if(typeof this.socket>"u"){i(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Si(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Ru(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((i,r)=>{const s=Wf.isReactNative()?void 0:{rejectUnauthorized:!g_(e)},n=new m_(e,[],s);w_()?n.onerror=o=>{const a=o;r(this.emitError(a.error))}:n.on("error",o=>{r(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),i(n)}})}onOpen(e){e.onmessage=i=>this.onPayload(i),e.onclose=i=>this.onClose(i),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?Yi(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),s=r.message||r.toString(),n=hn(e,s);this.events.emit("payload",n)}parseError(e,i=this.url){return n_(e,Fu(i),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Bu&&this.events.setMaxListeners(Bu)}emitError(e){const i=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Fu(this.url)}`));return this.events.emit("register_error",i),i}};const Zf="wc",Qf=2,Ws="core",Ct=`${Zf}@2:${Ws}:`,v_={name:Ws,logger:"error"},E_={database:":memory:"},__="crypto",Uu="client_ed25519_seed",x_=L.ONE_DAY,I_="keychain",S_="0.3",D_="messages",A_="0.3",$_=L.SIX_HOURS,O_="publisher",Xf="irn",T_="error",ed="wss://relay.walletconnect.org",C_="relayer",de={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},P_="_subscription",st={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},R_=.1,Ro="2.21.8",he={link_mode:"link_mode",relay:"relay"},Cs={inbound:"inbound",outbound:"outbound"},F_="0.3",B_="WALLETCONNECT_CLIENT_ID",Nu="WALLETCONNECT_LINK_MODE_APPS",et={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},U_="subscription",N_="0.3",k_="pairing",L_="0.3",br={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}}},bi={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},pt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},M_="history",q_="0.3",j_="expirer",ot={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},z_="0.3",K_="verify-api",V_="https://verify.walletconnect.com",td="https://verify.walletconnect.org",Br=td,H_=`${Br}/v3`,W_=[V_,td],G_="echo",Y_="https://echo.walletconnect.com",It={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},Lt={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"},ii={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"},vr={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"},gi={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"},Er={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"},J_=.1,Z_="event-client",Q_=86400,X_="https://pulse.walletconnect.org/batch";function ex(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(i[o]!==255)throw new TypeError(n+" is ambiguous");i[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),h=Math.log(256)/Math.log(a);function l(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,E=0,v=d.length;E!==v&&d[E]===0;)E++,g++;for(var m=(v-E)*h+1>>>0,D=new Uint8Array(m);E!==v;){for(var I=d[E],R=0,U=m-1;(I!==0||R<y)&&U!==-1;U--,R++)I+=256*D[U]>>>0,D[U]=I%a>>>0,I=I/a>>>0;if(I!==0)throw new Error("Non-zero carry");y=R,E++}for(var C=m-y;C!==m&&D[C]===0;)C++;for(var w=c.repeat(g);C<m;++C)w+=t.charAt(D[C]);return w}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,E=0;d[g]===c;)y++,g++;for(var v=(d.length-g)*u+1>>>0,m=new Uint8Array(v);d[g];){var D=i[d.charCodeAt(g)];if(D===255)return;for(var I=0,R=v-1;(D!==0||I<E)&&R!==-1;R--,I++)D+=a*m[R]>>>0,m[R]=D%256>>>0,D=D/256>>>0;if(D!==0)throw new Error("Non-zero carry");E=I,g++}if(d[g]!==" "){for(var U=v-E;U!==v&&m[U]===0;)U++;for(var C=new Uint8Array(y+(v-U)),w=y;U!==v;)C[w++]=m[U++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:l,decodeUnsafe:f,decode:p}}var tx=ex,ix=tx;const id=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")},rx=t=>new TextEncoder().encode(t),sx=t=>new TextDecoder().decode(t);class nx{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ox{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return rd(this,e)}}class ax{constructor(e){this.decoders=e}or(e){return rd(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const rd=(t,e)=>new ax({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class cx{constructor(e,i,r,s){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=s,this.encoder=new nx(e,i,r),this.decoder=new ox(e,i,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const fn=({name:t,prefix:e,encode:i,decode:r})=>new cx(t,e,i,r),ss=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:s}=ix(i,e);return fn({prefix:t,name:e,encode:r,decode:n=>id(s(n))})},ux=(t,e,i,r)=>{const s={};for(let h=0;h<e.length;++h)s[e[h]]=h;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*i/8|0);let a=0,c=0,u=0;for(let h=0;h<n;++h){const l=s[t[h]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|l,a+=i,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},hx=(t,e,i)=>{const r=e[e.length-1]==="=",s=(1<<i)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,n+=e[s&a>>o];if(o&&(n+=e[s&a<<i-o]),r)for(;n.length*i&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>fn({prefix:e,name:t,encode(s){return hx(s,r,i)},decode(s){return ux(s,r,i,t)}}),lx=fn({prefix:"\0",name:"identity",encode:t=>sx(t),decode:t=>rx(t)});var fx=Object.freeze({__proto__:null,identity:lx});const dx=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var px=Object.freeze({__proto__:null,base2:dx});const gx=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var yx=Object.freeze({__proto__:null,base8:gx});const wx=ss({prefix:"9",name:"base10",alphabet:"0123456789"});var mx=Object.freeze({__proto__:null,base10:wx});const bx=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),vx=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Ex=Object.freeze({__proto__:null,base16:bx,base16upper:vx});const _x=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),xx=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Ix=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Sx=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Dx=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ax=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$x=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Ox=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Tx=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Cx=Object.freeze({__proto__:null,base32:_x,base32upper:xx,base32pad:Ix,base32padupper:Sx,base32hex:Dx,base32hexupper:Ax,base32hexpad:$x,base32hexpadupper:Ox,base32z:Tx});const Px=ss({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Rx=ss({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Fx=Object.freeze({__proto__:null,base36:Px,base36upper:Rx});const Bx=ss({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Ux=ss({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Nx=Object.freeze({__proto__:null,base58btc:Bx,base58flickr:Ux});const kx=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Lx=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Mx=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),qx=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var jx=Object.freeze({__proto__:null,base64:kx,base64pad:Lx,base64url:Mx,base64urlpad:qx});const sd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),zx=sd.reduce((t,e,i)=>(t[i]=e,t),[]),Kx=sd.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function Vx(t){return t.reduce((e,i)=>(e+=zx[i],e),"")}function Hx(t){const e=[];for(const i of t){const r=Kx[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const Wx=fn({prefix:"🚀",name:"base256emoji",encode:Vx,decode:Hx});var Gx=Object.freeze({__proto__:null,base256emoji:Wx}),Yx=nd,ku=128,Jx=127,Zx=~Jx,Qx=Math.pow(2,31);function nd(t,e,i){e=e||[],i=i||0;for(var r=i;t>=Qx;)e[i++]=t&255|ku,t/=128;for(;t&Zx;)e[i++]=t&255|ku,t>>>=7;return e[i]=t|0,nd.bytes=i-r+1,e}var Xx=Fo,e8=128,Lu=127;function Fo(t,r){var i=0,r=r||0,s=0,n=r,o,a=t.length;do{if(n>=a)throw Fo.bytes=0,new RangeError("Could not decode varint");o=t[n++],i+=s<28?(o&Lu)<<s:(o&Lu)*Math.pow(2,s),s+=7}while(o>=e8);return Fo.bytes=n-r,i}var t8=Math.pow(2,7),i8=Math.pow(2,14),r8=Math.pow(2,21),s8=Math.pow(2,28),n8=Math.pow(2,35),o8=Math.pow(2,42),a8=Math.pow(2,49),c8=Math.pow(2,56),u8=Math.pow(2,63),h8=function(t){return t<t8?1:t<i8?2:t<r8?3:t<s8?4:t<n8?5:t<o8?6:t<a8?7:t<c8?8:t<u8?9:10},l8={encode:Yx,decode:Xx,encodingLength:h8},od=l8;const Mu=(t,e,i=0)=>(od.encode(t,e,i),e),qu=t=>od.encodingLength(t),Bo=(t,e)=>{const i=e.byteLength,r=qu(t),s=r+qu(i),n=new Uint8Array(s+i);return Mu(t,n,0),Mu(i,n,r),n.set(e,s),new f8(t,i,e,n)};class f8{constructor(e,i,r,s){this.code=e,this.size=i,this.digest=r,this.bytes=s}}const ad=({name:t,code:e,encode:i})=>new d8(t,e,i);class d8{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Bo(this.code,i):i.then(r=>Bo(this.code,r))}else throw Error("Unknown type, must be binary type")}}const cd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),p8=ad({name:"sha2-256",code:18,encode:cd("SHA-256")}),g8=ad({name:"sha2-512",code:19,encode:cd("SHA-512")});var y8=Object.freeze({__proto__:null,sha256:p8,sha512:g8});const ud=0,w8="identity",hd=id,m8=t=>Bo(ud,hd(t)),b8={code:ud,name:w8,encode:hd,digest:m8};var v8=Object.freeze({__proto__:null,identity:b8});new TextEncoder,new TextDecoder;const ju={...fx,...px,...yx,...mx,...Ex,...Cx,...Fx,...Nx,...jx,...Gx};({...y8,...v8});function ld(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function E8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?ld(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fd(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const zu=fd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Wn=fd("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=E8(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),_8={utf8:zu,"utf-8":zu,hex:ju.base16,latin1:Wn,ascii:Wn,binary:Wn,...ju};function x8(t,e="utf8"){const i=_8[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?ld(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}var I8=Object.defineProperty,S8=(t,e,i)=>e in t?I8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,_t=(t,e,i)=>S8(t,typeof e!="symbol"?e+"":e,i);class D8{constructor(e,i){this.core=e,this.logger=i,_t(this,"keychain",new Map),_t(this,"name",I_),_t(this,"version",S_),_t(this,"initialized",!1),_t(this,"storagePrefix",Ct),_t(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),_t(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),_t(this,"set",async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()}),_t(this,"get",r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:n}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(n)}return s}),_t(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=je(i,this.name)}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,vo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eo(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 A8=Object.defineProperty,$8=(t,e,i)=>e in t?A8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ae=(t,e,i)=>$8(t,typeof e!="symbol"?e+"":e,i);class O8{constructor(e,i,r){this.core=e,this.logger=i,Ae(this,"name",__),Ae(this,"keychain"),Ae(this,"randomSessionIdentifier",Co()),Ae(this,"initialized",!1),Ae(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ae(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),Ae(this,"getClientId",async()=>{this.isInitialized();const s=await this.getClientSeed(),n=xc(s);return tl(n.publicKey)}),Ae(this,"generateKeyPair",()=>{this.isInitialized();const s=ME();return this.setPrivateKey(s.publicKey,s.privateKey)}),Ae(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=xc(n),a=this.randomSessionIdentifier;return await A1(a,s,x_,o)}),Ae(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=qE(a,n);return this.setSymKey(c,o)}),Ae(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||Ts(s);return await this.keychain.set(o,s),o}),Ae(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ae(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),Ae(this,"encode",async(s,n,o)=>{this.isInitialized();const a=qf(o),c=Si(n);if(mu(a))return KE(c,o?.encoding);if(wu(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const u=this.getSymKey(s),{type:h,senderPublicKey:l}=a;return jE({type:h,symKey:u,message:c,senderPublicKey:l,encoding:o?.encoding})}),Ae(this,"decode",async(s,n,o)=>{this.isInitialized();const a=HE(n,o);if(mu(a)){const c=VE(n,o?.encoding);return Yi(c)}if(wu(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;s=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(s),u=zE({symKey:c,encoded:n,encoding:o?.encoding});return Yi(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ae(this,"getPayloadType",(s,n=Ye)=>{const o=Vr({encoded:s,encoding:n});return Oi(o.type)}),Ae(this,"getPayloadSenderPublicKey",(s,n=Ye)=>{const o=Vr({encoded:s,encoding:n});return o.senderPublicKey?Ze(o.senderPublicKey,qe):void 0}),this.core=e,this.logger=je(i,this.name),this.keychain=r||new D8(this.core,this.logger)}get context(){return Qe(this.logger)}async setPrivateKey(e,i){return await this.keychain.set(e,i),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Uu)}catch{e=Co(),await this.keychain.set(Uu,e)}return x8(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 T8=Object.defineProperty,C8=Object.defineProperties,P8=Object.getOwnPropertyDescriptors,Ku=Object.getOwnPropertySymbols,R8=Object.prototype.hasOwnProperty,F8=Object.prototype.propertyIsEnumerable,Uo=(t,e,i)=>e in t?T8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,B8=(t,e)=>{for(var i in e||(e={}))R8.call(e,i)&&Uo(t,i,e[i]);if(Ku)for(var i of Ku(e))F8.call(e,i)&&Uo(t,i,e[i]);return t},U8=(t,e)=>C8(t,P8(e)),Xe=(t,e,i)=>Uo(t,typeof e!="symbol"?e+"":e,i);class N8 extends Ig{constructor(e,i){super(e,i),this.logger=e,this.core=i,Xe(this,"messages",new Map),Xe(this,"messagesWithoutClientAck",new Map),Xe(this,"name",D_),Xe(this,"version",A_),Xe(this,"initialized",!1),Xe(this,"storagePrefix",Ct),Xe(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),Xe(this,"set",async(r,s,n)=>{this.isInitialized();const o=at(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),n===Cs.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,U8(B8({},c),{[o]:s}))}return await this.persist(),o}),Xe(this,"get",r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s}),Xe(this,"getWithoutAck",r=>{this.isInitialized();const s={};for(const n of r){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Xe(this,"has",(r,s)=>{this.isInitialized();const n=this.get(r),o=at(s);return typeof n[o]<"u"}),Xe(this,"ack",async(r,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(r);if(typeof n>"u")return;const o=at(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,n),await this.persist()}),Xe(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=je(e,this.name),this.core=i}get context(){return Qe(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,vo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,vo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Eo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Eo(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 k8=Object.defineProperty,L8=Object.defineProperties,M8=Object.getOwnPropertyDescriptors,Vu=Object.getOwnPropertySymbols,q8=Object.prototype.hasOwnProperty,j8=Object.prototype.propertyIsEnumerable,No=(t,e,i)=>e in t?k8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,zi=(t,e)=>{for(var i in e||(e={}))q8.call(e,i)&&No(t,i,e[i]);if(Vu)for(var i of Vu(e))j8.call(e,i)&&No(t,i,e[i]);return t},Hu=(t,e)=>L8(t,M8(e)),nt=(t,e,i)=>No(t,typeof e!="symbol"?e+"":e,i);class z8 extends Sg{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,nt(this,"events",new rt.EventEmitter),nt(this,"name",O_),nt(this,"queue",new Map),nt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),nt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),nt(this,"needsTransportRestart",!1),nt(this,"publish",async(r,s,n)=>{var o,a,c,u,h;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:n}});const l=n?.ttl||$_,f=n?.prompt||!1,p=n?.tag||0,d=n?.id||ci().toString(),g=Wi(Vs().protocol),y={id:d,method:n?.publishMethod||g.publish,params:zi({topic:r,message:s,ttl:l,prompt:f,tag:p,attestation:n?.attestation},n?.tvf&&{tvf:n.tvf})},E=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{ve((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),ve((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const v=new Promise(async m=>{const D=({id:R})=>{var U;((U=y.id)==null?void 0:U.toString())===R.toString()&&(this.removeRequestFromQueue(R),this.relayer.events.removeListener(de.publish,D),m())};this.relayer.events.on(de.publish,D);const I=Ot(new Promise((R,U)=>{this.rpcPublish(y,n).then(R).catch(C=>{this.logger.warn(C,C?.message),U(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await I,this.events.removeListener(de.publish,D)}catch(R){this.queue.set(d,{request:y,opts:n,attempt:1}),this.logger.warn(R,R?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:s,opts:n}}),await Ot(v,this.publishTimeout,E)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),(h=n?.internal)!=null&&h.throwOnFailedPublish)throw v}finally{this.queue.delete(d)}}),nt(this,"publishCustom",async r=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:h={}}=r,{attestation:l,tvf:f,publishMethod:p,prompt:d,tag:g,ttl:y=L.FIVE_MINUTES}=h,E=h.id||ci().toString(),v=Wi(Vs().protocol),m=p||v.publish,D={id:E,method:m,params:zi(Hu(zi({},u),{ttl:y,prompt:d,tag:g,attestation:l}),f)},I=`Failed to publish custom payload, please try again. id:${E} tag:${g}`;try{ve((s=D.params)==null?void 0:s.prompt)&&((n=D.params)==null||delete n.prompt),ve((o=D.params)==null?void 0:o.tag)&&((a=D.params)==null||delete a.tag);const R=new Promise(async U=>{const C=({id:O})=>{var _;((_=D.id)==null?void 0:_.toString())===O.toString()&&(this.removeRequestFromQueue(O),this.relayer.events.removeListener(de.publish,C),U())};this.relayer.events.on(de.publish,C);const w=Ot(new Promise((O,_)=>{this.rpcPublish(D,h).then(O).catch($=>{this.logger.warn($,$?.message),_($)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${m} id:${E} tag:${g}`);try{await w,this.events.removeListener(de.publish,C)}catch(O){this.queue.set(E,{request:D,opts:h,attempt:1}),this.logger.warn(O,O?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:E,payload:u,opts:h}}),await Ot(R,this.publishTimeout,I)}catch(R){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(R),(c=h?.internal)!=null&&c.throwOnFailedPublish)throw R}finally{this.queue.delete(E)}}),nt(this,"on",(r,s)=>{this.events.on(r,s)}),nt(this,"once",(r,s)=>{this.events.once(r,s)}),nt(this,"off",(r,s)=>{this.events.off(r,s)}),nt(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.relayer=e,this.logger=je(i,this.name),this.registerEventListeners()}get context(){return Qe(this.logger)}async rpcPublish(e,i){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(de.publish,zi(zi({},e),i)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,i)=>{var r;const s=e.attempt+1;this.queue.set(i,Hu(zi({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Ci.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(de.connection_stalled);return}this.checkQueue()}),this.relayer.on(de.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var K8=Object.defineProperty,V8=(t,e,i)=>e in t?K8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ki=(t,e,i)=>V8(t,typeof e!="symbol"?e+"":e,i);class H8{constructor(){Ki(this,"map",new Map),Ki(this,"set",(e,i)=>{const r=this.get(e);this.exists(e,i)||this.map.set(e,[...r,i])}),Ki(this,"get",e=>this.map.get(e)||[]),Ki(this,"exists",(e,i)=>this.get(e).includes(i)),Ki(this,"delete",(e,i)=>{if(typeof i>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,i))return;const s=r.filter(n=>n!==i);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),Ki(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var W8=Object.defineProperty,G8=Object.defineProperties,Y8=Object.getOwnPropertyDescriptors,Wu=Object.getOwnPropertySymbols,J8=Object.prototype.hasOwnProperty,Z8=Object.prototype.propertyIsEnumerable,ko=(t,e,i)=>e in t?W8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,_r=(t,e)=>{for(var i in e||(e={}))J8.call(e,i)&&ko(t,i,e[i]);if(Wu)for(var i of Wu(e))Z8.call(e,i)&&ko(t,i,e[i]);return t},Gn=(t,e)=>G8(t,Y8(e)),ae=(t,e,i)=>ko(t,typeof e!="symbol"?e+"":e,i);class Q8 extends $g{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,ae(this,"subscriptions",new Map),ae(this,"topicMap",new H8),ae(this,"events",new rt.EventEmitter),ae(this,"name",U_),ae(this,"version",N_),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",Ct),ae(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(r,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const o=Vs(s),a={topic:r,relay:o,transportType:s?.transportType};(n=s?.internal)!=null&&n.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ae(this,"unsubscribe",async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)}),ae(this,"isSubscribed",r=>new Promise(s=>{s(this.topicMap.topics.includes(r))})),ae(this,"isKnownTopic",r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(n=>n.topic===r))})),ae(this,"on",(r,s)=>{this.events.on(r,s)}),ae(this,"once",(r,s)=>{this.events.once(r,s)}),ae(this,"off",(r,s)=>{this.events.off(r,s)}),ae(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Ci.pulse,async()=>{await this.checkPending()}),this.events.on(et.created,async r=>{const s=et.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(et.deleted,async r=>{const s=et.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})}),this.relayer=e,this.logger=je(i,this.name),this.clientId=""}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,i){let r=!1;try{r=this.getSubscription(e).topic===i}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,i){const r=this.topicMap.get(e);await Promise.all(r.map(async s=>await this.unsubscribeById(e,s,i)))}async unsubscribeById(e,i,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}});try{const s=Vs(r);await this.restartToComplete({topic:e,id:i,relay:s}),await this.rpcUnsubscribe(e,i,s);const n=le("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,i,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,i,r){var s,n;const o=await this.getSubscriptionId(e);if((s=r?.internal)!=null&&s.skipSubscribe)return o;(!r||r?.transportType===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:i});const a={method:Wi(i.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=r?.internal)==null?void 0:n.throwOnFailedPublish;try{if(r?.transportType===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(l=>this.logger.warn(l))},L.toMiliseconds(L.ONE_SECOND)),o;const u=new Promise(async l=>{const f=p=>{p.topic===e&&(this.events.removeListener(et.created,f),l(p.id))};this.events.on(et.created,f);try{const p=await Ot(new Promise((d,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(et.created,f),l(p)}catch{}}),h=await Ot(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!h&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return h?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(de.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const i=e[0].relay,r={method:Wi(i.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Ot(new Promise(s=>{this.relayer.request(r).catch(n=>this.logger.warn(n)).then(s)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const i=e[0].relay,r={method:Wi(i.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await Ot(new Promise((n,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(de.connection_stalled)}return s}rpcUnsubscribe(e,i,r){const s={method:Wi(r.protocol).unsubscribe,params:{topic:e,id:i}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,i){this.setSubscription(e,Gn(_r({},i),{id:e})),this.pending.delete(i.topic)}onBatchSubscribe(e){e.length&&e.forEach(i=>{this.setSubscription(i.id,_r({},i)),this.pending.delete(i.topic)})}async onUnsubscribe(e,i,r){this.events.removeAllListeners(i),this.hasSubscription(i,e)&&this.deleteSubscription(i,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,i){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:i}),this.addSubscription(e,i)}addSubscription(e,i){this.subscriptions.set(e,_r({},i)),this.topicMap.set(i.topic,e),this.events.emit(et.created,i)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const i=this.subscriptions.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}deleteSubscription(e,i){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:i});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(et.deleted,Gn(_r({},r),{reason:i}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(et.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],i=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<i;r++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(et.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(i=>{var r;return i.topic===((r=this.subscriptions.get(i.id))==null?void 0:r.topic)})){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async i=>Gn(_r({},i),{id:await this.getSubscriptionId(i.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await av(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return at(e+await this.getClientId())}}var X8=Object.defineProperty,Gu=Object.getOwnPropertySymbols,eI=Object.prototype.hasOwnProperty,tI=Object.prototype.propertyIsEnumerable,Lo=(t,e,i)=>e in t?X8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Yu=(t,e)=>{for(var i in e||(e={}))eI.call(e,i)&&Lo(t,i,e[i]);if(Gu)for(var i of Gu(e))tI.call(e,i)&&Lo(t,i,e[i]);return t},ee=(t,e,i)=>Lo(t,typeof e!="symbol"?e+"":e,i);class iI extends Dg{constructor(e){super(e),ee(this,"protocol","wc"),ee(this,"version",2),ee(this,"core"),ee(this,"logger"),ee(this,"events",new rt.EventEmitter),ee(this,"provider"),ee(this,"messages"),ee(this,"subscriber"),ee(this,"publisher"),ee(this,"name",C_),ee(this,"transportExplicitlyClosed",!1),ee(this,"initialized",!1),ee(this,"connectionAttemptInProgress",!1),ee(this,"relayUrl"),ee(this,"projectId"),ee(this,"packageName"),ee(this,"bundleId"),ee(this,"hasExperiencedNetworkDisruption",!1),ee(this,"pingTimeout"),ee(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ee(this,"reconnectTimeout"),ee(this,"connectPromise"),ee(this,"reconnectInProgress",!1),ee(this,"requestsInFlight",[]),ee(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ee(this,"request",async i=>{var r,s;this.logger.debug("Publishing Request Payload");const n=i.id||ci().toString();await this.toEstablishConnection();try{this.logger.trace({id:n,method:i.method,topic:(r=i.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${n}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${n}`),o}}),ee(this,"resetPingTimeout",()=>{qs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,r,s,n;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(n=(s=(r=(i=this.provider)==null?void 0:i.connection)==null?void 0:r.socket)==null?void 0:s.terminate)==null||n.call(s)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ee(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),ee(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(de.connect)}),ee(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ee(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(de.error,i),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ee(this,"registerProviderListeners",()=>{this.provider.on(st.payload,this.onPayloadHandler),this.provider.on(st.connect,this.onConnectHandler),this.provider.on(st.disconnect,this.onDisconnectHandler),this.provider.on(st.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je(e.logger,this.name):Zs(Ho({level:e.logger||T_})),this.messages=new N8(this.logger,e.core),this.subscriber=new Q8(this,this.logger),this.publisher=new z8(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ed,Vb()?this.packageName=Lc():Hb()&&(this.bundleId=Lc()),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?.message))}get context(){return Qe(this.logger)}get connected(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,i,r){this.isInitialized(),await this.publisher.publish(e,i,r),await this.recordMessageEvent({topic:e,message:i,publishedAt:Date.now(),transportType:he.relay},Cs.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,i){var r,s,n;this.isInitialized(),(!(i!=null&&i.transportType)||i?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=i?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(s=i?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const u=h=>{h.topic===e&&(this.subscriber.off(et.created,u),c())};return await Promise.all([new Promise(h=>{c=h,this.subscriber.on(et.created,u)}),new Promise(async(h,l)=>{a=await this.subscriber.subscribe(e,Yu({internal:{throwOnFailedPublish:o}},i)).catch(f=>{o&&l(f)})||a,h()})]),a}async unsubscribe(e,i){this.isInitialized(),await this.subscriber.unsubscribe(e,i)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Ot(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(i,r)=>{await this.connect(e).then(i).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Ou())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const i=e.sort((r,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${i.length} message events sorted`);for(const r of i)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${i.length} message events processed`)}async onLinkMessageEvent(e,i){const{topic:r}=e;if(!i.sessionExists){const s=me(L.FIVE_MINUTES),n={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,n)}this.events.emit(de.message,e),await this.recordMessageEvent(e,Cs.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let i=1;for(;i<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${i}...`),await this.createProvider(),await new Promise(async(r,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(st.disconnect,n),await Ot(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(st.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(st.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(st.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${i}`);break}await new Promise(r=>setTimeout(r,L.toMiliseconds(i*1))),i++}}startPingTimeout(){var e,i,r,s,n;if(qs())try{(i=(e=this.provider)==null?void 0:e.connection)!=null&&i.socket&&((n=(s=(r=this.provider)==null?void 0:r.connection)==null?void 0:s.socket)==null||n.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Jf(new b_(Zb({sdkVersion:Ro,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,i){const{topic:r,message:s}=e;await this.messages.set(r,s,i)}async shouldIgnoreMessageEvent(e){const{topic:i,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(i))return this.logger.warn(`Ignoring message for unknown topic ${i}`),!0;const s=this.messages.has(i,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Aa(e)){if(!e.method.endsWith(P_))return;const i=e.params,{topic:r,message:s,publishedAt:n,attestation:o}=i.data,a={topic:r,message:s,publishedAt:n,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yu({type:"event",event:i.id},a)),this.events.emit(i.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ln(e)&&this.events.emit(de.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Cs.inbound),this.events.emit(de.message,e))}async acknowledgePayload(e){const i=Wr(e.id,!0);await this.provider.connection.send(i)}unregisterProviderListeners(){this.provider.off(st.payload,this.onPayloadHandler),this.provider.off(st.connect,this.onConnectHandler),this.provider.off(st.disconnect,this.onDisconnectHandler),this.provider.off(st.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Ou();M3(async i=>{e!==i&&(e=i,i?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Ci.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&z3())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(i){this.logger.warn(i,i?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(de.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},L.toMiliseconds(R_)))))}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 rI(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ju(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Zu(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const sI="[object RegExp]",nI="[object String]",oI="[object Number]",aI="[object Boolean]",Qu="[object Arguments]",cI="[object Symbol]",uI="[object Date]",hI="[object Map]",lI="[object Set]",fI="[object Array]",dI="[object Function]",pI="[object ArrayBuffer]",Yn="[object Object]",gI="[object Error]",yI="[object DataView]",wI="[object Uint8Array]",mI="[object Uint8ClampedArray]",bI="[object Uint16Array]",vI="[object Uint32Array]",EI="[object BigUint64Array]",_I="[object Int8Array]",xI="[object Int16Array]",II="[object Int32Array]",SI="[object BigInt64Array]",DI="[object Float32Array]",AI="[object Float64Array]";function $I(){}function Xu(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 OI(t,e,i){return Ar(t,e,void 0,void 0,void 0,void 0,i)}function Ar(t,e,i,r,s,n,o){const a=o(t,e,i,r,s,n);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 Ur(t,e,n,o)}return Ur(t,e,n,o)}function Ur(t,e,i,r){if(Object.is(t,e))return!0;let s=Zu(t),n=Zu(e);if(s===Qu&&(s=Yn),n===Qu&&(n=Yn),s!==n)return!1;switch(s){case nI:return t.toString()===e.toString();case oI:{const c=t.valueOf(),u=e.valueOf();return rI(c,u)}case aI:case uI:case cI:return Object.is(t.valueOf(),e.valueOf());case sI:return t.source===e.source&&t.flags===e.flags;case dI:return t===e}i=i??new Map;const o=i.get(t),a=i.get(e);if(o!=null&&a!=null)return o===e;i.set(t,e),i.set(e,t);try{switch(s){case hI:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Ar(u,e.get(c),c,t,e,i,r))return!1;return!0}case lI:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let h=0;h<c.length;h++){const l=c[h],f=u.findIndex(p=>Ar(l,p,void 0,t,e,i,r));if(f===-1)return!1;u.splice(f,1)}return!0}case fI:case wI:case mI:case bI:case vI:case EI:case _I:case xI:case II:case SI:case DI:case AI:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Ar(t[c],e[c],c,t,e,i,r))return!1;return!0}case pI:return t.byteLength!==e.byteLength?!1:Ur(new Uint8Array(t),new Uint8Array(e),i,r);case yI:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ur(new Uint8Array(t),new Uint8Array(e),i,r);case gI:return t.name===e.name&&t.message===e.message;case Yn:{if(!(Ur(t.constructor,e.constructor,i,r)||Xu(t)&&Xu(e)))return!1;const c=[...Object.keys(t),...Ju(t)],u=[...Object.keys(e),...Ju(e)];if(c.length!==u.length)return!1;for(let h=0;h<c.length;h++){const l=c[h],f=t[l];if(!Object.hasOwn(e,l))return!1;const p=e[l];if(!Ar(f,p,l,t,e,i,r))return!1}return!0}default:return!1}}finally{i.delete(t),i.delete(e)}}function TI(t,e){return OI(t,e,$I)}var CI=Object.defineProperty,eh=Object.getOwnPropertySymbols,PI=Object.prototype.hasOwnProperty,RI=Object.prototype.propertyIsEnumerable,Mo=(t,e,i)=>e in t?CI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,th=(t,e)=>{for(var i in e||(e={}))PI.call(e,i)&&Mo(t,i,e[i]);if(eh)for(var i of eh(e))RI.call(e,i)&&Mo(t,i,e[i]);return t},Ke=(t,e,i)=>Mo(t,typeof e!="symbol"?e+"":e,i);class Fi extends Ag{constructor(e,i,r,s=Ct,n=void 0){super(e,i,r,s),this.core=e,this.logger=i,this.name=r,Ke(this,"map",new Map),Ke(this,"version",F_),Ke(this,"cached",[]),Ke(this,"initialized",!1),Ke(this,"getKey"),Ke(this,"storagePrefix",Ct),Ke(this,"recentlyDeleted",[]),Ke(this,"recentlyDeletedLimit",200),Ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!ve(o)?this.map.set(this.getKey(o),o):w3(o)?this.map.set(o.id,o):m3(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ke(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())}),Ke(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ke(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>TI(a[c],o[c]))):this.values)),Ke(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=th(th({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ke(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=je(i,this.name),this.storagePrefix=s,this.getKey=n}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const i=this.map.get(e);if(!i){if(this.recentlyDeleted.includes(e)){const{message:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return i}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var FI=Object.defineProperty,BI=(t,e,i)=>e in t?FI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Z=(t,e,i)=>BI(t,typeof e!="symbol"?e+"":e,i);class UI{constructor(e,i){this.core=e,this.logger=i,Z(this,"name",k_),Z(this,"version",L_),Z(this,"events",new bh),Z(this,"pairings"),Z(this,"initialized",!1),Z(this,"storagePrefix",Ct),Z(this,"ignoredPayloadTypes",[zt]),Z(this,"registeredMethods",[]),Z(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Z(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),Z(this,"create",async r=>{this.isInitialized();const s=Co(),n=await this.core.crypto.setSymKey(s),o=me(L.FIVE_MINUTES),a={protocol:Xf},c={topic:n,expiry:o,relay:a,active:!1,methods:r?.methods},u=vu({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(bi.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:r?.transportType,internal:r?.internal}),{topic:n,uri:u}}),Z(this,"pair",async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[It.pairing_started]}});this.isValidPair(r,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:u}=bu(r.uri);s.props.properties.topic=n,s.addTrace(It.pairing_uri_validation_success),s.addTrace(It.pairing_uri_not_expired);let h;if(this.pairings.keys.includes(n)){if(h=this.pairings.get(n),s.addTrace(It.existing_pairing),h.active)throw s.setError(Lt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(It.pairing_not_expired)}const l=c||me(L.FIVE_MINUTES),f={topic:n,relay:a,expiry:l,active:!1,methods:u};this.core.expirer.set(n,l),await this.pairings.set(n,f),s.addTrace(It.store_new_pairing),r.activatePairing&&await this.activate({topic:n}),this.events.emit(bi.create,f),s.addTrace(It.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(It.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Lt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw s.setError(Lt.subscribe_pairing_topic_failure),p}return s.addTrace(It.subscribe_pairing_topic_success),f}),Z(this,"activate",async({topic:r})=>{this.isInitialized();const s=me(L.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})}),Z(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=wi();this.events.once(se("pairing_ping",n),({error:u})=>{u?c(u):a()}),await o()}}),Z(this,"updateExpiry",async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})}),Z(this,"updateMetadata",async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})}),Z(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Z(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",le("USER_DISCONNECTED")),await this.deletePairing(s))}),Z(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return vu({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),Z(this,"sendRequest",async(r,s,n)=>{const o=jt(s,n),a=await this.core.crypto.encode(r,o),c=br[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),Z(this,"sendResult",async(r,s,n)=>{const o=Wr(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,u=br[c].res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),Z(this,"sendError",async(r,s,n)=>{const o=hn(r,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,u=br[c]?br[c].res:br.unregistered_method.res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),Z(this,"deletePairing",async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,le("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])}),Z(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(s=>ri(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))}),Z(this,"onRelayEventRequest",async r=>{const{topic:s,payload:n}=r;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),Z(this,"onRelayEventResponse",async r=>{const{topic:s,payload:n}=r,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),Z(this,"onPairingPingRequest",async(r,s)=>{const{id:n}=s;try{this.isValidPing({topic:r}),await this.sendResult(n,r,!0),this.events.emit(bi.ping,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),Z(this,"onPairingPingResponse",(r,s)=>{const{id:n}=s;setTimeout(()=>{Dt(s)?this.events.emit(se("pairing_ping",n),{}):ct(s)&&this.events.emit(se("pairing_ping",n),{error:s.error})},500)}),Z(this,"onPairingDeleteRequest",async(r,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(bi.delete,{id:n,topic:r})}catch(o){await this.sendError(n,r,o),this.logger.error(o)}}),Z(this,"onUnknownRpcMethodRequest",async(r,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=le("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,r,a),this.logger.error(a)}catch(a){await this.sendError(n,r,a),this.logger.error(a)}}),Z(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(le("WC_METHOD_UNSUPPORTED",r))}),Z(this,"isValidPair",(r,s)=>{var n;if(!He(r)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(Lt.malformed_pairing_uri),new Error(a)}if(!y3(r.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(Lt.malformed_pairing_uri),new Error(a)}const o=bu(r?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Lt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Lt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(Lt.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Z(this,"isValidPing",async r=>{if(!He(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Z(this,"isValidDisconnect",async r=>{if(!He(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:s}=r;await this.isValidPairingTopic(s)}),Z(this,"isValidPairingTopic",async r=>{if(!ye(r,!1)){const{message:s}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(ri(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}}),this.core=e,this.logger=je(i,this.name),this.pairings=new Fi(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Qe(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(de.message,async e=>{const{topic:i,message:r,transportType:s}=e;if(this.pairings.keys.includes(i)&&s!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const n=await this.core.crypto.decode(i,r);Aa(n)?(this.core.history.set(i,n),await this.onRelayEventRequest({topic:i,payload:n})):ln(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:i,payload:n}),this.core.history.delete(i,n.id)),await this.core.relayer.messages.ack(i,r)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(ot.expired,async e=>{const{topic:i}=Jl(e.target);i&&this.pairings.keys.includes(i)&&(await this.deletePairing(i,!0),this.events.emit(bi.expire,{topic:i}))})}}var NI=Object.defineProperty,kI=(t,e,i)=>e in t?NI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,$e=(t,e,i)=>kI(t,typeof e!="symbol"?e+"":e,i);class LI extends xg{constructor(e,i){super(e,i),this.core=e,this.logger=i,$e(this,"records",new Map),$e(this,"events",new rt.EventEmitter),$e(this,"name",M_),$e(this,"version",q_),$e(this,"cached",[]),$e(this,"initialized",!1),$e(this,"storagePrefix",Ct),$e(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),$e(this,"set",(r,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:n,expiry:me(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(pt.created,o)}),$e(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response>"u"&&(s.response=ct(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(pt.updated,s))}),$e(this,"get",async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s))),$e(this,"delete",(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===r){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(pt.deleted,n)}}),this.persist()}),$e(this,"exists",async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1)),$e(this,"on",(r,s)=>{this.events.on(r,s)}),$e(this,"once",(r,s)=>{this.events.once(r,s)}),$e(this,"off",(r,s)=>{this.events.off(r,s)}),$e(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=je(i,this.name)}get context(){return Qe(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(i=>{if(typeof i.response<"u")return;const r={topic:i.topic,request:jt(i.request.method,i.request.params,i.id),chainId:i.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const i=this.records.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(pt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(pt.created,e=>{const i=pt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(pt.updated,e=>{const i=pt.updated;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(pt.deleted,e=>{const i=pt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.core.heartbeat.on(Ci.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(i=>{L.toMiliseconds(i.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${i.id}`),this.records.delete(i.id),this.events.emit(pt.deleted,i,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MI=Object.defineProperty,qI=(t,e,i)=>e in t?MI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ke=(t,e,i)=>qI(t,typeof e!="symbol"?e+"":e,i);class jI extends Og{constructor(e,i){super(e,i),this.core=e,this.logger=i,ke(this,"expirations",new Map),ke(this,"events",new rt.EventEmitter),ke(this,"name",j_),ke(this,"version",z_),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"storagePrefix",Ct),ke(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ke(this,"has",r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}}),ke(this,"set",(r,s)=>{this.isInitialized();const n=this.formatTarget(r),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(ot.created,{target:n,expiration:o})}),ke(this,"get",r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)}),ke(this,"del",r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(ot.deleted,{target:s,expiration:n})}}),ke(this,"on",(r,s)=>{this.events.on(r,s)}),ke(this,"once",(r,s)=>{this.events.once(r,s)}),ke(this,"off",(r,s)=>{this.events.off(r,s)}),ke(this,"removeListener",(r,s)=>{this.events.removeListener(r,s)}),this.logger=je(i,this.name)}get context(){return Qe(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 Qb(e);if(typeof e=="number")return Xb(e);const{message:i}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(i)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(ot.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const i=this.expirations.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return i}checkExpiry(e,i){const{expiry:r}=i;L.toMiliseconds(r)-Date.now()<=0&&this.expire(e,i)}expire(e,i){this.expirations.delete(e),this.events.emit(ot.expired,{target:e,expiration:i})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,i)=>this.checkExpiry(i,e))}registerEventListeners(){this.core.heartbeat.on(Ci.pulse,()=>this.checkExpirations()),this.events.on(ot.created,e=>{const i=ot.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(ot.expired,e=>{const i=ot.expired;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(ot.deleted,e=>{const i=ot.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zI=Object.defineProperty,KI=(t,e,i)=>e in t?zI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ge=(t,e,i)=>KI(t,typeof e!="symbol"?e+"":e,i);class VI extends Tg{constructor(e,i,r){super(e,i,r),this.core=e,this.logger=i,this.store=r,ge(this,"name",K_),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",H_),ge(this,"storagePrefix",Ct),ge(this,"version",Qf),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async s=>{if(!sr()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const u=Di(),h=this.startAbortTimer(L.ONE_SECOND*5),l=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",y),u.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",d,{signal:this.abortController.signal});const y=E=>{if(E.data&&typeof E.data=="string")try{const v=JSON.parse(E.data);if(v.type==="verify_attestation"){if(ho(v.attestation).payload.id!==o)return;clearInterval(h),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",y),f(v.attestation===null?"":v.attestation)}}catch(v){this.logger.warn(v)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",l),l}catch(u){this.logger.warn(u)}return""}),ge(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(ho(n).payload.id!==a)return;const u=await this.isValidJwtAttestation(n);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)}),ge(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ge(this,"getVerifyUrl",s=>{let n=s||Br;return W_.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Br}`),n=Br),n}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(L.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),ge(this,"persistPublicKey",async s=>{this.logger.debug("persisting public key to local storage",s),await this.store.setItem(this.storeKey,s),this.publicKey=s}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),ge(this,"validateAttestation",(s,n)=>{const o=GE(s,n.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=je(i,this.name),this.abortController=new AbortController,this.isDevEnv=fa(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Qe(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var HI=Object.defineProperty,WI=(t,e,i)=>e in t?HI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ih=(t,e,i)=>WI(t,typeof e!="symbol"?e+"":e,i);class GI extends Cg{constructor(e,i){super(e,i),this.projectId=e,this.logger=i,ih(this,"context",G_),ih(this,"registerDeviceToken",async r=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=r,c=`${Y_}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=je(i,this.context)}}var YI=Object.defineProperty,rh=Object.getOwnPropertySymbols,JI=Object.prototype.hasOwnProperty,ZI=Object.prototype.propertyIsEnumerable,qo=(t,e,i)=>e in t?YI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xr=(t,e)=>{for(var i in e||(e={}))JI.call(e,i)&&qo(t,i,e[i]);if(rh)for(var i of rh(e))ZI.call(e,i)&&qo(t,i,e[i]);return t},Ee=(t,e,i)=>qo(t,typeof e!="symbol"?e+"":e,i);class QI extends Pg{constructor(e,i,r=!0){super(e,i,r),this.core=e,this.logger=i,Ee(this,"context",Z_),Ee(this,"storagePrefix",Ct),Ee(this,"storageVersion",J_),Ee(this,"events",new Map),Ee(this,"shouldPersist",!1),Ee(this,"init",async()=>{if(!fa())try{const s={eventId:qc(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Gl(this.core.relayer.protocol,this.core.relayer.version,Ro)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),Ee(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,u=qc(),h=this.core.projectId||"",l=Date.now(),f=xr({eventId:u,timestamp:l,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:h,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),Ee(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return xr(xr({},a),this.setMethods(a.eventId))}),Ee(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),Ee(this,"setEventListeners",()=>{this.core.heartbeat.on(Ci.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(s.timestamp)>Q_&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),Ee(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),Ee(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ee(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,xr(xr({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),Ee(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Ee(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${X_}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ro}${n}`,{method:"POST",body:JSON.stringify(s)})}),Ee(this,"getAppDomain",()=>Wl().url),this.logger=je(i,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var XI=Object.defineProperty,sh=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,jo=(t,e,i)=>e in t?XI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nh=(t,e)=>{for(var i in e||(e={}))eS.call(e,i)&&jo(t,i,e[i]);if(sh)for(var i of sh(e))tS.call(e,i)&&jo(t,i,e[i]);return t},ce=(t,e,i)=>jo(t,typeof e!="symbol"?e+"":e,i);class $a extends bg{constructor(e){var i;super(e),ce(this,"protocol",Zf),ce(this,"version",Qf),ce(this,"name",Ws),ce(this,"relayUrl"),ce(this,"projectId"),ce(this,"customStoragePrefix"),ce(this,"events",new rt.EventEmitter),ce(this,"logger"),ce(this,"heartbeat"),ce(this,"relayer"),ce(this,"crypto"),ce(this,"storage"),ce(this,"history"),ce(this,"expirer"),ce(this,"pairing"),ce(this,"verify"),ce(this,"echoClient"),ce(this,"linkModeSupportedApps"),ce(this,"eventClient"),ce(this,"initialized",!1),ce(this,"logChunkController"),ce(this,"on",(a,c)=>this.events.on(a,c)),ce(this,"once",(a,c)=>this.events.once(a,c)),ce(this,"off",(a,c)=>this.events.off(a,c)),ce(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ce(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const h={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(h,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ed,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Ho({level:typeof e?.logger=="string"&&e.logger?e.logger:v_.logger,name:Ws}),{logger:n,chunkLoggerController:o}=yg({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(i=this.logChunkController)!=null&&i.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=je(n,this.name),this.heartbeat=new op,this.crypto=new O8(this,this.logger,e?.keychain),this.history=new LI(this,this.logger),this.expirer=new jI(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new jp(nh(nh({},E_),e?.storageOptions)),this.relayer=new iI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new UI(this,this.logger),this.verify=new VI(this,this.logger,this.storage),this.echoClient=new GI(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new QI(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new $a(e);await i.initialize();const r=await i.crypto.getClientId();return await i.storage.setItem(B_,r),i}get context(){return Qe(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(Nu,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(Nu)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${e}`,r=`${i}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[i]}catch(i){console.warn("Failed to get global WalletConnect core",i);return}}setGlobalCore(e){var i;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((i=e.opts)==null?void 0:i.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const iS=$a,dd="wc",pd=2,gd="client",Oa=`${dd}@${pd}:${gd}:`,Jn={name:gd,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},oh="WALLETCONNECT_DEEPLINK_CHOICE",rS="proposal",ah="Proposal expired",sS="session",Vi=L.SEVEN_DAYS,nS="engine",Oe={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}}},Zn={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},xt={idle:"IDLE",active:"ACTIVE"},oS={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:""}},aS="request",cS=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],uS="wc",hS="auth",lS="authKeys",fS="pairingTopics",dS="requests",dn=`${uS}@${1.5}:${hS}:`,Ps=`${dn}:PUB_KEY`;var pS=Object.defineProperty,gS=Object.defineProperties,yS=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,wS=Object.prototype.hasOwnProperty,mS=Object.prototype.propertyIsEnumerable,zo=(t,e,i)=>e in t?pS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ne=(t,e)=>{for(var i in e||(e={}))wS.call(e,i)&&zo(t,i,e[i]);if(ch)for(var i of ch(e))mS.call(e,i)&&zo(t,i,e[i]);return t},Le=(t,e)=>gS(t,yS(e)),F=(t,e,i)=>zo(t,typeof e!="symbol"?e+"":e,i);class bS extends Ug{constructor(e){super(e),F(this,"name",nS),F(this,"events",new bh),F(this,"initialized",!1),F(this,"requestQueue",{state:xt.idle,queue:[]}),F(this,"sessionRequestQueue",{state:xt.idle,queue:[]}),F(this,"emittedSessionRequests",new cv({limit:500})),F(this,"requestQueueDelay",L.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(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(Oe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Le(ne({},i),{requiredNamespaces:i.requiredNamespaces||{},optionalNamespaces:i.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=l3(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:n,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=r;let h=s,l,f=!1;try{if(h){const R=this.client.core.pairing.pairings.get(h);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=R.active}}catch(R){throw this.client.logger.error(`connect() -> pairing.get(${h}) failed`),R}if(!h||!f){const{topic:R,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});h=R,l=U}if(!h){const{message:R}=M("NO_MATCHING_KEY",`connect() pairing topic: ${h}`);throw new Error(R)}const p=await this.client.core.crypto.generateKeyPair(),d=Oe.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,g=me(d),y=Le(ne(ne({requiredNamespaces:n,optionalNamespaces:o,relays:u??[{protocol:Xf}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:h},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:St()}),E=se("session_connect",y.id),{reject:v,resolve:m,done:D}=wi(d,ah),I=({id:R})=>{R===y.id&&(this.client.events.off("proposal_expire",I),this.pendingSessions.delete(y.id),this.events.emit(E,{error:{message:ah,code:0}}))};return this.client.events.on("proposal_expire",I),this.events.once(E,({error:R,session:U})=>{this.client.events.off("proposal_expire",I),R?v(R):U&&m(U)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:l,approval:D}}),F(this,"pair",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(i)}catch(r){throw this.client.logger.error("pair() failed"),r}}),F(this,"approve",async i=>{var r,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=i?.id)==null?void 0:r.toString(),trace:[ii.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(w){throw o.setError(vr.no_internet_connection),w}try{await this.isValidProposalId(i?.id)}catch(w){throw this.client.logger.error(`approve() -> proposal.get(${i?.id}) failed`),o.setError(vr.proposal_not_found),w}try{await this.isValidApprove(i)}catch(w){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(vr.session_approve_namespace_validation_failure),w}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:h,scopedProperties:l,sessionConfig:f}=i,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:g,requiredNamespaces:y,optionalNamespaces:E}=p;let v=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:d});v||(v=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:ii.session_approve_started,properties:{topic:d,trace:[ii.session_approve_started,ii.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),D=g.publicKey,I=await this.client.core.crypto.generateSharedKey(m,D),R=ne(ne(ne({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:m,metadata:this.client.metadata},expiry:me(Vi)},h&&{sessionProperties:h}),l&&{scopedProperties:l}),f&&{sessionConfig:f}),U=he.relay;v.addTrace(ii.subscribing_session_topic);try{await this.client.core.relayer.subscribe(I,{transportType:U,internal:{skipSubscribe:!0}})}catch(w){throw v.setError(vr.subscribe_session_topic_failure),w}v.addTrace(ii.subscribe_session_topic_success);const C=Le(ne({},R),{topic:I,requiredNamespaces:y,optionalNamespaces:E,pairingTopic:d,acknowledged:!1,self:R.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:he.relay});await this.client.session.set(I,C),v.addTrace(ii.store_session);try{await this.sendApproveSession({sessionTopic:I,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:m},sessionSettleRequest:R,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),v.addTrace(ii.session_approve_publish_success)}catch(w){throw this.client.logger.error(w),this.client.session.delete(I,le("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(I),w}return this.client.core.eventClient.deleteEvent({eventId:v.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(I,me(Vi)),{topic:I,acknowledged:()=>Promise.resolve(this.client.session.get(I))}}),F(this,"reject",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(i)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:s}=i;let n;try{n=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}n&&await this.sendError({id:r,topic:n,error:s,rpcOpts:Oe.wc_sessionPropose.reject}),await this.deleteProposal(r)}),F(this,"update",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(i)}catch(l){throw this.client.logger.error("update() -> isValidUpdate() failed"),l}const{topic:r,namespaces:s}=i,{done:n,resolve:o,reject:a}=wi(),c=St(),u=ci().toString(),h=this.client.session.get(r).namespaces;return this.events.once(se("session_update",c),({error:l})=>{l?a(l):o()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(l=>{this.client.logger.error(l),this.client.session.update(r,{namespaces:h}),a(l)}),{acknowledged:n}}),F(this,"extend",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(i)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=i,s=St(),{done:n,resolve:o,reject:a}=wi();return this.events.once(se("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,me(Vi)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),F(this,"request",async i=>{this.isInitialized();try{await this.isValidRequest(i)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:s,topic:n,expiry:o=Oe.wc_sessionRequest.req.ttl}=i,a=this.client.session.get(n);a?.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const c=St(),u=ci().toString(),{done:h,resolve:l,reject:f}=wi(o,"Request expired. Please try again.");this.events.once(se("session_request",c),({error:y,result:E})=>{y?f(y):l(E)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:{request:Le(ne({},s),{expiryTimestamp:me(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(y=>f(y)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),await h();const g={request:Le(ne({},s),{expiryTimestamp:me(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(E=>f(E)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:r,id:c}),y()}),new Promise(async y=>{var E;if(!((E=a.sessionConfig)!=null&&E.disableDeepLink)){const v=await rv(this.client.core.storage,oh);await ev({id:c,topic:n,wcDeepLink:v})}y()}),h()]).then(y=>y[2])}),F(this,"respond",async i=>{this.isInitialized(),await this.isValidRespond(i);const{topic:r,response:s}=i,{id:n}=s,o=this.client.session.get(r);o.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Dt(s)?await this.sendResult({id:n,topic:r,result:s.result,throwOnFailedPublish:!0,appLink:a}):ct(s)&&await this.sendError({id:n,topic:r,error:s.error,appLink:a}),this.cleanupAfterResponse(i)}),F(this,"ping",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(i)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=i;if(this.client.session.keys.includes(r)){const s=St(),n=ci().toString(),{done:o,resolve:a,reject:c}=wi();this.events.once(se("session_ping",s),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),F(this,"emit",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(i);const{topic:r,event:s,chainId:n}=i,o=ci().toString(),a=St();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(i);const{topic:r}=i;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:le("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}}),F(this,"find",i=>(this.isInitialized(),this.client.session.getAll().filter(r=>p3(r,i)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(i,r)=>{var s;this.isInitialized(),this.isValidAuthenticate(i);const n=r&&this.client.core.linkModeSupportedApps.includes(r)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:h,nonce:l,type:f,exp:p,nbf:d,methods:g=[],expiry:y}=i,E=[...i.resources||[]],{topic:v,uri:m}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:m}});const D=await this.client.core.crypto.generateKeyPair(),I=Ts(D);if(await Promise.all([this.client.auth.authKeys.set(Ps,{responseTopic:I,publicKey:D}),this.client.auth.pairingTopics.set(I,{topic:I,pairingTopic:v})]),await this.client.core.relayer.subscribe(I,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${v}`),g.length>0){const{namespace:A}=$s(a[0]);let B=b2(A,"request",g);Os(E)&&(B=E2(B,E.pop())),E.push(B)}const R=y&&y>Oe.wc_sessionAuthenticate.req.ttl?y:Oe.wc_sessionAuthenticate.req.ttl,U={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:h,version:"1",nonce:l,iat:new Date().toISOString(),exp:p,nbf:d,resources:E},requester:{publicKey:D,metadata:this.client.metadata},expiryTimestamp:me(R)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},w={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:D,metadata:this.client.metadata},expiryTimestamp:me(Oe.wc_sessionPropose.req.ttl),id:St()},{done:O,resolve:_,reject:$}=wi(R,"Request expired"),P=St(),k=se("session_connect",w.id),x=se("session_request",P),b=async({error:A,session:B})=>{this.events.off(x,S),A?$(A):B&&_({session:B})},S=async A=>{var B,N,j;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),A.error){const J=le("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return A.error.code===J.code?void 0:(this.events.off(k,b),$(A.error.message))}await this.deleteProposal(w.id),this.events.off(k,b);const{cacaos:z,responder:K}=A.result,V=[],H=[];for(const J of z){await Qc({cacao:J,projectId:this.client.core.projectId})||(this.client.logger.error(J,"Signature verification failed"),$(le("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:fe}=J,Ie=Os(fe.resources),fi=[_o(fe.iss)],ns=js(fe.iss);if(Ie){const Bi=Xc(Ie),gn=eu(Ie);V.push(...Bi),fi.push(...gn)}for(const Bi of fi)H.push(`${Bi}:${ns}`)}const re=await this.client.core.crypto.generateSharedKey(D,K.publicKey);let ie;V.length>0&&(ie={topic:re,acknowledged:!0,self:{publicKey:D,metadata:this.client.metadata},peer:K,controller:K.publicKey,expiry:me(Vi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:Iu([...new Set(V)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(re,{transportType:o}),await this.client.session.set(re,ie),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:K.metadata}),ie=this.client.session.get(re)),(B=this.client.metadata.redirect)!=null&&B.linkMode&&(N=K.metadata.redirect)!=null&&N.linkMode&&(j=K.metadata.redirect)!=null&&j.universal&&r&&(this.client.core.addLinkModeSupportedApp(K.metadata.redirect.universal),this.client.session.update(re,{transportType:he.link_mode})),_({auths:z,session:ie})};this.events.once(k,b),this.events.once(x,S);let T;try{if(n){const A=jt("wc_sessionAuthenticate",U,P);this.client.core.history.set(v,A);const B=await this.client.core.crypto.encode("",A,{type:rs,encoding:ai});T=_s(r,v,B)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:U,expiry:i.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:w,expiry:Oe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:w.id})])}catch(A){throw this.events.off(k,b),this.events.off(x,S),A}return await this.setProposal(w.id,w),await this.setAuthRequest(P,{request:Le(ne({},U),{verifyContext:{}}),pairingTopic:v,transportType:o}),{uri:T??m,response:O}}),F(this,"approveSessionAuthenticate",async i=>{const{id:r,auths:s}=i,n=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[gi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw n.setError(Er.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw n.setError(Er.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=Ts(c),l={type:zt,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const y of s){if(!await Qc({cacao:y,projectId:this.client.core.projectId})){n.setError(Er.invalid_cacao);const I=le("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:h,error:I,encodeOpts:l}),new Error(I.message)}n.addTrace(gi.cacaos_verified);const{p:E}=y,v=Os(E.resources),m=[_o(E.iss)],D=js(E.iss);if(v){const I=Xc(v),R=eu(v);f.push(...I),m.push(...R)}for(const I of m)p.push(`${I}:${D}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);n.addTrace(gi.create_authenticated_session_topic);let g;if(f?.length>0){g={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(Vi),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Iu([...new Set(f)],[...new Set(p)]),transportType:a},n.addTrace(gi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw n.setError(Er.subscribe_authenticated_session_topic_failure),y}n.addTrace(gi.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),n.addTrace(gi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(gi.publishing_authenticated_session_approve);try{await this.sendResult({topic:h,id:r,result:{cacaos:s,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:l,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw n.setError(Er.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:g}}),F(this,"rejectSessionAuthenticate",async i=>{this.isInitialized();const{id:r,reason:s}=i,n=this.getPendingAuthRequest(r);if(!n)throw new Error(`Could not find pending auth request with id ${r}`);n.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ts(o),u={type:zt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:u,rpcOpts:Oe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),F(this,"formatAuthMessage",i=>{this.isInitialized();const{request:r,iss:s}=i;return ff(r,s)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const i=this.relayMessageCache.shift();i&&await this.onRelayMessage(i)}catch(i){this.client.logger.error(i)}},50)}),F(this,"cleanupDuplicatePairings",async i=>{if(i.pairingTopic)try{const r=this.client.core.pairing.pairings.get(i.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===i.peer.metadata.url&&n.topic&&n.topic!==r.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),F(this,"deleteSession",async i=>{var r;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=i,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,le("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(oh).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===s&&this.deletePendingSessionRequest(u.id,le("USER_DISCONNECTED"))}),s===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=xt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),F(this,"deleteProposal",async(i,r)=>{if(r)try{const s=this.client.proposal.get(i);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(vr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(i,le("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"proposal")}),F(this,"deletePendingSessionRequest",async(i,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(i,r),s?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==i),s&&(this.sessionRequestQueue.state=xt.idle,this.client.events.emit("session_request_expire",{id:i}))}),F(this,"deletePendingAuthRequest",async(i,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(i,r),s?Promise.resolve():this.client.core.expirer.del(i)])}),F(this,"setExpiry",async(i,r)=>{this.client.session.keys.includes(i)&&(this.client.core.expirer.set(i,r),await this.client.session.update(i,{expiry:r}))}),F(this,"setProposal",async(i,r)=>{this.client.core.expirer.set(i,me(Oe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(i,r)}),F(this,"setAuthRequest",async(i,r)=>{const{request:s,pairingTopic:n,transportType:o=he.relay}=r;this.client.core.expirer.set(i,s.expiryTimestamp),await this.client.auth.requests.set(i,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:i,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async i=>{const{id:r,topic:s,params:n,verifyContext:o}=i,a=n.request.expiryTimestamp||me(Oe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:n,verifyContext:o})}),F(this,"sendRequest",async i=>{const{topic:r,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:h,tvf:l,publishOpts:f={}}=i,p=jt(s,n,c);let d;const g=!!h;try{const v=g?ai:Ye;d=await this.client.core.crypto.encode(r,p,{encoding:v})}catch(v){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),v}let y;if(cS.includes(s)){const v=at(JSON.stringify(p)),m=at(d);y=await this.client.core.verify.register({id:m,decryptedId:v})}const E=ne(ne({},Oe[s].req),f);if(E.attestation=y,o&&(E.ttl=o),a&&(E.id=a),this.client.core.history.set(r,p),g){const v=_s(h,r,d);await global.Linking.openURL(v,this.client.name)}else E.tvf=Le(ne({},l),{correlationId:p.id}),u?(E.internal=Le(ne({},E.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,E)):this.client.core.relayer.publish(r,d,E).catch(v=>this.client.logger.error(v));return p.id}),F(this,"sendProposeSession",async i=>{const{proposal:r,publishOpts:s}=i,n=jt("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,n);const o=await this.client.core.crypto.encode(r.pairingTopic,n,{encoding:Ye}),a=at(JSON.stringify(n)),c=at(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Le(ne({},s),{publishMethod:"wc_proposeSession",attestation:u})})}),F(this,"sendApproveSession",async i=>{const{sessionTopic:r,pairingProposalResponse:s,proposal:n,sessionSettleRequest:o,publishOpts:a}=i,c=Wr(n.id,s),u=await this.client.core.crypto.encode(n.pairingTopic,c,{encoding:Ye}),h=jt("wc_sessionSettle",o,a?.id),l=await this.client.core.crypto.encode(r,h,{encoding:Ye});this.client.core.history.set(r,h),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:n.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:l},opts:Le(ne({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async i=>{const{id:r,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=i,u=Wr(r,n);let h;const l=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=l?ai:Ye;h=await this.client.core.crypto.encode(s,u,Le(ne({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),d}let f,p;try{f=await this.client.core.history.get(s,r);const d=f.request;try{p=this.getTVFParams(r,d.params,n)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),d}if(l){const d=_s(c,s,h);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=Oe[d].res;g.tvf=Le(ne({},p),{correlationId:r}),o?(g.internal=Le(ne({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,h,g)):this.client.core.relayer.publish(s,h,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),F(this,"sendError",async i=>{const{id:r,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=i,u=hn(r,n);let h;const l=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=l?ai:Ye;h=await this.client.core.crypto.encode(s,u,Le(ne({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),p}if(l){const p=_s(c,s,h);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Oe[p].res;this.client.core.relayer.publish(s,h,d)}await this.client.core.history.resolve(u)}),F(this,"cleanup",async()=>{const i=[],r=[];this.client.session.getAll().forEach(s=>{let n=!1;ri(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&i.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{ri(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...i.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])}),F(this,"onProviderMessageEvent",async i=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(i):await this.onRelayMessage(i)}),F(this,"onRelayEventRequest",async i=>{this.requestQueue.queue.push(i),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===xt.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=xt.active;const i=this.requestQueue.queue.shift();if(i)try{await this.processRequest(i)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=xt.idle}),F(this,"processRequest",async i=>{const{topic:r,payload:s,attestation:n,transportType:o,encryptedId:a}=i,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async i=>{const{topic:r,payload:s,transportType:n}=i,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",i=>{const{topic:r}=i,{message:s}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),F(this,"shouldIgnorePairingRequest",i=>{const{topic:r,requestMethod:s}=i,n=this.expectedPairingMethodMap.get(r);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async i=>{const{topic:r,payload:s,attestation:n,encryptedId:o}=i,{params:a,id:c}=s;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Lt.proposal_listener_not_found)),this.isValidConnect(ne({},s.params));const h=a.expiryTimestamp||me(Oe.wc_sessionPropose.req.ttl),l=ne({id:c,pairingTopic:r,expiryTimestamp:h,attestation:n,encryptedId:o},a);await this.setProposal(c,l);const f=await this.getVerifyContext({attestationId:n,hash:at(JSON.stringify(s)),encryptedId:o,metadata:l.proposer.metadata});u?.addTrace(It.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:l,verifyContext:f})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Oe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),F(this,"onSessionProposeResponse",async(i,r,s)=>{const{id:n}=r;if(Dt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const h=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(n,{sessionTopic:h,pairingTopic:i,proposalId:n,publicKey:c});const l=await this.client.core.relayer.subscribe(h,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:l}),await this.client.core.pairing.activate({topic:i})}else if(ct(r)){await this.deleteProposal(n);const o=se("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),F(this,"onSessionSettleRequest",async(i,r)=>{const{id:s,params:n}=r;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:h,scopedProperties:l,sessionConfig:f}=r.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===i);if(!p)return this.client.logger.error(`Pending session not found for topic ${i}`);const d=this.client.proposal.get(p.proposalId),g=Le(ne(ne(ne({topic:i,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},h&&{sessionProperties:h}),l&&{scopedProperties:l}),f&&{sessionConfig:f}),{transportType:he.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(se("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:i,result:!0})}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(i,r)=>{const{id:s}=r;Dt(r)?(await this.client.session.update(i,{acknowledged:!0}),this.events.emit(se("session_approve",s),{})):ct(r)&&(await this.client.session.delete(i,le("USER_DISCONNECTED")),this.events.emit(se("session_approve",s),{error:r.error}))}),F(this,"onSessionUpdateRequest",async(i,r)=>{const{params:s,id:n}=r;try{const o=`${i}_session_update`,a=mr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:i,error:le("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ne({topic:i},s));try{mr.set(o,n),await this.client.session.update(i,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:i,result:!0})}catch(c){throw mr.delete(o),c}this.client.events.emit("session_update",{id:n,topic:i,params:s})}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(i,r)=>r.toString().slice(0,-3)<i.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(i,r)=>{const{id:s}=r,n=se("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Dt(r)?this.events.emit(se("session_update",s),{}):ct(r)&&this.events.emit(se("session_update",s),{error:r.error})}),F(this,"onSessionExtendRequest",async(i,r)=>{const{id:s}=r;try{this.isValidExtend({topic:i}),await this.setExpiry(i,me(Vi)),await this.sendResult({id:s,topic:i,result:!0}),this.client.events.emit("session_extend",{id:s,topic:i})}catch(n){await this.sendError({id:s,topic:i,error:n}),this.client.logger.error(n)}}),F(this,"onSessionExtendResponse",(i,r)=>{const{id:s}=r,n=se("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Dt(r)?this.events.emit(se("session_extend",s),{}):ct(r)&&this.events.emit(se("session_extend",s),{error:r.error})}),F(this,"onSessionPingRequest",async(i,r)=>{const{id:s}=r;try{this.isValidPing({topic:i}),await this.sendResult({id:s,topic:i,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:i})}catch(n){await this.sendError({id:s,topic:i,error:n}),this.client.logger.error(n)}}),F(this,"onSessionPingResponse",(i,r)=>{const{id:s}=r,n=se("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);Dt(r)?this.events.emit(se("session_ping",s),{}):ct(r)&&this.events.emit(se("session_ping",s),{error:r.error})},500)}),F(this,"onSessionDeleteRequest",async(i,r)=>{const{id:s}=r;try{this.isValidDisconnect({topic:i,reason:r.params}),await Promise.all([new Promise(n=>{this.client.core.relayer.once(de.publish,async()=>{n(await this.deleteSession({topic:i,id:s}))})}),this.sendResult({id:s,topic:i,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:i,error:le("USER_DISCONNECTED")})]).catch(n=>this.client.logger.error(n))}catch(n){this.client.logger.error(n)}}),F(this,"onSessionRequest",async i=>{var r,s,n;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:h}=i,{id:l,params:f}=a;try{await this.isValidRequest(ne({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:at(JSON.stringify(jt("wc_sessionRequest",f,l))),encryptedId:u,metadata:p.peer.metadata,transportType:h}),g={id:l,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(g),h===he.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:l,topic:o,error:p}),this.client.logger.error(p)}}),F(this,"onSessionRequestResponse",(i,r)=>{const{id:s}=r,n=se("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);Dt(r)?this.events.emit(se("session_request",s),{result:r.result}):ct(r)&&this.events.emit(se("session_request",s),{error:r.error})}),F(this,"onSessionEventRequest",async(i,r)=>{const{id:s,params:n}=r;try{const o=`${i}_session_event_${n.event.name}`,a=mr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(ne({topic:i},n)),this.client.events.emit("session_event",{id:s,topic:i,params:n}),mr.set(o,s)}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(i,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:i,payload:r}),Dt(r)?this.events.emit(se("session_request",s),{result:r.result}):ct(r)&&this.events.emit(se("session_request",s),{error:r.error})}),F(this,"onSessionAuthenticateRequest",async i=>{var r;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=i;try{const{requester:u,authPayload:h,expiryTimestamp:l}=n.params,f=await this.getVerifyContext({attestationId:o,hash:at(JSON.stringify(n)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:s,id:n.id,authPayload:h,verifyContext:f,expiryTimestamp:l};await this.setAuthRequest(n.id,{request:p,pairingTopic:s,transportType:c}),c===he.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:f})}catch(u){this.client.logger.error(u);const h=n.params.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:zt,receiverPublicKey:h,senderPublicKey:l};await this.sendError({id:n.id,topic:s,error:u,encodeOpts:p,rpcOpts:Oe.wc_sessionAuthenticate.autoReject,appLink:f})}}),F(this,"addSessionRequestToSessionRequestQueue",i=>{this.sessionRequestQueue.queue.push(i)}),F(this,"cleanupAfterResponse",i=>{this.deletePendingSessionRequest(i.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=xt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:i,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===i&&n.request.method==="wc_sessionRequest").forEach(n=>{const o=n.request.id,a=se("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(se("session_request",n.request.id),{error:r})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===xt.active){this.client.logger.info("session request queue is already active.");return}const i=this.sessionRequestQueue.queue[0];if(!i){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(i)}catch(r){this.client.logger.error(r)}}),F(this,"emitSessionRequest",i=>{if(this.emittedSessionRequests.has(i.id)){this.client.logger.warn({id:i.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);return}this.sessionRequestQueue.state=xt.active,this.emittedSessionRequests.add(i.id),this.client.events.emit("session_request",i)}),F(this,"onPairingCreated",i=>{if(i.methods&&this.expectedPairingMethodMap.set(i.topic,i.methods),i.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===i.topic);r&&this.onSessionProposeRequest({topic:i.topic,payload:jt("wc_sessionPropose",Le(ne({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),F(this,"isValidConnect",async i=>{if(!He(i)){const{message:u}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(i)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=i;if(ve(r)||await this.isValidPairingTopic(r),!D3(c,!0)){const{message:u}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!ve(s)&&Hr(s)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(s,"requiredNamespaces")}if(!ve(n)&&Hr(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(s||{}).concat(Object.keys(n||{}));if(!Object.keys(a).every(h=>u.includes(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),F(this,"validateNamespaces",(i,r)=>{const s=S3(i,"connect()",r);if(s)throw new Error(s.message)}),F(this,"isValidApprove",async i=>{if(!He(i))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${i}`).message);const{id:r,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=i;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=Vn(s,"approve()");if(u)throw new Error(u.message);const h=Au(c.requiredNamespaces,s,"approve()");if(h)throw new Error(h.message);if(!ye(n,!0)){const{message:l}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(l)}if(ve(o)||this.validateSessionProps(o,"sessionProperties"),!ve(a)){this.validateSessionProps(a,"scopedProperties");const l=new Set(Object.keys(s));if(!Object.keys(a).every(f=>l.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(l).join(", ")}`)}}),F(this,"isValidReject",async i=>{if(!He(i)){const{message:n}=M("MISSING_OR_INVALID",`reject() params: ${i}`);throw new Error(n)}const{id:r,reason:s}=i;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!$3(s)){const{message:n}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),F(this,"isValidSessionSettleRequest",i=>{if(!He(i)){const{message:u}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${i}`);throw new Error(u)}const{relay:r,controller:s,namespaces:n,expiry:o}=i;if(!Kf(r)){const{message:u}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=b3(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Vn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(ri(o)){const{message:u}=M("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),F(this,"isValidUpdate",async i=>{if(!He(i)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${i}`);throw new Error(c)}const{topic:r,namespaces:s}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const n=this.client.session.get(r),o=Vn(s,"update()");if(o)throw new Error(o.message);const a=Au(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async i=>{if(!He(i)){const{message:s}=M("MISSING_OR_INVALID",`extend() params: ${i}`);throw new Error(s)}const{topic:r}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),F(this,"isValidRequest",async i=>{if(!He(i)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${i}`);throw new Error(c)}const{topic:r,request:s,chainId:n,expiry:o}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Du(a,n)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!O3(s)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!P3(a,n,s.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}if(o&&!U3(o,Zn)){const{message:c}=M("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Zn.min} and ${Zn.max}`);throw new Error(c)}}),F(this,"isValidRespond",async i=>{var r;if(!He(i)){const{message:o}=M("MISSING_OR_INVALID",`respond() params: ${i}`);throw new Error(o)}const{topic:s,response:n}=i;try{await this.isValidSessionTopic(s)}catch(o){throw(r=i?.response)!=null&&r.id&&this.cleanupAfterResponse(i),o}if(!T3(n)){const{message:o}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(o)}}),F(this,"isValidPing",async i=>{if(!He(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidEmit",async i=>{if(!He(i)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${i}`);throw new Error(a)}const{topic:r,event:s,chainId:n}=i;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Du(o,n)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!C3(s)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!R3(o,n,s.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async i=>{if(!He(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidAuthenticate",i=>{const{chains:r,uri:s,domain:n,nonce:o}=i;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ye(s,!1))throw new Error("uri is required parameter");if(!ye(n,!1))throw new Error("domain is required parameter");if(!ye(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>$s(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=$s(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async i=>{const{attestationId:r,hash:s,encryptedId:n,metadata:o,transportType:a}=i,c={verified:{verifyUrl:o.verifyUrl||Br,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const h=this.getAppLinkIfEnabled(o,a);return c.verified.validation=h&&new URL(h).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:n,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(i,r)=>{Object.values(i).forEach((s,n)=>{if(s==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(i)[n]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",i=>{const r=this.client.auth.requests.get(i);return typeof r=="object"?r:void 0}),F(this,"addToRecentlyDeleted",(i,r)=>{if(this.recentlyDeletedMap.set(i,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",i=>{const r=this.recentlyDeletedMap.get(i);if(r){const{message:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${i}`);throw new Error(s)}}),F(this,"isLinkModeEnabled",(i,r)=>{var s,n,o,a,c,u,h,l,f;return!i||r!==he.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((h=i?.redirect)==null?void 0:h.universal)!==void 0&&((l=i?.redirect)==null?void 0:l.universal)!==""&&((f=i?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(i.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(i,r)=>{var s;return this.isLinkModeEnabled(i,r)?(s=i?.redirect)==null?void 0:s.universal:void 0}),F(this,"handleLinkModeMessage",({url:i})=>{if(!i||!i.includes("wc_ev")||!i.includes("topic"))return;const r=Mc(i,"topic")||"",s=decodeURIComponent(Mc(i,"wc_ev")||""),n=this.client.session.keys.includes(r);n&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:n})}),F(this,"registerLinkModeListeners",async()=>{var i;if(fa()||li()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await r.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),F(this,"getTVFParams",(i,r,s)=>{var n,o,a;if(!((n=r.request)!=null&&n.method))return{};const c={correlationId:i,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,s);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),F(this,"isValidContractData",i=>{var r;if(!i)return!1;try{const s=i?.data||((r=i?.[0])==null?void 0:r.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(i,r)=>{var s;try{if(!r)return[];const n=i.method,o=oS[n];if(n==="sui_signTransaction")return[r2(r.transactionBytes)];if(n==="near_signTransaction")return[Gc(r)];if(n==="near_signTransactions")return r.map(c=>Gc(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=r.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[Z3({transaction:i.params.transactionPayload,signature:r.signature})];if(n==="algo_signTxn")return Xi(r)?r.map(c=>Yc(c)):[Yc(r)];if(n==="cosmos_signDirect")return[n2(r)];if(typeof r=="string")return[r];const a=r[o.key];if(Xi(a))return n==="solana_signAllTransactions"?a.map(c=>i2(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn("Error extracting tx hashes from result",n)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,i=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,s]of Object.entries(i))for(const n of s)try{await this.onProviderMessageEvent({topic:r,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${n}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}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(de.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:i,message:r,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Ps)?this.client.auth.authKeys.get(Ps):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(i,r,{receiverPublicKey:o,encoding:n===he.link_mode?ai:Ye});Aa(a)?(this.client.core.history.set(i,a),await this.onRelayEventRequest({topic:i,payload:a,attestation:s,transportType:n,encryptedId:at(r)})):ln(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:i,payload:a,transportType:n}),this.client.core.history.delete(i,a.id)):await this.onRelayEventUnknownPayload({topic:i,payload:a,transportType:n}),await this.client.core.relayer.messages.ack(i,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(ot.expired,async e=>{const{topic:i,id:r}=Jl(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);i?this.client.session.keys.includes(i)&&(await this.deleteSession({topic:i,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:i})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(bi.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(bi.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ye(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(i)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(i)}if(ri(this.client.core.pairing.pairings.get(e).expiry)){const{message:i}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(i)}}async isValidSessionTopic(e){if(!ye(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(i)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(i)}if(ri(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:i}=M("EXPIRED",`session topic: ${e}`);throw new Error(i)}if(!this.client.core.crypto.keychain.has(e)){const{message:i}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(i)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ye(e,!1)){const{message:i}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(i)}else{const{message:i}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(i)}}async isValidProposalId(e){if(!A3(e)){const{message:i}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(i)}if(!this.client.proposal.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(i)}if(ri(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:i}=M("EXPIRED",`proposal id: ${e}`);throw new Error(i)}}}class vS extends Fi{constructor(e,i){super(e,i,rS,Oa),this.core=e,this.logger=i}}class ES extends Fi{constructor(e,i){super(e,i,sS,Oa),this.core=e,this.logger=i}}class _S extends Fi{constructor(e,i){super(e,i,aS,Oa,r=>r.id),this.core=e,this.logger=i}}class xS extends Fi{constructor(e,i){super(e,i,lS,dn,()=>Ps),this.core=e,this.logger=i}}class IS extends Fi{constructor(e,i){super(e,i,fS,dn),this.core=e,this.logger=i}}class SS extends Fi{constructor(e,i){super(e,i,dS,dn,r=>r.id),this.core=e,this.logger=i}}var DS=Object.defineProperty,AS=(t,e,i)=>e in t?DS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Qn=(t,e,i)=>AS(t,typeof e!="symbol"?e+"":e,i);class $S{constructor(e,i){this.core=e,this.logger=i,Qn(this,"authKeys"),Qn(this,"pairingTopics"),Qn(this,"requests"),this.authKeys=new xS(this.core,this.logger),this.pairingTopics=new IS(this.core,this.logger),this.requests=new SS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var OS=Object.defineProperty,TS=(t,e,i)=>e in t?OS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Q=(t,e,i)=>TS(t,typeof e!="symbol"?e+"":e,i);class pn extends Bg{constructor(e){super(e),Q(this,"protocol",dd),Q(this,"version",pd),Q(this,"name",Jn.name),Q(this,"metadata"),Q(this,"core"),Q(this,"logger"),Q(this,"events",new rt.EventEmitter),Q(this,"engine"),Q(this,"session"),Q(this,"proposal"),Q(this,"pendingRequest"),Q(this,"auth"),Q(this,"signConfig"),Q(this,"on",(r,s)=>this.events.on(r,s)),Q(this,"once",(r,s)=>this.events.once(r,s)),Q(this,"off",(r,s)=>this.events.off(r,s)),Q(this,"removeListener",(r,s)=>this.events.removeListener(r,s)),Q(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),Q(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"update",async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"request",async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"find",r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),Q(this,"authenticate",async(r,s)=>{try{return await this.engine.authenticate(r,s)}catch(n){throw this.logger.error(n.message),n}}),Q(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),Q(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}}),this.name=e?.name||Jn.name,this.metadata=Gb(e?.metadata),this.signConfig=e?.signConfig;const i=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Zs(Ho({level:e?.logger||Jn.logger}));this.core=e?.core||new iS(e),this.logger=je(i,this.name),this.session=new ES(this.core,this.logger),this.proposal=new vS(this.core,this.logger),this.pendingRequest=new _S(this.core,this.logger),this.engine=new bS(this),this.auth=new $S(this.core,this.logger)}static async init(e){const i=new pn(e);return await i.initialize(),i}get context(){return Qe(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 Xn=yt.getDevice(),CS={width:"245px",height:"245px",borderRadius:"40px",zIndex:"99999",backgroundColor:"white",border:"none",outline:"none"},PS=`
<div id="argent-mobile-modal-container" style="position: relative; display: flex; justify-content: center; align-items: center">
<iframe class="argent-iframe" allow="clipboard-write"></iframe>
</div>
`;class RS{constructor(){W(this,"bridgeUrl","https://login.ready.co");W(this,"mobileUrl","ready://");W(this,"type","overlay");W(this,"wcUri");W(this,"overlay");W(this,"popupWindow");W(this,"closingTimeout");W(this,"standaloneConnectorModal")}showWalletConnectModal(e,i){const r=encodeURIComponent(e),s=encodeURIComponent(window.location.href);this.showModal({desktop:`${this.bridgeUrl}?wc=${r}&href=${s}&device=desktop&onlyQR=true`,ios:`${this.mobileUrl}app/wc?uri=${r}&href=${s}&device=mobile&onlyQR=true`,android:`${this.mobileUrl}app/wc?uri=${r}&href=${s}&device=mobile&onlyQR=true`},i)}getWalletConnectQR(e){const i=encodeURIComponent(e),r=encodeURIComponent(window.location.href);this.getQR({desktop:`${this.bridgeUrl}?wc=${i}&href=${r}&device=desktop&onlyQR=true`,ios:`${this.mobileUrl}app/wc?uri=${i}&href=${r}&device=mobile&onlyQR=true`,android:`${this.mobileUrl}app/wc?uri=${i}&href=${r}&device=mobile&onlyQR=true`})}openMobileApp(e){const i=document.createElement("button");i.style.display="none",i.addEventListener("click",()=>{window.location.href=e[Xn]}),i.click()}getQR(e){if(["android","ios"].includes(Xn)){this.openMobileApp(e);return}const i=document.createElement("div"),r=document.querySelector("#starknetkit-modal-container");if(r?.shadowRoot){const s=r.shadowRoot.querySelector(".qr-code-slot");if(s){s.innerHTML=PS,document.body.appendChild(i),this.overlay=i;const n=s.querySelector("iframe");n.setAttribute("src",e.desktop);for(const[o,a]of Object.entries(CS))n.style[o]=a}else throw new Error("Cannot find QR code slot")}else throw new Error("Cannot find modal")}showApprovalModal(e){const i=encodeURIComponent(window.location.href),r={desktop:`${this.bridgeUrl}?action=sign&device=desktop&href=${i}`,ios:`${this.mobileUrl}app/wc/request?href=${i}&device=mobile`,android:`${this.mobileUrl}app/wc/request?href=${i}&device=mobile`};if(!hh.isInArgentMobileAppBrowser()){if(this.getModal(void 0,yt.Layout.approval),["android","ios"].includes(Xn)){this.openMobileApp(r);return}return}this.showModal(r,void 0)}closeModal({success:e,isRequest:i}={success:!1,isRequest:!1}){const r=this.standaloneConnectorModal;e?(r?.$set({layout:yt.Layout.success}),setTimeout(()=>r?.$destroy(),500)):i?(r?.$set({layout:yt.Layout.requestFailure}),setTimeout(()=>r?.$destroy(),500)):r?.$set({layout:yt.Layout.loginFailure})}getModal(e,i=yt.Layout.qrCode){this.standaloneConnectorModal=new yt.Modal({target:yt.getModalTarget(),props:{layout:i,dappName:e?.dappName,showBackButton:!1,selectedWallet:e,callback:async r=>{try{const s=r?.connector;this.standaloneConnectorModal?.$destroy(),await s?.connect()}catch{this.standaloneConnectorModal?.$set({layout:yt.Layout.loginFailure})}}}})}showModal(e,i){this.getModal(i,yt.Layout.qrCode),this.getQR(e)}}const mt=new RS,Gs=At.constants.NetworkName,FS=async({projectId:t,chainId:e,name:i,description:r,rpcUrl:s,bridgeUrl:n=BS(e),mobileUrl:o=US(e),modalType:a="overlay",url:c,icons:u,walletConnect:h,onlyQRCode:l,modalWallet:f},p)=>{if(!n)throw new Error("bridgeUrl is required");if(!o)throw new Error("mobileUrl is required");mt.bridgeUrl=n,mt.mobileUrl=o,mt.type=a;const d={projectId:t,metadata:{name:i??"Unknown dapp",description:r??"Unknown dapp description",url:c??"#",icons:u??[],...h?.metadata}},g=await pn.init(d),y=new At.RpcProvider({nodeUrl:s}),E=new p({client:g,chainId:e,rpcUrl:s,provider:y});g.on("session_event",v=>{}),g.on("session_update",({topic:v,params:m})=>{const{namespaces:D}=m,I=g.session.get(v);E.updateSession({...I,namespaces:D})}),g.on("session_delete",()=>{});try{const v=g.session.getAll().find(E.isValidSession);if(v)return E.updateSession(v),E;const m={requiredNamespaces:E.getRequiredNamespaces()};hh.resetWalletConnect(),await new Promise(R=>setTimeout(R,200));const{uri:D,approval:I}=await g.connect(m);if(D){l?mt.getWalletConnectQR(D):mt.showWalletConnectModal(D,{...f,dappName:i||""}),mt.wcUri=D;const R=await I();E.updateSession(R),mt.closeModal({success:!0})}return E}catch{return console.error("@argent/login::error"),mt.closeModal(),null}},BS=t=>{if(!t)throw new Error(`Unknown or unsupported chainId (${t}), either specify a supported chain or set bridgeUrl.`);const e=parseInt(`${t}`);if(String(t).startsWith(Gs.SN_SEPOLIA)||e===11155111)return"https://mobile-login.hydrogen.argent47.net";if(String(t).startsWith(Gs.SN_MAIN)||e===1)return"https://login.argent.xyz"},US=t=>{if(!t)throw new Error(`Unknown or unsupported chainId (${t}), either specify a supported chain or set mobileUrl.`);const e=parseInt(`${t}`);if(String(t).startsWith(Gs.SN_SEPOLIA)||e===11155111)return"argent-dev://";if(String(t).startsWith(Gs.SN_MAIN)||e===1)return"argent://"};var NS=Object.defineProperty,kS=(t,e,i)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,yi=(t,e,i)=>kS(t,typeof e!="symbol"?e+"":e,i);function LS(t){return typeof t<"u"&&typeof t.context<"u"}const $t={init:"signer_init",uri:"signer_uri",created:"signer_created",updated:"signer_updated",deleted:"signer_deleted",event:"signer_event"};class MS extends u_{constructor(e){super(),yi(this,"events",new rt.EventEmitter),yi(this,"requiredNamespaces"),yi(this,"pending",!1),yi(this,"session"),yi(this,"opts"),yi(this,"client"),yi(this,"initializing",!1),this.requiredNamespaces=e?.requiredNamespaces||{},this.opts=e?.client}get connected(){return typeof this.session<"u"}get connecting(){return this.pending}get chains(){return this.session?Hl(this.session.namespaces):Ub(this.requiredNamespaces)}get accounts(){return this.session?Vl(this.session.namespaces):[]}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(){if(this.pending)return new Promise((e,i)=>{this.events.once("open",()=>{if(this.events.once("open_error",r=>{i(r)}),typeof this.client>"u")return i(new Error("Sign Client not initialized"));e()})});try{this.pending=!0;const e=await this.register(),i=e.find({requiredNamespaces:this.requiredNamespaces});if(i.length)return this.onOpen(i[0]);const{uri:r,approval:s}=await e.connect({requiredNamespaces:this.requiredNamespaces});this.events.emit($t.uri,{uri:r}),this.session=await s(),this.events.emit($t.created,this.session),this.onOpen()}catch(e){throw this.events.emit("open_error",e),e}}async close(){typeof this.session>"u"||(await(await this.register()).disconnect({topic:this.session.topic,reason:le("USER_DISCONNECTED")}),this.onClose())}async send(e,i){if(typeof this.client>"u"&&(this.client=await this.register(),this.connected||await this.open()),typeof this.session>"u")throw new Error("Signer connection is missing session");this.client.request({topic:this.session.topic,request:e,chainId:i?.chainId}).then(r=>this.events.emit("payload",Wr(e.id,r))).catch(r=>this.events.emit("payload",hn(e.id,r.message)))}async register(e=this.opts){if(typeof this.client<"u")return this.client;if(this.initializing)return new Promise((i,r)=>{this.events.once("register_error",s=>{r(s)}),this.events.once($t.init,()=>{if(typeof this.client>"u")return r(new Error("Sign Client not initialized"));i(this.client)})});if(LS(e))return this.client=e,this.registerEventListeners(),this.client;try{return this.initializing=!0,this.client=await pn.init(e),this.initializing=!1,this.registerEventListeners(),this.events.emit($t.init),this.client}catch(i){throw this.events.emit("register_error",i),i}}onOpen(e){this.pending=!1,e&&(this.session=e),this.events.emit("open")}onClose(){this.pending=!1,this.client&&(this.client=void 0),this.events.emit("close")}registerEventListeners(){typeof this.client<"u"&&(this.client.on("session_event",e=>{var i;this.session&&((i=this.session)==null?void 0:i.topic)!==e.topic||this.events.emit($t.event,e.params)}),this.client.on("session_update",e=>{var i;typeof this.client<"u"&&(this.session&&((i=this.session)==null?void 0:i.topic)!==e.topic||(this.session=this.client.session.get(e.topic),this.events.emit($t.updated,this.session)))}),this.client.on("session_delete",e=>{var i;this.session&&(this.session&&((i=this.session)==null?void 0:i.topic)!==e.topic||(this.onClose(),this.events.emit($t.deleted,this.session),this.session=void 0))}))}}class qS{constructor(){W(this,"accounts",[]);W(this,"eventEmitter",new rt.EventEmitter);W(this,"updateSession",e=>{if(!this.isValidSession(e))throw console.warn("updateSession incompatible session",e,"for adapter",this.formatChainId(this.chainId)),new Error("Invalid session");this.session=e;const i=Hl(e.namespaces,[this.namespace]);this.setChainIds(i);const r=Vl(e.namespaces,[this.namespace]);this.setAccounts(r)});W(this,"isValidSession",({namespaces:e,requiredNamespaces:i})=>{const r=this.formatChainId(this.chainId);return i&&Object.keys(i).length>0?!!i[this.namespace]?.chains?.includes(r):!!e?.[this.namespace]?.accounts.some(s=>s.startsWith(r))})}getRequiredNamespaces(){const e=[this.formatChainId(this.chainId)];return{[this.namespace]:{chains:e,methods:this.methods,events:this.events}}}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}setChainIds(e){const r=e.filter(s=>this.isCompatibleChainId(s)).map(s=>this.parseChainId(s)).filter(s=>s!==this.chainId);r.length&&(this.chainId=r[0],this.eventEmitter.emit("chainChanged",this.chainId))}setChainId(e){this.isCompatibleChainId(e)&&(this.chainId=this.parseChainId(e),this.eventEmitter.emit("chainChanged",this.chainId))}parseAccountId(e){const[i,r,s]=e.split(":");return{chainId:`${i}:${r}`,address:s}}getSignerConnection(e){return new MS({requiredNamespaces:{[this.namespace]:{chains:this.rpc.chains,methods:this.rpc.methods,events:this.rpc.events}},client:e})}registerEventListeners(){this.rpcProvider.on("connect",()=>{const{chains:e,accounts:i}=this.signerConnection;e?.length&&this.setChainIds(e),i?.length&&this.setAccounts(i)}),this.signerConnection.on($t.created,this.updateSession),this.signerConnection.on($t.updated,this.updateSession),this.signerConnection.on($t.event,e=>{if(!this.rpc.chains.includes(e.chainId))return;const{event:i}=e;i.name==="accountsChanged"?(this.accounts=i.data,this.eventEmitter.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(i.data):this.eventEmitter.emit(i.name,i.data)}),this.rpcProvider.on("disconnect",()=>{this.eventEmitter.emit("disconnect")})}}class uh extends At.Account{constructor(e,i,r,s){super({provider:e,address:i,signer:r}),this.wallet=s}async execute(e,i,r={}){const s=Array.isArray(e)?e:[e],n=i===void 0||Array.isArray(i)?r:i;return await this.wallet.wallet_requestAddInvokeTransaction({accountAddress:this.address,executionRequest:{calls:s,invocationDetails:n}})}async declare(e,i){throw new Error("Not supported via Ready Login")}async deployAccount(e,i){throw new Error("Not supported via Ready Login")}}class jS{constructor(e){this.wallet=e}async getPubKey(){throw new Error("Not supported via Ready Login")}async signMessage(e,i){const{signature:r}=await this.wallet.wallet_signTypedData({accountAddress:i,typedData:e});return r}async signTransaction(e,i,r){throw new Error("Not supported via Ready Login")}async signDeployAccountTransaction(e){throw new Error("Not supported via Ready Login")}async signDeclareTransaction(e){throw new Error("Not supported via Ready Login")}}const zS=t=>t.replace(/^SN_/,"SN"),KS=t=>t.replace(/^SN/,"SN_");class VS extends qS{constructor({client:i,chainId:r,rpcUrl:s,provider:n}){super();W(this,"id","argentMobile");W(this,"name","Ready (formerly Argent)");W(this,"version","0.1.0");W(this,"icon","");W(this,"provider");W(this,"signer");W(this,"account");W(this,"selectedAddress","");W(this,"namespace","starknet");W(this,"methods",["starknet_supportedSpecs","starknet_signTypedData","starknet_requestAddInvokeTransaction","wallet_supportedSpecs","wallet_signTypedData","wallet_addInvokeTransaction"]);W(this,"events",["chainChanged","accountsChanged"]);W(this,"remoteSigner");W(this,"signerConnection");W(this,"rpcProvider");W(this,"chainId");W(this,"client");W(this,"session");W(this,"rpc");W(this,"walletRpc");W(this,"handleRequest");W(this,"request",async i=>{if(!this.session)throw new Error("No session");let r=i.type;(r==="wallet_addInvokeTransaction"||r==="wallet_supportedSpecs"||r==="wallet_signTypedData")&&(r=r.replace("wallet_","starknet_"));const s=this.handleRequest[r];if(s)return s(i.params);throw new Error(`Not implemented: .request() for ${i.type}`)});W(this,"on",(i,r)=>{this.eventEmitter.on(i,r)});W(this,"off",(i,r)=>{this.eventEmitter.off(i,r)});W(this,"handleRequestChainId",()=>this.chainId===At.constants.NetworkName.SN_SEPOLIA?At.constants.StarknetChainId.SN_SEPOLIA:At.constants.StarknetChainId.SN_MAIN);W(this,"handleRequestAccounts",()=>this.accounts);W(this,"handleGetPermissions",async()=>await this.isPreauthorized()?["accounts"]:[]);W(this,"handleAddInvokeTransaction",async i=>{const{calls:r}=i;return await this.requestWallet({method:"starknet_requestAddInvokeTransaction",params:{accountAddress:this.account.address,executionRequest:{calls:r?.map(({contract_address:s,entry_point:n,...o})=>({...o,contractAddress:s,entrypoint:n}))}}})});W(this,"handleSignTypedData",async i=>{const r={accountAddress:this.account.address,typedData:i},s=await this.requestWallet({method:"starknet_signTypedData",params:r});return"signature"in s?s.signature:s});W(this,"handleSupportedSpecs",async()=>await this.requestWallet({method:"starknet_supportedSpecs",params:{}}));this.chainId=String(r??At.constants.NetworkName.SN_MAIN),this.rpc={chains:r?[this.formatChainId(this.chainId)]:[],methods:this.methods,events:this.events},this.signerConnection=this.getSignerConnection(i),this.rpcProvider=new Jf(this.signerConnection),this.client=i,this.registerEventListeners(),this.walletRpc=new Proxy({},{get:(o,a)=>c=>this.requestWallet({method:a,params:c})}),this.remoteSigner=new jS(this.walletRpc),this.provider=n||new At.RpcProvider({nodeUrl:s}),this.account=new uh(this.provider,"",this.remoteSigner,this.walletRpc),this.handleRequest=Object.freeze({wallet_requestChainId:this.handleRequestChainId,wallet_requestAccounts:this.handleRequestAccounts,wallet_getPermissions:this.handleGetPermissions,starknet_addInvokeTransaction:this.handleAddInvokeTransaction,starknet_signTypedData:this.handleSignTypedData,starknet_supportedSpecs:this.handleSupportedSpecs,wallet_addInvokeTransaction:this.handleAddInvokeTransaction,wallet_signTypedData:this.handleSignTypedData,wallet_supportedSpecs:this.handleSupportedSpecs})}getNetworkName(i){if(i==="SN_SEPOLIA")return At.constants.NetworkName.SN_SEPOLIA;if(i==="SN_MAIN")return At.constants.NetworkName.SN_MAIN;throw new Error(`Unknown starknet.js network name for chainId ${i}`)}async enable(){return await this.rpcProvider.connect(),this.accounts}get isConnected(){return!0}async isPreauthorized(){return!!this.client.session.getAll().find(this.isValidSession)}async requestWallet(i){if(!this.session)throw new Error("No session");try{const{topic:r}=this.session,s=this.formatChainId(this.chainId);mt.showApprovalModal(i);const n=await this.client.request({topic:r,chainId:s,request:i});return mt.closeModal({success:!0}),n}catch(r){throw mt.closeModal({isRequest:!0}),r instanceof Error||r&&r.message!==void 0?new Error(r.message):new Error("Unknown error on requestWallet")}}get isConnecting(){return this.signerConnection.connecting}async disable(){await this.rpcProvider.disconnect()}get isWalletConnect(){return!0}registerEventListeners(){super.registerEventListeners(),this.eventEmitter.on("chainChanged",i=>{throw new Error("Not implemented: chainChanged")})}formatChainId(i){return`${this.namespace}:${zS(i)}`}parseChainId(i){return KS(i.split(":")[1])}setAccounts(i){this.accounts=i.filter(n=>this.parseChainId(this.parseAccountId(n).chainId)===this.chainId).map(n=>this.parseAccountId(n).address);const{address:r}=this.parseAccountId(i[0]),s=r.startsWith("0x")?r:`0x${r}`;this.account=new uh(this.provider,s,this.remoteSigner,this.walletRpc),this.eventEmitter.emit("accountsChanged",this.accounts),this.selectedAddress=s}}const HS=async t=>FS(t,VS),WS=Object.freeze(Object.defineProperty({__proto__:null,getStarknetWindowObject:HS},Symbol.toStringTag,{value:"Module"}));exports.Hash=fl;exports.abytes=Ji;exports.aexists=go;exports.ahash=nw;exports.anumber=qr;exports.aoutput=ll;exports.clean=ia;exports.concatBytes=dw;exports.createHasher=dl;exports.createView=aw;exports.index=WS;exports.randomBytes=pw;exports.rotr=cw;exports.toBytes=ra;