@reown/walletkit 1.2.10 → 1.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,4 +1,4 @@
1
- (function(Ne,Rt){typeof exports=="object"&&typeof module<"u"?Rt(exports):typeof define=="function"&&define.amd?define(["exports"],Rt):(Ne=typeof globalThis<"u"?globalThis:Ne||self,Rt(Ne["@reown/walletkit"]={}))})(this,function(Ne){"use strict";var Rt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function lu(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Ue={exports:{}},ln=typeof Reflect=="object"?Reflect:null,hu=ln&&typeof ln.apply=="function"?ln.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Hi;ln&&typeof ln.ownKeys=="function"?Hi=ln.ownKeys:Object.getOwnPropertySymbols?Hi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Hi=function(e){return Object.getOwnPropertyNames(e)};function s0(t){console&&console.warn&&console.warn(t)}var fu=Number.isNaN||function(e){return e!==e};function se(){se.init.call(this)}Ue.exports=se,Ue.exports.once=u0,se.EventEmitter=se,se.prototype._events=void 0,se.prototype._eventsCount=0,se.prototype._maxListeners=void 0;var du=10;function Wi(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return du},set:function(t){if(typeof t!="number"||t<0||fu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");du=t}}),se.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},se.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||fu(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 pu(t){return t._maxListeners===void 0?se.defaultMaxListeners:t._maxListeners}se.prototype.getMaxListeners=function(){return pu(this)},se.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")hu(c,this,r);else for(var u=c.length,l=mu(c,u),n=0;n<u;++n)hu(l[n],this,r);return!0};function gu(t,e,r,n){var i,s,o;if(Wi(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=pu(t),i>0&&o.length>i&&!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,s0(a)}return t}se.prototype.addListener=function(e,r){return gu(this,e,r,!1)},se.prototype.on=se.prototype.addListener,se.prototype.prependListener=function(e,r){return gu(this,e,r,!0)};function o0(){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 yu(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=o0.bind(n);return i.listener=r,n.wrapFn=i,i}se.prototype.once=function(e,r){return Wi(r),this.on(e,yu(this,e,r)),this},se.prototype.prependOnceListener=function(e,r){return Wi(r),this.prependListener(e,yu(this,e,r)),this},se.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Wi(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():a0(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function wu(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?c0(i):mu(i,i.length)}se.prototype.listeners=function(e){return wu(this,e,!0)},se.prototype.rawListeners=function(e){return wu(this,e,!1)},se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):bu.call(t,e)},se.prototype.listenerCount=bu;function bu(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Hi(this._events):[]};function mu(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function a0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function c0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function u0(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}vu(t,e,s,{once:!0}),e!=="error"&&l0(t,i,{once:!0})})}function l0(t,e,r){typeof t.on=="function"&&vu(t,"error",e,r)}function vu(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const Eu="wc",h0=2,fo="WalletKit",f0=`${Eu}@2:${fo}:`,d0={database:":memory:"},p0="request";var M={};/*! *****************************************************************************
1
+ (function(Re,Ct){typeof exports=="object"&&typeof module<"u"?Ct(exports):typeof define=="function"&&define.amd?define(["exports"],Ct):(Re=typeof globalThis<"u"?globalThis:Re||self,Ct(Re["@reown/walletkit"]={}))})(this,function(Re){"use strict";var Ct=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function gu(t){var e=t.default;if(typeof e=="function"){var r=function(){return e.apply(this,arguments)};r.prototype=e.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(t).forEach(function(n){var i=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(r,n,i.get?i:{enumerable:!0,get:function(){return t[n]}})}),r}var Ce={exports:{}},dn=typeof Reflect=="object"?Reflect:null,yu=dn&&typeof dn.apply=="function"?dn.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},Hi;dn&&typeof dn.ownKeys=="function"?Hi=dn.ownKeys:Object.getOwnPropertySymbols?Hi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Hi=function(e){return Object.getOwnPropertyNames(e)};function D0(t){console&&console.warn&&console.warn(t)}var wu=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}Ce.exports=oe,Ce.exports.once=B0,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var bu=10;function Wi(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 bu},set:function(t){if(typeof t!="number"||t<0||wu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");bu=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||wu(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 mu(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return mu(this)},oe.prototype.emit=function(e){for(var r=[],n=1;n<arguments.length;n++)r.push(arguments[n]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(r.length>0&&(o=r[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")yu(c,this,r);else for(var u=c.length,l=Su(c,u),n=0;n<u;++n)yu(l[n],this,r);return!0};function vu(t,e,r,n){var i,s,o;if(Wi(r),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,r.listener?r.listener:r),s=t._events),o=s[e]),o===void 0)o=s[e]=r,++t._eventsCount;else if(typeof o=="function"?o=s[e]=n?[r,o]:[o,r]:n?o.unshift(r):o.push(r),i=mu(t),i>0&&o.length>i&&!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,D0(a)}return t}oe.prototype.addListener=function(e,r){return vu(this,e,r,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(e,r){return vu(this,e,r,!0)};function A0(){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 Eu(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=A0.bind(n);return i.listener=r,n.wrapFn=i,i}oe.prototype.once=function(e,r){return Wi(r),this.on(e,Eu(this,e,r)),this},oe.prototype.prependOnceListener=function(e,r){return Wi(r),this.prependListener(e,Eu(this,e,r)),this},oe.prototype.removeListener=function(e,r){var n,i,s,o,a;if(Wi(r),i=this._events,i===void 0)return this;if(n=i[e],n===void 0)return this;if(n===r||n.listener===r)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,n.listener||r));else if(typeof n!="function"){for(s=-1,o=n.length-1;o>=0;o--)if(n[o]===r||n[o].listener===r){a=n[o].listener,s=o;break}if(s<0)return this;s===0?n.shift():$0(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this},oe.prototype.off=oe.prototype.removeListener,oe.prototype.removeAllListeners=function(e){var r,n,i;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var s=Object.keys(n),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(r=n[e],typeof r=="function")this.removeListener(e,r);else if(r!==void 0)for(i=r.length-1;i>=0;i--)this.removeListener(e,r[i]);return this};function xu(t,e,r){var n=t._events;if(n===void 0)return[];var i=n[e];return i===void 0?[]:typeof i=="function"?r?[i.listener||i]:[i]:r?O0(i):Su(i,i.length)}oe.prototype.listeners=function(e){return xu(this,e,!0)},oe.prototype.rawListeners=function(e){return xu(this,e,!1)},oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):_u.call(t,e)},oe.prototype.listenerCount=_u;function _u(t){var e=this._events;if(e!==void 0){var r=e[t];if(typeof r=="function")return 1;if(r!==void 0)return r.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?Hi(this._events):[]};function Su(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function $0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function O0(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function B0(t,e){return new Promise(function(r,n){function i(o){t.removeListener(e,s),n(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),r([].slice.call(arguments))}Iu(t,e,s,{once:!0}),e!=="error"&&T0(t,i,{once:!0})})}function T0(t,e,r){typeof t.on=="function"&&Iu(t,"error",e,r)}function Iu(t,e,r,n){if(typeof t.on=="function")n.once?t.once(e,r):t.on(e,r);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){n.once&&t.removeEventListener(e,i),r(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const Du="wc",P0=2,bo="WalletKit",R0=`${Du}@2:${bo}:`,C0={database:":memory:"},U0="request";var M={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -11,21 +11,21 @@
11
11
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */var po=function(t,e){return po=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},po(t,e)};function g0(t,e){po(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var go=function(){return go=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},go.apply(this,arguments)};function y0(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function w0(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function b0(t,e){return function(r,n){e(r,n,t)}}function m0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function v0(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function E0(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function x0(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function _0(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function yo(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function xu(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function S0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(xu(arguments[e]));return t}function I0(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Fn(t){return this instanceof Fn?(this.v=t,this):new Fn(t)}function A0(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){n[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(n[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Fn?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function D0(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Fn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function $0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof yo=="function"?yo(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function O0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function B0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function T0(t){return t&&t.__esModule?t:{default:t}}function P0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function C0(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var R0=Object.freeze({__proto__:null,__extends:g0,get __assign(){return go},__rest:y0,__decorate:w0,__param:b0,__metadata:m0,__awaiter:v0,__generator:E0,__createBinding:x0,__exportStar:_0,__values:yo,__read:xu,__spread:S0,__spreadArrays:I0,__await:Fn,__asyncGenerator:A0,__asyncDelegator:D0,__asyncValues:$0,__makeTemplateObject:O0,__importStar:B0,__importDefault:T0,__classPrivateFieldGet:P0,__classPrivateFieldSet:C0}),Gi=lu(R0),wo={},kn={},_u;function N0(){if(_u)return kn;_u=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return kn.delay=t,kn}var kr={},bo={},Lr={},Su;function U0(){return Su||(Su=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.ONE_THOUSAND=Lr.ONE_HUNDRED=void 0,Lr.ONE_HUNDRED=100,Lr.ONE_THOUSAND=1e3),Lr}var mo={},Iu;function F0(){return Iu||(Iu=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}(mo)),mo}var Au;function Du(){return Au||(Au=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(U0(),t),e.__exportStar(F0(),t)}(bo)),bo}var $u;function k0(){if($u)return kr;$u=1,Object.defineProperty(kr,"__esModule",{value:!0}),kr.fromMiliseconds=kr.toMiliseconds=void 0;const t=Du();function e(n){return n*t.ONE_THOUSAND}kr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return kr.fromMiliseconds=r,kr}var Ou;function L0(){return Ou||(Ou=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(N0(),t),e.__exportStar(k0(),t)}(wo)),wo}var hn={},Bu;function M0(){if(Bu)return hn;Bu=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return hn.Watch=t,hn.default=t,hn}var vo={},Ln={},Tu;function z0(){if(Tu)return Ln;Tu=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.IWatch=void 0;class t{}return Ln.IWatch=t,Ln}var Pu;function q0(){return Pu||(Pu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Gi.__exportStar(z0(),t)}(vo)),vo}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(L0(),t),e.__exportStar(M0(),t),e.__exportStar(q0(),t),e.__exportStar(Du(),t)})(M);class Mr{}class j0 extends Mr{constructor(e){super()}}const Cu=M.FIVE_SECONDS,zr={pulse:"heartbeat_pulse"};class Eo extends j0{constructor(e){super(e),this.events=new Ue.exports.EventEmitter,this.interval=Cu,this.interval=e?.interval||Cu}static async init(e){const r=new Eo(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(zr.pulse)}}const V0=/"(?:_|\\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*:/,K0=/"(?: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*:/,H0=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function W0(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){G0(t);return}return e}function G0(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Yi(t,e={}){if(typeof t!="string")return t;const r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){const n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!H0.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(V0.test(t)||K0.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,W0)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}function Y0(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return Y0(t(...e))}catch(r){return Promise.reject(r)}}function Z0(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function J0(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Zi(t){if(Z0(t))return String(t);if(J0(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Zi(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Ru(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const xo="base64:";function X0(t){if(typeof t=="string")return t;Ru();const e=Buffer.from(t).toString("base64");return xo+e}function Q0(t){return typeof t!="string"||!t.startsWith(xo)?t:(Ru(),Buffer.from(t.slice(xo.length),"base64"))}function Ye(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function ey(...t){return Ye(t.join(":"))}function Ji(t){return t=Ye(t),t?t+":":""}function T5(t){return t}const ty="memory",ry=()=>{const t=new Map;return{name:ty,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function ny(t={}){const e={mounts:{"":t.driver||ry()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},n=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),i=(u,l)=>{if(e.watching){l=Ye(l);for(const h of e.watchListeners)h(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Nu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{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=Ye(g?d:d.key),_=g?void 0:d.value,A=g||!d.options?l:{...l,...d.options},m=r(y);p(m).items.push({key:y,value:_,relativeKey:m.relativeKey,options:A})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=Ye(u);const{relativeKey:h,driver:f}=r(u);return xe(f.hasItem,h,l)},getItem(u,l={}){u=Ye(u);const{relativeKey:h,driver:f}=r(u);return xe(f.getItem,h,l).then(p=>Yi(p))},getItems(u,l){return a(u,l,h=>h.driver.getItems?xe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:ey(h.base,p.key),value:Yi(p.value)}))):Promise.all(h.items.map(f=>xe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:Yi(p)})))))},getItemRaw(u,l={}){u=Ye(u);const{relativeKey:h,driver:f}=r(u);return f.getItemRaw?xe(f.getItemRaw,h,l):xe(f.getItem,h,l).then(p=>Q0(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ye(u);const{relativeKey:f,driver:p}=r(u);p.setItem&&(await xe(p.setItem,f,Zi(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return xe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Zi(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>xe(h.driver.setItem,f.relativeKey,Zi(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ye(u);const{relativeKey:f,driver:p}=r(u);if(p.setItemRaw)await xe(p.setItemRaw,f,l,h);else if(p.setItem)await xe(p.setItem,f,X0(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ye(u);const{relativeKey:h,driver:f}=r(u);f.removeItem&&(await xe(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await xe(f.removeItem,h+"$",l),f.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ye(u);const{relativeKey:h,driver:f}=r(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await xe(f.getMeta,h,l)),!l.nativeOnly){const d=await xe(f.getItem,h+"$",l).then(g=>Yi(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,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Ji(u);const h=n(u,!0);let f=[];const p=[];for(const d of h){const g=await xe(d.driver.getKeys,d.relativeBase,l);for(const y of g){const _=d.mountpoint+Ye(y);f.some(A=>_.startsWith(A))||p.push(_)}f=[d.mountpoint,...f.filter(y=>!y.startsWith(d.mountpoint))]}return u?p.filter(d=>d.startsWith(u)&&d[d.length-1]!=="$"):p.filter(d=>d[d.length-1]!=="$")},async clear(u,l={}){u=Ji(u),await Promise.all(n(u,!1).map(async h=>{if(h.driver.clear)return xe(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Uu(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=Ji(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(Nu(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=Ji(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),l&&await Uu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ye(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ye(u),n(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function Nu(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function Uu(t){typeof t.dispose=="function"&&await xe(t.dispose)}function qr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Fu(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const n=qr(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}let _o;function Mn(){return _o||(_o=Fu("keyval-store","keyval")),_o}function ku(t,e=Mn()){return e("readonly",r=>qr(r.get(t)))}function iy(t,e,r=Mn()){return r("readwrite",n=>(n.put(e,t),qr(n.transaction)))}function sy(t,e=Mn()){return e("readwrite",r=>(r.delete(t),qr(r.transaction)))}function oy(t=Mn()){return t("readwrite",e=>(e.clear(),qr(e.transaction)))}function ay(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},qr(t.transaction)}function cy(t=Mn()){return t("readonly",e=>{if(e.getAllKeys)return qr(e.getAllKeys());const r=[];return ay(e,n=>r.push(n.key)).then(()=>r)})}const uy=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),ly=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,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function fn(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return ly(t)}catch{return t}}function jr(t){return typeof t=="string"?t:uy(t)||""}const hy="idb-keyval";var fy=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=Fu(t.dbName,t.storeName)),{name:hy,options:t,async hasItem(i){return!(typeof await ku(r(i),n)>"u")},async getItem(i){return await ku(r(i),n)??null},setItem(i,s){return iy(r(i),s,n)},removeItem(i){return sy(r(i),n)},getKeys(){return cy(n)},clear(){return oy(n)}}};const dy="WALLET_CONNECT_V2_INDEXED_DB",py="keyvaluestorage";class gy{constructor(){this.indexedDb=ny({driver:fy({dbName:dy,storeName:py})})}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 r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,jr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var So=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Xi={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof So<"u"&&So.localStorage?Xi.exports=So.localStorage:typeof window<"u"&&window.localStorage?Xi.exports=window.localStorage:Xi.exports=new e})();function yy(t){var e;return[t[0],fn((e=t[1])!=null?e:"")]}class wy{constructor(){this.localStorage=Xi.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(yy)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return fn(r)}async setItem(e,r){this.localStorage.setItem(e,jr(r))}async removeItem(e){this.localStorage.removeItem(e)}}const by="wc_storage_version",Lu=1,my=async(t,e,r)=>{const n=by,i=await e.getItem(n);if(i&&i>=Lu){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(n,Lu),r(e),vy(t,o)},vy=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class Ey{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new wy;this.storage=e;try{const r=new gy;my(e,r,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,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}function xy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var _y=Sy;function Sy(t,e,r){var n=r&&r.stringify||xy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a<s;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=n(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const Mu=_y;var Gt=Nt;const zn=Ry().console||{},Iy={mapHttpRequest:es,mapHttpResponse:es,wrapRequestSerializer:Ao,wrapResponseSerializer:Ao,wrapErrorSerializer:Ao,req:es,res:es,err:By};function Ay(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Nt(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 r=t.browser.write||zn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=Ay(t.browser.serialize,n);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=qn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:f});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:Ty(t)};c.levels=Nt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=qn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=Io());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,dn(u,c,"error","log"),dn(u,c,"fatal","error"),dn(u,c,"warn","error"),dn(u,c,"info","log"),dn(u,c,"debug","log"),dn(u,c,"trace","log")}function p(d,g){if(!d)throw new Error("missing bindings for child Pino");g=g||{},i&&d.serializers&&(g.serializers=d.serializers);const y=g.serializers;if(i&&y){var _=Object.assign({},n,y),A=t.browser.serialize===!0?Object.keys(_):i;delete d.serializers,Qi([d],A,_,this._stdErrSerialize)}function m(v){this._childLevel=(v._childLevel|0)+1,this.error=pn(v,d,"error"),this.fatal=pn(v,d,"fatal"),this.warn=pn(v,d,"warn"),this.info=pn(v,d,"info"),this.debug=pn(v,d,"debug"),this.trace=pn(v,d,"trace"),_&&(this.serializers=_,this._serialize=A),e&&(this._logEvent=Io([].concat(v._logEvent.bindings,d)))}return m.prototype=this,new m(this)}return c}Nt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Nt.stdSerializers=Iy,Nt.stdTimeFunctions=Object.assign({},{nullTime:zu,epochTime:qu,unixTime:Py,isoTime:Cy});function dn(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?qn:i[r]?i[r]:zn[r]||zn[n]||qn,Dy(t,e,r)}function Dy(t,e,r){!t.transmit&&e[r]===qn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===zn?zn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Qi(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,$y(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Nt.levels.values[u],h=Nt.levels.values[r];if(h<l)return;Oy(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:Nt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function $y(t,e,r,n){t._serialize&&Qi(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=Nt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?Mu(i.shift(),i):void 0}else typeof s=="string"&&(s=Mu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function Qi(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=Nt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function pn(t,e,r){return function(){const n=new Array(1+arguments.length);n[0]=e;for(var i=1;i<n.length;i++)n[i]=arguments[i-1];return t[r].apply(this,n)}}function Oy(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Qi(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=r.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,n(s,t._logEvent,a),t._logEvent=Io(c)}function Io(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function By(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function Ty(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?zu:qu}function es(){return{}}function Ao(t){return t}function qn(){}function zu(){return!1}function qu(){return Date.now()}function Py(){return Math.round(Date.now()/1e3)}function Cy(){return new Date(Date.now()).toISOString()}function Ry(){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 Ny={level:"info"},jn="custom_context",Do=1e3*1024;class Uy{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}}class ju{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new Uy(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.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 r=this.head;for(;r!==null;)e.push(r.value),r=r.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 r=e.value;return e=e.next,{done:!1,value:r}}}}}class Vu{constructor(e,r=Do){this.level=e??"error",this.levelValue=Gt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new ju(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Gt.levels.values.error?console.error(e):r===Gt.levels.values.warn?console.warn(e):r===Gt.levels.values.debug?console.debug(e):r===Gt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(jr({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new ju(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(jr({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class Fy{constructor(e,r=Do){this.baseChunkLogger=new Vu(e,r)}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 r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}}class ky{constructor(e,r=Do){this.baseChunkLogger=new Vu(e,r)}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 Ly=Object.defineProperty,My=Object.defineProperties,zy=Object.getOwnPropertyDescriptors,Ku=Object.getOwnPropertySymbols,qy=Object.prototype.hasOwnProperty,jy=Object.prototype.propertyIsEnumerable,Hu=(t,e,r)=>e in t?Ly(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ts=(t,e)=>{for(var r in e||(e={}))qy.call(e,r)&&Hu(t,r,e[r]);if(Ku)for(var r of Ku(e))jy.call(e,r)&&Hu(t,r,e[r]);return t},rs=(t,e)=>My(t,zy(e));function $o(t){return rs(ts({},t),{level:t?.level||Ny.level})}function Vy(t,e=jn){return t[e]||""}function Ky(t,e,r=jn){return t[r]=e,t}function Ze(t,e=jn){let r="";return typeof t.bindings>"u"?r=Vy(t,e):r=t.bindings().context||"",r}function Hy(t,e,r=jn){const n=Ze(t,r);return n.trim()?`${n}/${e}`:e}function Ve(t,e,r=jn){const n=Hy(t,e,r),i=t.child({context:n});return Ky(i,n,r)}function Wy(t){var e,r;const n=new Fy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Gt(rs(ts({},t.opts),{level:"trace",browser:rs(ts({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function Gy(t){var e;const r=new ky((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Gt(rs(ts({},t.opts),{level:"trace"})),chunkLoggerController:r}}function Yy(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Wy(t):Gy(t)}var Zy=Object.defineProperty,Jy=(t,e,r)=>e in t?Zy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wu=(t,e,r)=>Jy(t,typeof e!="symbol"?e+"":e,r);class Xy extends Mr{constructor(e){super(),this.opts=e,Wu(this,"protocol","wc"),Wu(this,"version",2)}}var Qy=Object.defineProperty,e1=(t,e,r)=>e in t?Qy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,t1=(t,e,r)=>e1(t,typeof e!="symbol"?e+"":e,r);class r1 extends Mr{constructor(e,r){super(),this.core=e,this.logger=r,t1(this,"records",new Map)}}class n1{constructor(e,r){this.logger=e,this.core=r}}class i1 extends Mr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class s1 extends Mr{constructor(e){super()}}class o1{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}}class a1 extends Mr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class c1 extends Mr{constructor(e,r){super(),this.core=e,this.logger=r}}class u1{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}}class l1{constructor(e,r){this.projectId=e,this.logger=r}}class h1{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}}var f1=Object.defineProperty,d1=(t,e,r)=>e in t?f1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Gu=(t,e,r)=>d1(t,typeof e!="symbol"?e+"":e,r);class p1{constructor(e){this.opts=e,Gu(this,"protocol","wc"),Gu(this,"version",2)}}class g1{constructor(e){this.client=e}}function y1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yu(t,...e){if(!y1(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 Zu(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 w1(t,e){Yu(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const gn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oo=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function b1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Ju(t){return typeof t=="string"&&(t=b1(t)),Yu(t),t}class m1{clone(){return this._cloneInto()}}function v1(t){const e=n=>t().update(Ju(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Xu(t=32){if(gn&&typeof gn.getRandomValues=="function")return gn.getRandomValues(new Uint8Array(t));if(gn&&typeof gn.randomBytes=="function")return gn.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function E1(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}class x1 extends m1{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Oo(this.buffer)}update(e){Zu(this);const{view:r,buffer:n,blockLen:i}=this;e=Ju(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Oo(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Zu(this),w1(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)r[h]=0;E1(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Oo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%r&&e.buffer.set(n),e}}const ns=BigInt(2**32-1),Bo=BigInt(32);function Qu(t,e=!1){return e?{h:Number(t&ns),l:Number(t>>Bo&ns)}:{h:Number(t>>Bo&ns)|0,l:Number(t&ns)|0}}function _1(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=Qu(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const S1=(t,e)=>BigInt(t>>>0)<<Bo|BigInt(e>>>0),I1=(t,e,r)=>t>>>r,A1=(t,e,r)=>t<<32-r|e>>>r,D1=(t,e,r)=>t>>>r|e<<32-r,$1=(t,e,r)=>t<<32-r|e>>>r,O1=(t,e,r)=>t<<64-r|e>>>r-32,B1=(t,e,r)=>t>>>r-32|e<<64-r,T1=(t,e)=>e,P1=(t,e)=>t,C1=(t,e,r)=>t<<r|e>>>32-r,R1=(t,e,r)=>e<<r|t>>>32-r,N1=(t,e,r)=>e<<r-32|t>>>64-r,U1=(t,e,r)=>t<<r-32|e>>>64-r;function F1(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const k1=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),L1=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,M1=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),z1=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,q1=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),j1=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,Y={fromBig:Qu,split:_1,toBig:S1,shrSH:I1,shrSL:A1,rotrSH:D1,rotrSL:$1,rotrBH:O1,rotrBL:B1,rotr32H:T1,rotr32L:P1,rotlSH:C1,rotlSL:R1,rotlBH:N1,rotlBL:U1,add:F1,add3L:k1,add3H:L1,add4L:M1,add4H:z1,add5H:j1,add5L:q1},[V1,K1]=(()=>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))))(),lr=new Uint32Array(80),hr=new Uint32Array(80);class H1 extends x1{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:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,r){for(let m=0;m<16;m++,r+=4)lr[m]=e.getUint32(r),hr[m]=e.getUint32(r+=4);for(let m=16;m<80;m++){const v=lr[m-15]|0,x=hr[m-15]|0,B=Y.rotrSH(v,x,1)^Y.rotrSH(v,x,8)^Y.shrSH(v,x,7),R=Y.rotrSL(v,x,1)^Y.rotrSL(v,x,8)^Y.shrSL(v,x,7),C=lr[m-2]|0,b=hr[m-2]|0,T=Y.rotrSH(C,b,19)^Y.rotrBH(C,b,61)^Y.shrSH(C,b,6),I=Y.rotrSL(C,b,19)^Y.rotrBL(C,b,61)^Y.shrSL(C,b,6),$=Y.add4L(R,I,hr[m-7],hr[m-16]),P=Y.add4H($,B,T,lr[m-7],lr[m-16]);lr[m]=P|0,hr[m]=$|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let m=0;m<80;m++){const v=Y.rotrSH(h,f,14)^Y.rotrSH(h,f,18)^Y.rotrBH(h,f,41),x=Y.rotrSL(h,f,14)^Y.rotrSL(h,f,18)^Y.rotrBL(h,f,41),B=h&p^~h&g,R=f&d^~f&y,C=Y.add5L(A,x,R,K1[m],hr[m]),b=Y.add5H(C,_,v,B,V1[m],lr[m]),T=C|0,I=Y.rotrSH(n,i,28)^Y.rotrBH(n,i,34)^Y.rotrBH(n,i,39),$=Y.rotrSL(n,i,28)^Y.rotrBL(n,i,34)^Y.rotrBL(n,i,39),P=n&s^n&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(u|0,l|0,b|0,T|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const E=Y.add3L(T,$,F);n=Y.add3H(E,b,I,P),i=E|0}({h:n,l:i}=Y.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=Y.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Y.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Y.add(this.Eh|0,this.El|0,h|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:_,l:A}=Y.add(this.Hh|0,this.Hl|0,_|0,A|0),this.set(n,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){lr.fill(0),hr.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 W1=v1(()=>new H1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const To=BigInt(0),el=BigInt(1),G1=BigInt(2);function Po(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Co(t){if(!Po(t))throw new Error("Uint8Array expected")}function Ro(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Y1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function No(t){Co(t);let e="";for(let r=0;r<t.length;r++)e+=Y1[t[r]];return e}function tl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?To:BigInt("0x"+t)}const Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function rl(t){if(t>=Yt._0&&t<=Yt._9)return t-Yt._0;if(t>=Yt.A&&t<=Yt.F)return t-(Yt.A-10);if(t>=Yt.a&&t<=Yt.f)return t-(Yt.a-10)}function nl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=rl(t.charCodeAt(s)),a=rl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Z1(t){return tl(No(t))}function is(t){return Co(t),tl(No(Uint8Array.from(t).reverse()))}function il(t,e){return nl(t.toString(16).padStart(e*2,"0"))}function Uo(t,e){return il(t,e).reverse()}function Zt(t,e,r){let n;if(typeof e=="string")try{n=nl(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Po(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function sl(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Co(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}const Fo=t=>typeof t=="bigint"&&To<=t;function J1(t,e,r){return Fo(t)&&Fo(e)&&Fo(r)&&e<=t&&t<r}function Vn(t,e,r,n){if(!J1(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function X1(t){let e;for(e=0;t>To;t>>=el,e+=1);return e}const Q1=t=>(G1<<BigInt(t-1))-el,ew={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"||Po(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 ko(t,e,r={}){const n=(i,s,o)=>{const a=ew[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return t}function ol(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const _e=BigInt(0),de=BigInt(1),Vr=BigInt(2),tw=BigInt(3),Lo=BigInt(4),al=BigInt(5),cl=BigInt(8);function be(t,e){const r=t%e;return r>=_e?r:e+r}function rw(t,e,r){if(e<_e)throw new Error("invalid exponent, negatives unsupported");if(r<=_e)throw new Error("invalid modulus");if(r===de)return _e;let n=de;for(;e>_e;)e&de&&(n=n*t%r),t=t*t%r,e>>=de;return n}function Ut(t,e,r){let n=t;for(;e-- >_e;)n*=n,n%=r;return n}function ul(t,e){if(t===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let r=be(t,e),n=e,i=_e,s=de;for(;r!==_e;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==de)throw new Error("invert: does not exist");return be(i,e)}function nw(t){const e=(t-de)/Vr;let r,n,i;for(r=t-de,n=0;r%Vr===_e;r/=Vr,n++);for(i=Vr;i<t&&rw(i,e,t)!==t-de;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+de)/Lo;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 s=(r+de)/Vr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,i),r),l=o.pow(a,s),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,de<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function iw(t){if(t%Lo===tw){const e=(t+de)/Lo;return function(r,n){const i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%cl===al){const e=(t-al)/cl;return function(r,n){const i=r.mul(n,Vr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,Vr),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return nw(t)}const sw=(t,e)=>(be(t,e)&de)===de,ow=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function aw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=ow.reduce((n,i)=>(n[i]="function",n),e);return ko(t,r)}function cw(t,e,r){if(r<_e)throw new Error("invalid exponent, negatives unsupported");if(r===_e)return t.ONE;if(r===de)return e;let n=t.ONE,i=e;for(;r>_e;)r&de&&(n=t.mul(n,i)),i=t.sqr(i),r>>=de;return n}function uw(t,e){const r=new Array(e.length),n=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),i=t.inv(n);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),i),r}function ll(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function hl(t,e,r=!1,n={}){if(t<=_e)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=ll(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:i,BYTES:s,MASK:Q1(i),ZERO:_e,ONE:de,create:c=>be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _e<=c&&c<t},is0:c=>c===_e,isOdd:c=>(c&de)===de,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)=>cw(a,c,u),div:(c,u)=>be(c*ul(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ul(c,t),sqrt:n.sqrt||(c=>(o||(o=iw(t)),o(a,c))),invertBatch:c=>uw(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Uo(c,s):il(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?is(c):Z1(c)}});return Object.freeze(a)}const fl=BigInt(0),ss=BigInt(1);function Mo(t,e){const r=e.negate();return t?r:e}function dl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function zo(t,e){dl(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function lw(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function hw(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const qo=new WeakMap,pl=new WeakMap;function jo(t){return pl.get(t)||1}function fw(t,e){return{constTimeNegate:Mo,hasPrecomputes(r){return jo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>fl;)n&ss&&(i=i.add(s)),s=s.double(),n>>=ss;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=zo(n,e),o=[];let a=r,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){const{windows:s,windowSize:o}=zo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let f=0;f<s;f++){const p=f*o;let d=Number(i&u);i>>=h,d>o&&(d-=l,i+=ss);const g=p,y=p+Math.abs(d)-1,_=f%2!==0,A=d<0;d===0?c=c.add(Mo(_,n[g])):a=a.add(Mo(A,n[y]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=zo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(i===fl)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=ss),p===0)continue;let d=n[f+Math.abs(p)-1];p<0&&(d=d.negate()),s=s.add(d)}return s},getPrecomputes(r,n,i){let s=qo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&qo.set(n,i(s))),s},wNAFCached(r,n,i){const s=jo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=jo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){dl(n,e),pl.set(r,n),qo.delete(r)}}}function dw(t,e,r,n){if(lw(r,t),hw(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=X1(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let h=u;h>=0;h-=o){c.fill(i);for(let p=0;p<n.length;p++){const d=n[p],g=Number(d>>BigInt(h)&BigInt(a));c[g]=c[g].add(r[p])}let f=i;for(let p=c.length-1,d=i;p>0;p--)d=d.add(c[p]),f=f.add(d);if(l=l.add(f),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function pw(t){return aw(t.Fp),ko(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ll(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const $t=BigInt(0),Je=BigInt(1),os=BigInt(2),gw=BigInt(8),yw={zip215:!0};function ww(t){const e=pw(t);return ko(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function bw(t){const e=ww(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=os<<BigInt(a*8)-Je,l=r.create,h=hl(e.n,e.nBitLength),f=e.uvRatio||((E,w)=>{try{return{isValid:!0,value:r.sqrt(E*r.inv(w))}}catch{return{isValid:!1,value:$t}}}),p=e.adjustScalarBytes||(E=>E),d=e.domain||((E,w,S)=>{if(Ro("phflag",S),w.length||S)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){Vn("coordinate "+E,w,$t,u)}function y(E){if(!(E instanceof m))throw new Error("ExtendedPoint expected")}const _=ol((E,w)=>{const{ex:S,ey:O,ez:D}=E,N=E.is0();w==null&&(w=N?gw:r.inv(D));const U=l(S*w),L=l(O*w),j=l(D*w);if(N)return{x:$t,y:Je};if(j!==Je)throw new Error("invZ was invalid");return{x:U,y:L}}),A=ol(E=>{const{a:w,d:S}=e;if(E.is0())throw new Error("bad point: ZERO");const{ex:O,ey:D,ez:N,et:U}=E,L=l(O*O),j=l(D*D),V=l(N*N),K=l(V*V),H=l(L*w),Z=l(V*l(H+j)),Q=l(K+l(S*l(L*j)));if(Z!==Q)throw new Error("bad point: equation left != right (1)");const W=l(O*D),ae=l(N*U);if(W!==ae)throw new Error("bad point: equation left != right (2)");return!0});class m{constructor(w,S,O,D){this.ex=w,this.ey=S,this.ez=O,this.et=D,g("x",w),g("y",S),g("z",O),g("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof m)throw new Error("extended point not allowed");const{x:S,y:O}=w||{};return g("x",S),g("y",O),new m(S,O,Je,l(S*O))}static normalizeZ(w){const S=r.invertBatch(w.map(O=>O.ez));return w.map((O,D)=>O.toAffine(S[D])).map(m.fromAffine)}static msm(w,S){return dw(m,h,w,S)}_setWindowSize(w){B.setWindowSize(this,w)}assertValidity(){A(this)}equals(w){y(w);const{ex:S,ey:O,ez:D}=this,{ex:N,ey:U,ez:L}=w,j=l(S*L),V=l(N*D),K=l(O*L),H=l(U*D);return j===V&&K===H}is0(){return this.equals(m.ZERO)}negate(){return new m(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:S,ey:O,ez:D}=this,N=l(S*S),U=l(O*O),L=l(os*l(D*D)),j=l(w*N),V=S+O,K=l(l(V*V)-N-U),H=j+U,Z=H-L,Q=j-U,W=l(K*Z),ae=l(H*Q),ge=l(K*Q),dt=l(Z*H);return new m(W,ae,dt,ge)}add(w){y(w);const{a:S,d:O}=e,{ex:D,ey:N,ez:U,et:L}=this,{ex:j,ey:V,ez:K,et:H}=w;if(S===BigInt(-1)){const Xg=l((N-D)*(V+j)),Qg=l((N+D)*(V-j)),uu=l(Qg-Xg);if(uu===$t)return this.double();const e0=l(U*os*H),t0=l(L*os*K),r0=t0+e0,n0=Qg+Xg,i0=t0-e0,D5=l(r0*uu),$5=l(n0*i0),O5=l(r0*i0),B5=l(uu*n0);return new m(D5,$5,B5,O5)}const Z=l(D*j),Q=l(N*V),W=l(L*O*H),ae=l(U*K),ge=l((D+N)*(j+V)-Z-Q),dt=ae-W,At=ae+W,Dt=l(Q-S*Z),Wt=l(ge*dt),ho=l(At*Dt),I5=l(ge*Dt),A5=l(dt*At);return new m(Wt,ho,A5,I5)}subtract(w){return this.add(w.negate())}wNAF(w){return B.wNAFCached(this,w,m.normalizeZ)}multiply(w){const S=w;Vn("scalar",S,Je,n);const{p:O,f:D}=this.wNAF(S);return m.normalizeZ([O,D])[0]}multiplyUnsafe(w,S=m.ZERO){const O=w;return Vn("scalar",O,$t,n),O===$t?x:this.is0()||O===Je?this:B.wNAFCachedUnsafe(this,O,m.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return B.unsafeLadder(this,n).is0()}toAffine(w){return _(this,w)}clearCofactor(){const{h:w}=e;return w===Je?this:this.multiplyUnsafe(w)}static fromHex(w,S=!1){const{d:O,a:D}=e,N=r.BYTES;w=Zt("pointHex",w,N),Ro("zip215",S);const U=w.slice(),L=w[N-1];U[N-1]=L&-129;const j=is(U),V=S?u:r.ORDER;Vn("pointHex.y",j,$t,V);const K=l(j*j),H=l(K-Je),Z=l(O*K-D);let{isValid:Q,value:W}=f(H,Z);if(!Q)throw new Error("Point.fromHex: invalid y coordinate");const ae=(W&Je)===Je,ge=(L&128)!==0;if(!S&&W===$t&&ge)throw new Error("Point.fromHex: x=0 and x_0=1");return ge!==ae&&(W=l(-W)),m.fromAffine({x:W,y:j})}static fromPrivateKey(w){return b(w).point}toRawBytes(){const{x:w,y:S}=this.toAffine(),O=Uo(S,r.BYTES);return O[O.length-1]|=w&Je?128:0,O}toHex(){return No(this.toRawBytes())}}m.BASE=new m(e.Gx,e.Gy,Je,l(e.Gx*e.Gy)),m.ZERO=new m($t,Je,Je,$t);const{BASE:v,ZERO:x}=m,B=fw(m,a*8);function R(E){return be(E,n)}function C(E){return R(is(E))}function b(E){const w=r.BYTES;E=Zt("private key",E,w);const S=Zt("hashed private key",s(E),2*w),O=p(S.slice(0,w)),D=S.slice(w,2*w),N=C(O),U=v.multiply(N),L=U.toRawBytes();return{head:O,prefix:D,scalar:N,point:U,pointBytes:L}}function T(E){return b(E).pointBytes}function I(E=new Uint8Array,...w){const S=sl(...w);return C(s(d(S,Zt("context",E),!!i)))}function $(E,w,S={}){E=Zt("message",E),i&&(E=i(E));const{prefix:O,scalar:D,pointBytes:N}=b(w),U=I(S.context,O,E),L=v.multiply(U).toRawBytes(),j=I(S.context,L,N,E),V=R(U+j*D);Vn("signature.s",V,$t,n);const K=sl(L,Uo(V,r.BYTES));return Zt("result",K,r.BYTES*2)}const P=yw;function F(E,w,S,O=P){const{context:D,zip215:N}=O,U=r.BYTES;E=Zt("signature",E,2*U),w=Zt("message",w),S=Zt("publicKey",S,U),N!==void 0&&Ro("zip215",N),i&&(w=i(w));const L=is(E.slice(U,2*U));let j,V,K;try{j=m.fromHex(S,N),V=m.fromHex(E.slice(0,U),N),K=v.multiplyUnsafe(L)}catch{return!1}if(!N&&j.isSmallOrder())return!1;const H=I(D,V.toRawBytes(),j.toRawBytes(),w);return V.add(j.multiplyUnsafe(H)).subtract(K).clearCofactor().equals(m.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:T,sign:$,verify:F,ExtendedPoint:m,utils:{getExtendedPublicKey:b,randomPrivateKey:()=>o(r.BYTES),precompute(E=8,w=m.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const Vo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),gl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const mw=BigInt(1),yl=BigInt(2);BigInt(3);const vw=BigInt(5),Ew=BigInt(8);function xw(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Vo,o=t*t%s*t%s,a=Ut(o,yl,s)*o%s,c=Ut(a,mw,s)*t%s,u=Ut(c,vw,s)*c%s,l=Ut(u,e,s)*u%s,h=Ut(l,r,s)*l%s,f=Ut(h,n,s)*h%s,p=Ut(f,i,s)*f%s,d=Ut(p,i,s)*f%s,g=Ut(d,e,s)*u%s;return{pow_p_5_8:Ut(g,yl,s)*t%s,b2:o}}function _w(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Sw(t,e){const r=Vo,n=be(e*e*e,r),i=be(n*n*e,r),s=xw(t*i).pow_p_5_8;let o=be(t*n*s,r);const a=be(e*o*o,r),c=o,u=be(o*gl,r),l=a===t,h=a===be(-t,r),f=a===be(-t*gl,r);return l&&(o=c),(h||f)&&(o=u),sw(o,r)&&(o=be(-o,r)),{isValid:l||h,value:o}}const Iw=(()=>hl(Vo,void 0,!0))(),Aw=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Iw,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ew,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:W1,randomBytes:Xu,adjustScalarBytes:_w,uvRatio:Sw}))(),wl=(()=>bw(Aw))(),Dw="EdDSA",$w="JWT",as=".",cs="base64url",bl="utf8",ml="utf8",Ow=":",Bw="did",Tw="key",vl="base58btc",Pw="z",Cw="K36",Rw=32;function Ko(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function El(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ko(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function xl(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=El(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return Ko(r)}function Nw(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(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,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var m=(A-_)*l+1>>>0,v=new Uint8Array(m);_!==A;){for(var x=d[_],B=0,R=m-1;(x!==0||B<y)&&R!==-1;R--,B++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=B,_++}for(var C=m-y;C!==m&&v[C]===0;)C++;for(var b=c.repeat(g);C<m;++C)b+=t.charAt(v[C]);return b}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,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,m=new Uint8Array(A);d[g];){var v=r[d.charCodeAt(g)];if(v===255)return;for(var x=0,B=A-1;(v!==0||x<_)&&B!==-1;B--,x++)v+=a*m[B]>>>0,m[B]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&m[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),b=y;R!==A;)C[b++]=m[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var Uw=Nw,Fw=Uw;const _l=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")},kw=t=>new TextEncoder().encode(t),Lw=t=>new TextDecoder().decode(t);class Mw{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class zw{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 Sl(this,e)}}class qw{constructor(e){this.decoders=e}or(e){return Sl(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Sl=(t,e)=>new qw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class jw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new Mw(e,r,n),this.decoder=new zw(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const us=({name:t,prefix:e,encode:r,decode:n})=>new jw(t,e,r,n),Kn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Fw(r,e);return us({prefix:t,name:e,encode:n,decode:s=>_l(i(s))})},Vw=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Kw=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ae=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>us({prefix:e,name:t,encode(i){return Kw(i,n,r)},decode(i){return Vw(i,n,r,t)}}),Hw=us({prefix:"\0",name:"identity",encode:t=>Lw(t),decode:t=>kw(t)});var Ww=Object.freeze({__proto__:null,identity:Hw});const Gw=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Yw=Object.freeze({__proto__:null,base2:Gw});const Zw=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jw=Object.freeze({__proto__:null,base8:Zw});const Xw=Kn({prefix:"9",name:"base10",alphabet:"0123456789"});var Qw=Object.freeze({__proto__:null,base10:Xw});const eb=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),tb=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var rb=Object.freeze({__proto__:null,base16:eb,base16upper:tb});const nb=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ib=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),sb=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),ob=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),ab=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),cb=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ub=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lb=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),hb=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var fb=Object.freeze({__proto__:null,base32:nb,base32upper:ib,base32pad:sb,base32padupper:ob,base32hex:ab,base32hexupper:cb,base32hexpad:ub,base32hexpadupper:lb,base32z:hb});const db=Kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),pb=Kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var gb=Object.freeze({__proto__:null,base36:db,base36upper:pb});const yb=Kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),wb=Kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var bb=Object.freeze({__proto__:null,base58btc:yb,base58flickr:wb});const mb=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),vb=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Eb=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),xb=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var _b=Object.freeze({__proto__:null,base64:mb,base64pad:vb,base64url:Eb,base64urlpad:xb});const Il=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Sb=Il.reduce((t,e,r)=>(t[r]=e,t),[]),Ib=Il.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Ab(t){return t.reduce((e,r)=>(e+=Sb[r],e),"")}function Db(t){const e=[];for(const r of t){const n=Ib[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const $b=us({prefix:"\u{1F680}",name:"base256emoji",encode:Ab,decode:Db});var Ob=Object.freeze({__proto__:null,base256emoji:$b}),Bb=Dl,Al=128,Tb=127,Pb=~Tb,Cb=Math.pow(2,31);function Dl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Cb;)e[r++]=t&255|Al,t/=128;for(;t&Pb;)e[r++]=t&255|Al,t>>>=7;return e[r]=t|0,Dl.bytes=r-n+1,e}var Rb=Ho,Nb=128,$l=127;function Ho(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Ho.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&$l)<<i:(o&$l)*Math.pow(2,i),i+=7}while(o>=Nb);return Ho.bytes=s-n,r}var Ub=Math.pow(2,7),Fb=Math.pow(2,14),kb=Math.pow(2,21),Lb=Math.pow(2,28),Mb=Math.pow(2,35),zb=Math.pow(2,42),qb=Math.pow(2,49),jb=Math.pow(2,56),Vb=Math.pow(2,63),Kb=function(t){return t<Ub?1:t<Fb?2:t<kb?3:t<Lb?4:t<Mb?5:t<zb?6:t<qb?7:t<jb?8:t<Vb?9:10},Hb={encode:Bb,decode:Rb,encodingLength:Kb},Ol=Hb;const Bl=(t,e,r=0)=>(Ol.encode(t,e,r),e),Tl=t=>Ol.encodingLength(t),Wo=(t,e)=>{const r=e.byteLength,n=Tl(t),i=n+Tl(r),s=new Uint8Array(i+r);return Bl(t,s,0),Bl(r,s,n),s.set(e,i),new Wb(t,r,e,s)};class Wb{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Pl=({name:t,code:e,encode:r})=>new Gb(t,e,r);class Gb{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Wo(this.code,r):r.then(n=>Wo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Cl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Yb=Pl({name:"sha2-256",code:18,encode:Cl("SHA-256")}),Zb=Pl({name:"sha2-512",code:19,encode:Cl("SHA-512")});var Jb=Object.freeze({__proto__:null,sha256:Yb,sha512:Zb});const Rl=0,Xb="identity",Nl=_l;var Qb=Object.freeze({__proto__:null,identity:{code:Rl,name:Xb,encode:Nl,digest:t=>Wo(Rl,Nl(t))}});new TextEncoder,new TextDecoder;const Ul={...Ww,...Yw,...Jw,...Qw,...rb,...fb,...gb,...bb,..._b,...Ob};({...Jb,...Qb});function Fl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const kl=Fl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Go=Fl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=El(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ll={utf8:kl,"utf-8":kl,hex:Ul.base16,latin1:Go,ascii:Go,binary:Go,...Ul};function ls(t,e="utf8"){const r=Ll[e];if(!r)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"):r.encoder.encode(t).substring(1)}function yn(t,e="utf8"){const r=Ll[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ko(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Ml(t){return fn(ls(yn(t,cs),bl))}function hs(t){return ls(yn(jr(t),bl),cs)}function zl(t){const e=yn(Cw,vl),r=Pw+ls(xl([e,t]),vl);return[Bw,Tw,r].join(Ow)}function em(t){return ls(t,cs)}function tm(t){return yn(t,cs)}function rm(t){return yn([hs(t.header),hs(t.payload)].join(as),ml)}function nm(t){return[hs(t.header),hs(t.payload),em(t.signature)].join(as)}function Yo(t){const e=t.split(as),r=Ml(e[0]),n=Ml(e[1]),i=tm(e[2]),s=yn(e.slice(0,2).join(as),ml);return{header:r,payload:n,signature:i,data:s}}function ql(t=Xu(Rw)){const e=wl.getPublicKey(t);return{secretKey:xl([t,e]),publicKey:e}}async function im(t,e,r,n,i=M.fromMiliseconds(Date.now())){const s={alg:Dw,typ:$w},o=zl(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=rm({header:s,payload:c}),l=wl.sign(u,n.secretKey.slice(0,32));return nm({header:s,payload:c,signature:l})}var jl=function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},sm=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),om=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),am=function(){function t(e,r,n,i){this.name=e,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return t}(),cm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),um=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),lm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,hm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Vl=3,fm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",lm]],Kl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function dm(t){return t?Hl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new um:typeof navigator<"u"?Hl(navigator.userAgent):ym()}function pm(t){return t!==""&&fm.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function Hl(t){var e=pm(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new cm;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<Vl&&(i=jl(jl([],i,!0),wm(Vl-i.length),!0)):i=[];var s=i.join("."),o=gm(t),a=hm.exec(t);return a&&a[1]?new am(r,s,o,a[1]):new sm(r,s,o)}function gm(t){for(var e=0,r=Kl.length;e<r;e++){var n=Kl[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function ym(){var t=typeof process<"u"&&process.version;return t?new om(process.version.slice(1)):null}function wm(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var ue={};Object.defineProperty(ue,"__esModule",{value:!0}),ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=Wl=ue.getLocation=ue.getLocationOrThrow=Zo=ue.getNavigator=ue.getNavigatorOrThrow=Hr=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function Kr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=Kr;function wn(t){const e=Kr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=wn;function bm(){return wn("document")}ue.getDocumentOrThrow=bm;function mm(){return Kr("document")}var Hr=ue.getDocument=mm;function vm(){return wn("navigator")}ue.getNavigatorOrThrow=vm;function Em(){return Kr("navigator")}var Zo=ue.getNavigator=Em;function xm(){return wn("location")}ue.getLocationOrThrow=xm;function _m(){return Kr("location")}var Wl=ue.getLocation=_m;function Sm(){return wn("crypto")}ue.getCryptoOrThrow=Sm;function Im(){return Kr("crypto")}ue.getCrypto=Im;function Am(){return wn("localStorage")}ue.getLocalStorageOrThrow=Am;function Dm(){return Kr("localStorage")}ue.getLocalStorage=Dm;var Jo={};Object.defineProperty(Jo,"__esModule",{value:!0});var Gl=Jo.getWindowMetadata=void 0;const Yl=ue;function $m(){let t,e;try{t=Yl.getDocumentOrThrow(),e=Yl.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),f=[];for(let p=0;p<h.length;p++){const d=h[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.protocol+"//"+e.host;if(y.indexOf("/")===0)_+=y;else{const A=e.pathname.split("/");A.pop();const m=A.join("/");_+=m+"/"+y}f.push(_)}else if(y.indexOf("//")===0){const _=e.protocol+y;f.push(_)}else f.push(y)}}return f}function n(...h){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?h.includes(y):!1);if(g.length&&g){const y=d.getAttribute("content");if(y)return y}}return""}function i(){let h=n("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}Gl=Jo.getWindowMetadata=$m;function Hn(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Xo(t){return Hn(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Zl="2.31.0";let Qo={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Zl}`};class Wr extends Error{constructor(e,r={}){const n=(()=>r.cause instanceof Wr?r.cause.details:r.cause?.message?r.cause.message:r.details)(),i=(()=>r.cause instanceof Wr&&r.cause.docsPath||r.docsPath)(),s=Qo.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Qo.version?[`Version: ${Qo.version}`]:[]].join(`
15
- `);super(o,r.cause?{cause:r.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=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=Zl}walk(e){return Jl(this,e)}}function Jl(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Jl(t.cause,e):e?null:t}class Xl extends Wr{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function bn(t,{dir:e,size:r=32}={}){return typeof t=="string"?Om(t,{dir:e,size:r}):Bm(t,{dir:e,size:r})}function Om(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new Xl({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function Bm(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new Xl({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=e==="right";n[s?i:r-i-1]=t[s?i:t.length-i-1]}return n}class Tm extends Wr{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class Pm extends Wr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function mn(t,{size:e}){if(Xo(t)>e)throw new Pm({givenSize:Xo(t),maxSize:e})}function ea(t,e={}){const{signed:r}=e;e.size&&mn(t,{size:e.size});const n=BigInt(t);if(!r)return n;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function Cm(t,e={}){return Number(ea(t,e))}const Rm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ta(t,e={}){return typeof t=="number"||typeof t=="bigint"?ra(t,e):typeof t=="string"?Fm(t,e):typeof t=="boolean"?Nm(t,e):Ql(t,e)}function Nm(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(mn(r,{size:e.size}),bn(r,{size:e.size})):r}function Ql(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=Rm[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(mn(n,{size:e.size}),bn(n,{dir:"right",size:e.size})):n}function ra(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new Tm({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?bn(a,{size:n}):a}const Um=new TextEncoder;function Fm(t,e={}){const r=Um.encode(t);return Ql(r,e)}const km=new TextEncoder;function Lm(t,e={}){return typeof t=="number"||typeof t=="bigint"?zm(t,e):typeof t=="boolean"?Mm(t,e):Hn(t)?th(t,e):rh(t,e)}function Mm(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(mn(r,{size:e.size}),bn(r,{size:e.size})):r}const Jt={zero:48,nine:57,A:65,F:70,a:97,f:102};function eh(t){if(t>=Jt.zero&&t<=Jt.nine)return t-Jt.zero;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function th(t,e={}){let r=t;e.size&&(mn(r,{size:e.size}),r=bn(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=eh(n.charCodeAt(a++)),u=eh(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new Wr(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+u}return s}function zm(t,e){const r=ra(t,e);return th(r)}function rh(t,e={}){const r=km.encode(t);return typeof e.size=="number"?(mn(r,{size:e.size}),bn(r,{dir:"right",size:e.size})):r}const fs=BigInt(2**32-1),nh=BigInt(32);function qm(t,e=!1){return e?{h:Number(t&fs),l:Number(t>>nh&fs)}:{h:Number(t>>nh&fs)|0,l:Number(t&fs)|0}}function jm(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=qm(t[s],e);[n[s],i[s]]=[o,a]}return[n,i]}const Vm=(t,e,r)=>t<<r|e>>>32-r,Km=(t,e,r)=>e<<r|t>>>32-r,Hm=(t,e,r)=>e<<r-32|t>>>64-r,Wm=(t,e,r)=>t<<r-32|e>>>64-r,vn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Gm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Gr(t,...e){if(!Gm(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 Ym(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Wn(t.outputLen),Wn(t.blockLen)}function En(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 ih(t,e){Gr(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Zm(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function xn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function na(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ft(t,e){return t<<32-e|t>>>e}const Jm=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Xm(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Qm(t){for(let e=0;e<t.length;e++)t[e]=Xm(t[e]);return t}const sh=Jm?t=>t:Qm;function e2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ds(t){return typeof t=="string"&&(t=e2(t)),Gr(t),t}function t2(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Gr(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class ia{}function oh(t){const e=n=>t().update(ds(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ah(t=32){if(vn&&typeof vn.getRandomValues=="function")return vn.getRandomValues(new Uint8Array(t));if(vn&&typeof vn.randomBytes=="function")return Uint8Array.from(vn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const r2=BigInt(0),Gn=BigInt(1),n2=BigInt(2),i2=BigInt(7),s2=BigInt(256),o2=BigInt(113),ch=[],uh=[],lh=[];for(let t=0,e=Gn,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],ch.push(2*(5*n+r)),uh.push((t+1)*(t+2)/2%64);let i=r2;for(let s=0;s<7;s++)e=(e<<Gn^(e>>i2)*o2)%s2,e&n2&&(i^=Gn<<(Gn<<BigInt(s))-Gn);lh.push(i)}const hh=jm(lh,!0),a2=hh[0],c2=hh[1],fh=(t,e,r)=>r>32?Hm(t,e,r):Vm(t,e,r),dh=(t,e,r)=>r>32?Wm(t,e,r):Km(t,e,r);function u2(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[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=r[c],l=r[c+1],h=fh(u,l,1)^r[a],f=dh(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=uh[o],c=fh(i,s,a),u=dh(i,s,a),l=ch[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=a2[n],t[1]^=c2[n]}xn(r)}class sa extends ia{constructor(e,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,Wn(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Zm(this.state)}clone(){return this._cloneInto()}keccak(){sh(this.state32),u2(this.state32,this.rounds),sh(this.state32),this.posOut=0,this.pos=0}update(e){En(this),e=ds(e),Gr(e);const{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){En(this,!1),Gr(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=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 Wn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ih(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,xn(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new sa(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const l2=(t,e,r)=>oh(()=>new sa(e,t,r)),ph=(()=>l2(1,136,256/8))();function gh(t,e){const r=e||"hex",n=ph(Hn(t,{strict:!1})?Lm(t):t);return r==="bytes"?n:ta(n)}class yh extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const oa=new yh(8192);function h2(t,e){if(oa.has(`${t}.${e}`))return oa.get(`${t}.${e}`);const r=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),n=gh(rh(r),"bytes"),i=(e?r.substring(`${e}0x`.length):r).split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return oa.set(`${t}.${e}`,s),s}function f2(t){const e=gh(`0x${t.substring(4)}`).substring(26);return h2(`0x${e}`)}async function d2({hash:t,signature:e}){const r=Hn(t)?t:ta(t),{secp256k1:n}=await Promise.resolve().then(function(){return Nv});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:f}=e,p=Number(f??h),d=wh(p);return new n.Signature(ea(u),ea(l)).addRecoveryBit(d)}const o=Hn(e)?e:ta(e);if(Xo(o)!==65)throw new Error("invalid signature length");const a=Cm(`0x${o.slice(130)}`),c=wh(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function wh(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 p2({hash:t,signature:e}){return f2(await d2({hash:t,signature:e}))}function g2(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function y2(t,e,r){return t&e^~t&r}function w2(t,e,r){return t&e^t&r^e&r}class b2 extends ia{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=na(this.buffer)}update(e){En(this),e=ds(e),Gr(e);const{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=na(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){En(this),ih(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,xn(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)r[h]=0;g2(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=na(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const fr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),m2=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]),dr=new Uint32Array(64);class v2 extends b2{constructor(e=32){super(64,e,8,!1),this.A=fr[0]|0,this.B=fr[1]|0,this.C=fr[2]|0,this.D=fr[3]|0,this.E=fr[4]|0,this.F=fr[5]|0,this.G=fr[6]|0,this.H=fr[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)dr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=dr[h-15],p=dr[h-2],d=Ft(f,7)^Ft(f,18)^f>>>3,g=Ft(p,17)^Ft(p,19)^p>>>10;dr[h]=g+dr[h-7]+d+dr[h-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Ft(a,6)^Ft(a,11)^Ft(a,25),p=l+f+y2(a,c,u)+m2[h]+dr[h]|0,g=(Ft(n,2)^Ft(n,13)^Ft(n,22))+w2(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+g|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){xn(dr)}destroy(){this.set(0,0,0,0,0,0,0,0),xn(this.buffer)}}const ps=oh(()=>new v2),E2="0.1.1";function x2(){return E2}class Ke extends Error{constructor(e,r={}){const n=(()=>{if(r.cause instanceof Ke){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),i=(()=>r.cause instanceof Ke&&r.cause.docsPath||r.docsPath)(),o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
- `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{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,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${x2()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return bh(this,e)}}function bh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?bh(t.cause,e):e?null:t}function _2(t,e){if(Eh(t)>e)throw new T2({givenSize:Eh(t),maxSize:e})}const Xt={zero:48,nine:57,A:65,F:70,a:97,f:102};function mh(t){if(t>=Xt.zero&&t<=Xt.nine)return t-Xt.zero;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function S2(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new P2({size:t.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=t[o?s:t.length-s-1]}return i}function aa(t,e){if(ua(t)>e)throw new L2({givenSize:ua(t),maxSize:e})}function vh(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const i=t.replace("0x","");if(i.length>n*2)throw new M2({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const I2=new TextEncoder;function A2(t){return t instanceof Uint8Array?t:typeof t=="string"?$2(t):D2(t)}function D2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function $2(t,e={}){const{size:r}=e;let n=t;r&&(aa(t,r),n=ca(t,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=mh(i.charCodeAt(c++)),l=mh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new Ke(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function O2(t,e={}){const{size:r}=e,n=I2.encode(t);return typeof r=="number"?(_2(n,r),B2(n,r)):n}function B2(t,e){return S2(t,{dir:"right",size:e})}function Eh(t){return t.length}class T2 extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class P2 extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const C2=new TextEncoder,R2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function xh(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function N2(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(aa(r,e.size),gs(r,e.size)):r}function _h(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=R2[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(aa(n,e.size),ca(n,e.size)):n}function U2(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new k2({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?gs(c,n):c}function F2(t,e={}){return _h(C2.encode(t),e)}function gs(t,e){return vh(t,{dir:"left",size:e})}function ca(t,e){return vh(t,{dir:"right",size:e})}function ua(t){return Math.ceil((t.length-2)/2)}class k2 extends Ke{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class L2 extends Ke{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class M2 extends Ke{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new yh(128),ra(0,{size:32});function z2(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=ph(A2(t));return r==="Bytes"?n:_h(n)}class q2 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const la={checksum:new q2(8192)}.checksum,j2=/^0x[a-fA-F0-9]{40}$/;function Sh(t,e={}){const{strict:r=!0}=e;if(!j2.test(t))throw new Ih({address:t,cause:new K2});if(r){if(t.toLowerCase()===t)return;if(V2(t)!==t)throw new Ih({address:t,cause:new H2})}}function V2(t){if(la.has(t))return la.get(t);Sh(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=z2(O2(e),{as:"Bytes"}),n=e.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return la.set(t,i),i}class Ih extends Ke{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class K2 extends Ke{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class H2 extends Ke{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const W2=/^(.*)\[([0-9]*)\]$/,G2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,Y2=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function ha(t,e){if(t.length!==e.length)throw new J2({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const i=t[n],s=e[n];r.push(ha.encode(i,s))}return xh(...r)}(function(t){function e(r,n,i=!1){if(r==="address"){const c=n;return Sh(c),gs(c.toLowerCase(),i?32:0)}if(r==="string")return F2(n);if(r==="bytes")return n;if(r==="bool")return gs(N2(n),i?32:1);const s=r.match(Y2);if(s){const[c,u,l="256"]=s,h=Number.parseInt(l)/8;return U2(n,{size:i?32:h,signed:u==="int"})}const o=r.match(G2);if(o){const[c,u]=o;if(Number.parseInt(u)!==(n.length-2)/2)throw new Z2({expectedSize:Number.parseInt(u),value:n});return ca(n,i?32:0)}const a=r.match(W2);if(a&&Array.isArray(n)){const[c,u]=a,l=[];for(let h=0;h<n.length;h++)l.push(e(u,n[h],!0));return l.length===0?"0x":xh(...l)}throw new X2(r)}t.encode=e})(ha||(ha={}));class Z2 extends Ke{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${ua(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class J2 extends Ke{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
17
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class X2 extends Ke{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Ah extends ia{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Ym(e);const n=ds(r);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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),xn(s)}update(e){return En(this),this.iHash.update(e),this}digestInto(e){En(this),Gr(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:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Dh=(t,e,r)=>new Ah(t,e).update(r).digest();Dh.create=(t,e)=>new Ah(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fa=BigInt(0),da=BigInt(1);function Yn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function pr(t){if(!Yn(t))throw new Error("Uint8Array expected")}function Zn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function ys(t){const e=t.toString(16);return e.length&1?"0"+e:e}function $h(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?fa:BigInt("0x"+t)}const Oh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Q2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jn(t){if(pr(t),Oh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=Q2[t[r]];return e}const Qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bh(t){if(t>=Qt._0&&t<=Qt._9)return t-Qt._0;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function ws(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Oh)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=Bh(t.charCodeAt(s)),a=Bh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function kt(t){return $h(Jn(t))}function Th(t){return pr(t),$h(Jn(Uint8Array.from(t).reverse()))}function Yr(t,e){return ws(t.toString(16).padStart(e*2,"0"))}function Ph(t,e){return Yr(t,e).reverse()}function De(t,e,r){let n;if(typeof e=="string")try{n=ws(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Yn(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function pt(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];pr(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}function pa(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const ga=t=>typeof t=="bigint"&&fa<=t;function Xn(t,e,r){return ga(t)&&ga(e)&&ga(r)&&e<=t&&t<r}function Zr(t,e,r,n){if(!Xn(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function ev(t){let e;for(e=0;t>fa;t>>=da,e+=1);return e}const bs=t=>(da<<BigInt(t))-da,ya=t=>new Uint8Array(t),Ch=t=>Uint8Array.from(t);function tv(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");let n=ya(t),i=ya(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...h)=>r(i,n,...h),c=(h=ya(0))=>{i=a(Ch([0]),h),n=a(),h.length!==0&&(i=a(Ch([1]),h),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){n=a();const p=n.slice();f.push(p),h+=n.length}return pt(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(u()));)c();return o(),p}}const rv={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"||Yn(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 Qn(t,e,r={}){const n=(i,s,o)=>{const a=rv[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return t}function Rh(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const Xe=BigInt(0),He=BigInt(1),Jr=BigInt(2),nv=BigInt(3),Nh=BigInt(4),Uh=BigInt(5),Fh=BigInt(8);function Se(t,e){const r=t%e;return r>=Xe?r:e+r}function gt(t,e,r){let n=t;for(;e-- >Xe;)n*=n,n%=r;return n}function wa(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 r=Se(t,e),n=e,i=Xe,s=He;for(;r!==Xe;){const a=n/r,c=n%r,u=i-s*a;n=r,r=c,i=s,s=u}if(n!==He)throw new Error("invert: does not exist");return Se(i,e)}function kh(t,e){const r=(t.ORDER+He)/Nh,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function iv(t,e){const r=(t.ORDER-Uh)/Fh,n=t.mul(e,Jr),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,Jr),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function sv(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-He,r=0;for(;e%Jr===Xe;)e/=Jr,r++;let n=Jr;const i=ba(t);for(;Mh(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return kh;let s=i.pow(n,e);const o=(e+He)/Jr;return function(c,u){if(c.is0(u))return u;if(Mh(c,u)!==1)throw new Error("Cannot find square root");let l=r,h=c.mul(c.ONE,s),f=c.pow(u,e),p=c.pow(u,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,g=c.sqr(f);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");const y=He<<BigInt(l-d-1),_=c.pow(h,y);l=d,h=c.sqr(_),f=c.mul(f,h),p=c.mul(p,_)}return p}}function ov(t){return t%Nh===nv?kh:t%Fh===Uh?iv:sv(t)}const av=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lh(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=av.reduce((n,i)=>(n[i]="function",n),e);return Qn(t,r)}function cv(t,e,r){if(r<Xe)throw new Error("invalid exponent, negatives unsupported");if(r===Xe)return t.ONE;if(r===He)return e;let n=t.ONE,i=e;for(;r>Xe;)r&He&&(n=t.mul(n,i)),i=t.sqr(i),r>>=He;return n}function ms(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),s),n}function Mh(t,e){const r=(t.ORDER-He)/Jr,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function zh(t,e){e!==void 0&&Wn(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function ba(t,e,r=!1,n={}){if(t<=Xe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=zh(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:i,BYTES:s,MASK:bs(i),ZERO:Xe,ONE:He,create:c=>Se(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&He)===He,neg:c=>Se(-c,t),eql:(c,u)=>c===u,sqr:c=>Se(c*c,t),add:(c,u)=>Se(c+u,t),sub:(c,u)=>Se(c-u,t),mul:(c,u)=>Se(c*u,t),pow:(c,u)=>cv(a,c,u),div:(c,u)=>Se(c*wa(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>wa(c,t),sqrt:n.sqrt||(c=>(o||(o=ov(t)),o(a,c))),toBytes:c=>r?Ph(c,s):Yr(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Th(c):kt(c)},invertBatch:c=>ms(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function qh(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 jh(t){const e=qh(t);return e+Math.ceil(e/2)}function uv(t,e,r=!1){const n=t.length,i=qh(e),s=jh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Th(t):kt(t),a=Se(o,e-He)+He;return r?Ph(a,i):Yr(a,i)}const Vh=BigInt(0),ma=BigInt(1);function va(t,e){const r=e.negate();return t?r:e}function Kh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ea(t,e){Kh(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,s=bs(t),o=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function Hh(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),c=t>>o;a>n&&(a-=s,c+=ma);const u=e*n,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function lv(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function hv(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const xa=new WeakMap,Wh=new WeakMap;function _a(t){return Wh.get(t)||1}function fv(t,e){return{constTimeNegate:va,hasPrecomputes(r){return _a(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>Vh;)n&ma&&(i=i.add(s)),s=s.double(),n>>=ma;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Ea(n,e),o=[];let a=r,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){let s=t.ZERO,o=t.BASE;const a=Ea(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=Hh(i,c,a);i=u,h?o=o.add(va(p,n[d])):s=s.add(va(f,n[l]))}return{p:s,f:o}},wNAFUnsafe(r,n,i,s=t.ZERO){const o=Ea(r,e);for(let a=0;a<o.windows&&i!==Vh;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=Hh(i,a,o);if(i=c,!l){const f=n[u];s=s.add(h?f.negate():f)}}return s},getPrecomputes(r,n,i){let s=xa.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&xa.set(n,i(s))),s},wNAFCached(r,n,i){const s=_a(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=_a(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Kh(n,e),Wh.set(r,n),xa.delete(r)}}}function dv(t,e,r,n){lv(r,t),hv(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=ev(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=bs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=n[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(r[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[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 Gh(t){return Lh(t.Fp),Qn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...zh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Yh(t){t.lowS!==void 0&&Zn("lowS",t.lowS),t.prehash!==void 0&&Zn("prehash",t.prehash)}function pv(t){const e=Gh(t);Qn(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class gv extends Error{constructor(e=""){super(e)}}const er={Err:gv,_tlv:{encode:(t,e)=>{const{Err:r}=er;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=ys(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?ys(i.length/2|128):"";return ys(t)+s+i+e},decode(t,e){const{Err:r}=er;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=er;if(t<Ot)throw new e("integer: negative integers are not allowed");let r=ys(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=er;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 kt(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=er,i=De("signature",t),{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=er,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}};function Sa(t,e){return Jn(Yr(t,e))}const Ot=BigInt(0),oe=BigInt(1),gr=BigInt(2),ei=BigInt(3),Ia=BigInt(4);function yv(t){const e=pv(t),{Fp:r}=e,n=ba(e.n,e.nBitLength),i=e.toBytes||((m,v,x)=>{const B=v.toAffine();return pt(Uint8Array.from([4]),r.toBytes(B.x),r.toBytes(B.y))}),s=e.fromBytes||(m=>{const v=m.subarray(1),x=r.fromBytes(v.subarray(0,r.BYTES)),B=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x,y:B}});function o(m){const{a:v,b:x}=e,B=r.sqr(m),R=r.mul(B,m);return r.add(r.add(R,r.mul(m,v)),x)}function a(m,v){const x=r.sqr(v),B=o(m);return r.eql(x,B)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,ei),Ia),u=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,u)))throw new Error("bad curve params: a or b");function l(m){return Xn(m,oe,e.n)}function h(m){const{allowedPrivateKeyLengths:v,nByteLength:x,wrapPrivateKey:B,n:R}=e;if(v&&typeof m!="bigint"){if(Yn(m)&&(m=Jn(m)),typeof m!="string"||!v.includes(m.length))throw new Error("invalid private key");m=m.padStart(x*2,"0")}let C;try{C=typeof m=="bigint"?m:kt(De("private key",m,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof m)}return B&&(C=Se(C,R)),Zr("private key",C,oe,R),C}function f(m){if(!(m instanceof g))throw new Error("ProjectivePoint expected")}const p=Rh((m,v)=>{const{px:x,py:B,pz:R}=m;if(r.eql(R,r.ONE))return{x,y:B};const C=m.is0();v==null&&(v=C?r.ONE:r.inv(R));const b=r.mul(x,v),T=r.mul(B,v),I=r.mul(R,v);if(C)return{x:r.ZERO,y:r.ZERO};if(!r.eql(I,r.ONE))throw new Error("invZ was invalid");return{x:b,y:T}}),d=Rh(m=>{if(m.is0()){if(e.allowInfinityPoint&&!r.is0(m.py))return;throw new Error("bad point: ZERO")}const{x:v,y:x}=m.toAffine();if(!r.isValid(v)||!r.isValid(x))throw new Error("bad point: x or y not FE");if(!a(v,x))throw new Error("bad point: equation left != right");if(!m.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,x,B){if(v==null||!r.isValid(v))throw new Error("x required");if(x==null||!r.isValid(x)||r.is0(x))throw new Error("y required");if(B==null||!r.isValid(B))throw new Error("z required");this.px=v,this.py=x,this.pz=B,Object.freeze(this)}static fromAffine(v){const{x,y:B}=v||{};if(!v||!r.isValid(x)||!r.isValid(B))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const R=C=>r.eql(C,r.ZERO);return R(x)&&R(B)?g.ZERO:new g(x,B,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const x=ms(r,v.map(B=>B.pz));return v.map((B,R)=>B.toAffine(x[R])).map(g.fromAffine)}static fromHex(v){const x=g.fromAffine(s(De("pointHex",v)));return x.assertValidity(),x}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,x){return dv(g,n,v,x)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){d(this)}hasEvenY(){const{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:x,py:B,pz:R}=this,{px:C,py:b,pz:T}=v,I=r.eql(r.mul(x,T),r.mul(C,R)),$=r.eql(r.mul(B,T),r.mul(b,R));return I&&$}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:v,b:x}=e,B=r.mul(x,ei),{px:R,py:C,pz:b}=this;let T=r.ZERO,I=r.ZERO,$=r.ZERO,P=r.mul(R,R),F=r.mul(C,C),E=r.mul(b,b),w=r.mul(R,C);return w=r.add(w,w),$=r.mul(R,b),$=r.add($,$),T=r.mul(v,$),I=r.mul(B,E),I=r.add(T,I),T=r.sub(F,I),I=r.add(F,I),I=r.mul(T,I),T=r.mul(w,T),$=r.mul(B,$),E=r.mul(v,E),w=r.sub(P,E),w=r.mul(v,w),w=r.add(w,$),$=r.add(P,P),P=r.add($,P),P=r.add(P,E),P=r.mul(P,w),I=r.add(I,P),E=r.mul(C,b),E=r.add(E,E),P=r.mul(E,w),T=r.sub(T,P),$=r.mul(E,F),$=r.add($,$),$=r.add($,$),new g(T,I,$)}add(v){f(v);const{px:x,py:B,pz:R}=this,{px:C,py:b,pz:T}=v;let I=r.ZERO,$=r.ZERO,P=r.ZERO;const F=e.a,E=r.mul(e.b,ei);let w=r.mul(x,C),S=r.mul(B,b),O=r.mul(R,T),D=r.add(x,B),N=r.add(C,b);D=r.mul(D,N),N=r.add(w,S),D=r.sub(D,N),N=r.add(x,R);let U=r.add(C,T);return N=r.mul(N,U),U=r.add(w,O),N=r.sub(N,U),U=r.add(B,R),I=r.add(b,T),U=r.mul(U,I),I=r.add(S,O),U=r.sub(U,I),P=r.mul(F,N),I=r.mul(E,O),P=r.add(I,P),I=r.sub(S,P),P=r.add(S,P),$=r.mul(I,P),S=r.add(w,w),S=r.add(S,w),O=r.mul(F,O),N=r.mul(E,N),S=r.add(S,O),O=r.sub(w,O),O=r.mul(F,O),N=r.add(N,O),w=r.mul(S,N),$=r.add($,w),w=r.mul(U,N),I=r.mul(D,I),I=r.sub(I,w),w=r.mul(D,S),P=r.mul(U,P),P=r.add(P,w),new g(I,$,P)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return A.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:x,n:B}=e;Zr("scalar",v,Ot,B);const R=g.ZERO;if(v===Ot)return R;if(this.is0()||v===oe)return this;if(!x||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:C,k1:b,k2neg:T,k2:I}=x.splitScalar(v),$=R,P=R,F=this;for(;b>Ot||I>Ot;)b&oe&&($=$.add(F)),I&oe&&(P=P.add(F)),F=F.double(),b>>=oe,I>>=oe;return C&&($=$.negate()),T&&(P=P.negate()),P=new g(r.mul(P.px,x.beta),P.py,P.pz),$.add(P)}multiply(v){const{endo:x,n:B}=e;Zr("scalar",v,oe,B);let R,C;if(x){const{k1neg:b,k1:T,k2neg:I,k2:$}=x.splitScalar(v);let{p:P,f:F}=this.wNAF(T),{p:E,f:w}=this.wNAF($);P=A.constTimeNegate(b,P),E=A.constTimeNegate(I,E),E=new g(r.mul(E.px,x.beta),E.py,E.pz),R=P.add(E),C=F.add(w)}else{const{p:b,f:T}=this.wNAF(v);R=b,C=T}return g.normalizeZ([R,C])[0]}multiplyAndAddUnsafe(v,x,B){const R=g.BASE,C=(T,I)=>I===Ot||I===oe||!T.equals(R)?T.multiplyUnsafe(I):T.multiply(I),b=C(this,x).add(C(v,B));return b.is0()?void 0:b}toAffine(v){return p(this,v)}isTorsionFree(){const{h:v,isTorsionFree:x}=e;if(v===oe)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:x}=e;return v===oe?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return Zn("isCompressed",v),this.assertValidity(),i(g,this,v)}toHex(v=!0){return Zn("isCompressed",v),Jn(this.toRawBytes(v))}}g.BASE=new g(e.Gx,e.Gy,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:y,nBitLength:_}=e,A=fv(g,y?Math.ceil(_/2):_);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:l}}function wv(t){const e=Gh(t);return Qn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function bv(t){const e=wv(t),{Fp:r,n,nByteLength:i,nBitLength:s}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(E){return Se(E,n)}function u(E){return wa(E,n)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=yv({...e,toBytes(E,w,S){const O=w.toAffine(),D=r.toBytes(O.x),N=pt;return Zn("isCompressed",S),S?N(Uint8Array.from([w.hasEvenY()?2:3]),D):N(Uint8Array.from([4]),D,r.toBytes(O.y))},fromBytes(E){const w=E.length,S=E[0],O=E.subarray(1);if(w===o&&(S===2||S===3)){const D=kt(O);if(!Xn(D,oe,r.ORDER))throw new Error("Point is not on curve");const N=f(D);let U;try{U=r.sqrt(N)}catch(V){const K=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+K)}const L=(U&oe)===oe;return(S&1)===1!==L&&(U=r.neg(U)),{x:D,y:U}}else if(w===a&&S===4){const D=r.fromBytes(O.subarray(0,r.BYTES)),N=r.fromBytes(O.subarray(r.BYTES,2*r.BYTES));return{x:D,y:N}}else{const D=o,N=a;throw new Error("invalid Point, expected length of "+D+", or uncompressed "+N+", got "+w)}}});function d(E){const w=n>>oe;return E>w}function g(E){return d(E)?c(-E):E}const y=(E,w,S)=>kt(E.slice(w,S));class _{constructor(w,S,O){Zr("r",w,oe,n),Zr("s",S,oe,n),this.r=w,this.s=S,O!=null&&(this.recovery=O),Object.freeze(this)}static fromCompact(w){const S=i;return w=De("compactSignature",w,S*2),new _(y(w,0,S),y(w,S,2*S))}static fromDER(w){const{r:S,s:O}=er.toSig(De("DER",w));return new _(S,O)}assertValidity(){}addRecoveryBit(w){return new _(this.r,this.s,w)}recoverPublicKey(w){const{r:S,s:O,recovery:D}=this,N=R(De("msgHash",w));if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");const U=D===2||D===3?S+e.n:S;if(U>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=D&1?"03":"02",j=l.fromHex(L+Sa(U,r.BYTES)),V=u(U),K=c(-N*V),H=c(O*V),Z=l.BASE.multiplyAndAddUnsafe(j,K,H);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ws(this.toDERHex())}toDERHex(){return er.hexFromSig(this)}toCompactRawBytes(){return ws(this.toCompactHex())}toCompactHex(){const w=i;return Sa(this.r,w)+Sa(this.s,w)}}const A={isValidPrivateKey(E){try{return h(E),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const E=jh(e.n);return uv(e.randomBytes(E),e.n)},precompute(E=8,w=l.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}};function m(E,w=!0){return l.fromPrivateKey(E).toRawBytes(w)}function v(E){if(typeof E=="bigint")return!1;if(E instanceof l)return!0;const S=De("key",E).length,O=r.BYTES,D=O+1,N=2*O+1;if(!(e.allowedPrivateKeyLengths||i===D))return S===D||S===N}function x(E,w,S=!0){if(v(E)===!0)throw new Error("first arg must be private key");if(v(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(h(E)).toRawBytes(S)}const B=e.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");const w=kt(E),S=E.length*8-s;return S>0?w>>BigInt(S):w},R=e.bits2int_modN||function(E){return c(B(E))},C=bs(s);function b(E){return Zr("num < 2^"+s,E,Ot,C),Yr(E,i)}function T(E,w,S=I){if(["recovered","canonical"].some(W=>W in S))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:D}=e;let{lowS:N,prehash:U,extraEntropy:L}=S;N==null&&(N=!0),E=De("msgHash",E),Yh(S),U&&(E=De("prehashed msgHash",O(E)));const j=R(E),V=h(w),K=[b(V),b(j)];if(L!=null&&L!==!1){const W=L===!0?D(r.BYTES):L;K.push(De("extraEntropy",W))}const H=pt(...K),Z=j;function Q(W){const ae=B(W);if(!p(ae))return;const ge=u(ae),dt=l.BASE.multiply(ae).toAffine(),At=c(dt.x);if(At===Ot)return;const Dt=c(ge*c(Z+At*V));if(Dt===Ot)return;let Wt=(dt.x===At?0:2)|Number(dt.y&oe),ho=Dt;return N&&d(Dt)&&(ho=g(Dt),Wt^=1),new _(At,ho,Wt)}return{seed:H,k2sig:Q}}const I={lowS:e.lowS,prehash:!1},$={lowS:e.lowS,prehash:!1};function P(E,w,S=I){const{seed:O,k2sig:D}=T(E,w,S),N=e;return tv(N.hash.outputLen,N.nByteLength,N.hmac)(O,D)}l.BASE._setWindowSize(8);function F(E,w,S,O=$){const D=E;w=De("msgHash",w),S=De("publicKey",S);const{lowS:N,prehash:U,format:L}=O;if(Yh(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const j=typeof D=="string"||Yn(D),V=!j&&!L&&typeof D=="object"&&D!==null&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!j&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,H;try{if(V&&(K=new _(D.r,D.s)),j){try{L!=="compact"&&(K=_.fromDER(D))}catch(Wt){if(!(Wt instanceof er.Err))throw Wt}!K&&L!=="der"&&(K=_.fromCompact(D))}H=l.fromHex(S)}catch{return!1}if(!K||N&&K.hasHighS())return!1;U&&(w=e.hash(w));const{r:Z,s:Q}=K,W=R(w),ae=u(Q),ge=c(W*ae),dt=c(Z*ae),At=l.BASE.multiplyAndAddUnsafe(H,ge,dt)?.toAffine();return At?c(At.x)===Z:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:x,sign:P,verify:F,ProjectivePoint:l,Signature:_,utils:A}}function mv(t,e){const r=t.ORDER;let n=Ot;for(let d=r-oe;d%gr===Ot;d/=gr)n+=oe;const i=n,s=gr<<i-oe-oe,o=s*gr,a=(r-oe)/o,c=(a-oe)/gr,u=o-oe,l=s,h=t.pow(e,a),f=t.pow(e,(a+oe)/gr);let p=(d,g)=>{let y=h,_=t.pow(g,u),A=t.sqr(_);A=t.mul(A,g);let m=t.mul(d,A);m=t.pow(m,c),m=t.mul(m,_),_=t.mul(m,g),A=t.mul(m,d);let v=t.mul(A,_);m=t.pow(v,l);let x=t.eql(m,t.ONE);_=t.mul(A,f),m=t.mul(v,y),A=t.cmov(_,A,x),v=t.cmov(m,v,x);for(let B=i;B>oe;B--){let R=B-gr;R=gr<<R-oe;let C=t.pow(v,R);const b=t.eql(C,t.ONE);_=t.mul(A,y),y=t.mul(y,y),C=t.mul(v,y),A=t.cmov(_,A,b),v=t.cmov(C,v,b)}return{isValid:x,value:A}};if(t.ORDER%Ia===ei){const d=(t.ORDER-ei)/Ia,g=t.sqrt(t.neg(e));p=(y,_)=>{let A=t.sqr(_);const m=t.mul(y,_);A=t.mul(A,m);let v=t.pow(A,d);v=t.mul(v,m);const x=t.mul(v,g),B=t.mul(t.sqr(v),_),R=t.eql(B,y);let C=t.cmov(x,v,R);return{isValid:R,value:C}}}return p}function vv(t,e){if(Lh(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const r=mv(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return n=>{let i,s,o,a,c,u,l,h;i=t.sqr(n),i=t.mul(i,e.Z),s=t.sqr(i),s=t.add(s,i),o=t.add(s,t.ONE),o=t.mul(o,e.B),a=t.cmov(e.Z,t.neg(s),!t.eql(s,t.ZERO)),a=t.mul(a,e.A),s=t.sqr(o),u=t.sqr(a),c=t.mul(u,e.A),s=t.add(s,c),s=t.mul(s,o),u=t.mul(u,a),c=t.mul(u,e.B),s=t.add(s,c),l=t.mul(i,o);const{isValid:f,value:p}=r(s,u);h=t.mul(i,n),h=t.mul(h,p),l=t.cmov(l,o,f),h=t.cmov(h,p,f);const d=t.isOdd(n)===t.isOdd(h);h=t.cmov(t.neg(h),h,d);const g=ms(t,[a],!0)[0];return l=t.mul(l,g),{x:l,y:h}}}function Ev(t){return{hash:t,hmac:(e,...r)=>Dh(t,e,t2(...r)),randomBytes:ah}}function xv(t,e){const r=n=>bv({...t,...Ev(n)});return{...r(e),create:r}}const _v=kt;function yr(t,e){if(ti(t),ti(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function Sv(t,e){const r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function ti(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function Iv(t,e,r,n){pr(t),pr(e),ti(r),e.length>255&&(e=n(pt(pa("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=n,o=Math.ceil(r/i);if(r>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=pt(e,yr(e.length,1)),c=yr(0,s),u=yr(r,2),l=new Array(o),h=n(pt(c,t,u,yr(0,1),a));l[0]=n(pt(h,yr(1,1),a));for(let p=1;p<=o;p++){const d=[Sv(h,l[p-1]),yr(p+1,1),a];l[p]=n(pt(...d))}return pt(...l).slice(0,r)}function Av(t,e,r,n,i){if(pr(t),pr(e),ti(r),e.length>255){const s=Math.ceil(2*n/8);e=i.create({dkLen:s}).update(pa("H2C-OVERSIZE-DST-")).update(e).digest()}if(r>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:r}).update(t).update(yr(r,2)).update(e).update(yr(e.length,1)).digest()}function Zh(t,e,r){Qn(r,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:n,k:i,m:s,hash:o,expand:a,DST:c}=r;pr(t),ti(e);const u=typeof c=="string"?pa(c):c,l=n.toString(2).length,h=Math.ceil((l+i)/8),f=e*s*h;let p;if(a==="xmd")p=Iv(t,u,f,o);else if(a==="xof")p=Av(t,u,f,i,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let g=0;g<e;g++){const y=new Array(s);for(let _=0;_<s;_++){const A=h*(_+g*s),m=p.subarray(A,A+h);y[_]=Se(_v(m),n)}d[g]=y}return d}function Dv(t,e){const r=e.map(n=>Array.from(n).reverse());return(n,i)=>{const[s,o,a,c]=r.map(h=>h.reduce((f,p)=>t.add(t.mul(f,n),p))),[u,l]=ms(t,[o,c],!0);return n=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:n,y:i}}}function $v(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function n(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:r,hashToCurve(s,o){const a=Zh(s,2,{...r,DST:r.DST,...o}),c=n(a[0]),u=n(a[1]);return i(c.add(u))},encodeToCurve(s,o){const a=Zh(s,1,{...r,DST:r.encodeDST,...o});return i(n(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(n(s))}}}const ri=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),vs=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Aa=BigInt(0),ni=BigInt(1),Es=BigInt(2),Jh=(t,e)=>(t+e/Es)/e;function Xh(t){const e=ri,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,h=gt(l,r,e)*l%e,f=gt(h,r,e)*l%e,p=gt(f,Es,e)*u%e,d=gt(p,i,e)*p%e,g=gt(d,s,e)*d%e,y=gt(g,a,e)*g%e,_=gt(y,c,e)*y%e,A=gt(_,a,e)*g%e,m=gt(A,r,e)*l%e,v=gt(m,o,e)*d%e,x=gt(v,n,e)*u%e,B=gt(x,Es,e);if(!wr.eql(wr.sqr(B),t))throw new Error("Cannot find square root");return B}const wr=ba(ri,void 0,void 0,{sqrt:Xh}),ii=xv({a:Aa,b:BigInt(7),Fp:wr,n:vs,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=vs,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-ni*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=Jh(s*t,e),c=Jh(-n*t,e);let u=Se(t-a*r-c*i,e),l=Se(-a*n-c*s,e);const h=u>o,f=l>o;if(h&&(u=e-u),f&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}}},ps),Qh={};function xs(t,...e){let r=Qh[t];if(r===void 0){const n=ps(Uint8Array.from(t,i=>i.charCodeAt(0)));r=pt(n,n),Qh[t]=r}return ps(pt(r,...e))}const Da=t=>t.toRawBytes(!0).slice(1),$a=t=>Yr(t,32),Oa=t=>Se(t,ri),si=t=>Se(t,vs),Ba=(()=>ii.ProjectivePoint)(),Ov=(t,e,r)=>Ba.BASE.multiplyAndAddUnsafe(t,e,r);function Ta(t){let e=ii.utils.normPrivateKeyToScalar(t),r=Ba.fromPrivateKey(e);return{scalar:r.hasEvenY()?e:si(-e),bytes:Da(r)}}function ef(t){Zr("x",t,ni,ri);const e=Oa(t*t),r=Oa(e*t+BigInt(7));let n=Xh(r);n%Es!==Aa&&(n=Oa(-n));const i=new Ba(t,n,ni);return i.assertValidity(),i}const _n=kt;function tf(...t){return si(_n(xs("BIP0340/challenge",...t)))}function Bv(t){return Ta(t).bytes}function Tv(t,e,r=ah(32)){const n=De("message",t),{bytes:i,scalar:s}=Ta(e),o=De("auxRand",r,32),a=$a(s^_n(xs("BIP0340/aux",o))),c=xs("BIP0340/nonce",a,i,n),u=si(_n(c));if(u===Aa)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Ta(u),f=tf(l,i,n),p=new Uint8Array(64);if(p.set(l,0),p.set($a(si(h+f*s)),32),!rf(p,n,i))throw new Error("sign: Invalid signature produced");return p}function rf(t,e,r){const n=De("signature",t,64),i=De("message",e),s=De("publicKey",r,32);try{const o=ef(_n(s)),a=_n(n.subarray(0,32));if(!Xn(a,ni,ri))return!1;const c=_n(n.subarray(32,64));if(!Xn(c,ni,vs))return!1;const u=tf($a(a),Da(o),i),l=Ov(o,c,si(-u));return!(!l||!l.hasEvenY()||l.toAffine().x!==a)}catch{return!1}}const Pv=(()=>({getPublicKey:Bv,sign:Tv,verify:rf,utils:{randomPrivateKey:ii.utils.randomPrivateKey,lift_x:ef,pointToBytes:Da,numberToBytesBE:Yr,bytesToNumberBE:kt,taggedHash:xs,mod:Se}}))(),Cv=(()=>Dv(wr,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))))(),Rv=(()=>vv(wr,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:wr.create(BigInt("-11"))}))(),Pa=(()=>$v(ii.ProjectivePoint,t=>{const{x:e,y:r}=Rv(wr.create(t[0]));return Cv(e,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:wr.ORDER,m:1,k:128,expand:"xmd",hash:ps}))();var Nv=Object.freeze({__proto__:null,secp256k1:ii,schnorr:Pv,secp256k1_hasher:Pa,hashToCurve:(()=>Pa.hashToCurve)(),encodeToCurve:(()=>Pa.encodeToCurve)()});function Uv(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 l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const r=t.length,n=t.charAt(0),i=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);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 l=0,h=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,l++;const d=(p-f)*s+1>>>0,g=new Uint8Array(d);for(;f!==p;){let A=u[f],m=0;for(let v=d-1;(A!==0||m<h)&&v!==-1;v--,m++)A+=256*g[v]>>>0,g[v]=A%r>>>0,A=A/r>>>0;if(A!==0)throw new Error("Non-zero carry");h=m,f++}let y=d-h;for(;y!==d&&g[y]===0;)y++;let _=n.repeat(l);for(;y<d;++y)_+=t.charAt(g[y]);return _}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===n;)h++,l++;const p=(u.length-l)*i+1>>>0,d=new Uint8Array(p);for(;l<u.length;){const A=u.charCodeAt(l);if(A>255)return;let m=e[A];if(m===255)return;let v=0;for(let x=p-1;(m!==0||v<f)&&x!==-1;x--,v++)m+=r*d[x]>>>0,d[x]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");f=v,l++}let g=p-f;for(;g!==p&&d[g]===0;)g++;const y=new Uint8Array(h+(p-g));let _=h;for(;g!==p;)y[_++]=d[g++];return y}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var Fv="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",oi=Uv(Fv);function kv(t){const e=t.length;let r=0,n=0;for(;n<e;){let i=t.charCodeAt(n++);if(i&4294967168)if(!(i&4294965248))r+=2;else{if(i>=55296&&i<=56319&&n<e){const s=t.charCodeAt(n);(s&64512)===56320&&(++n,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?r+=4:r+=3}else{r++;continue}}return r}function Lv(t,e,r){const n=t.length;let i=r,s=0;for(;s<n;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<n){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128):(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128)}else{e[i++]=o;continue}e[i++]=o&63|128}}const Mv=new TextEncoder,zv=50;function qv(t,e,r){Mv.encodeInto(t,e.subarray(r))}function jv(t,e,r){t.length>zv?qv(t,e,r):Lv(t,e,r)}const Vv=4096;function nf(t,e,r){let n=e;const i=n+r,s=[];let o="";for(;n<i;){const a=t[n++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[n++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[n++]&63,u=t[n++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[n++]&63,u=t[n++]&63,l=t[n++]&63;let h=(a&7)<<18|c<<12|u<<6|l;h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|h&1023),s.push(h)}else s.push(a);s.length>=Vv&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Kv=new TextDecoder,Hv=200;function Wv(t,e,r){const n=t.subarray(e,e+r);return Kv.decode(n)}function Gv(t,e,r){return r>Hv?Wv(t,e,r):nf(t,e,r)}class _s{constructor(e,r){this.type=e,this.data=r}}class ot extends Error{constructor(e){super(e);const r=Object.create(ot.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ot.name})}}const ai=4294967295;function Yv(t,e,r){const n=r/4294967296,i=r;t.setUint32(e,n),t.setUint32(e+4,i)}function sf(t,e,r){const n=Math.floor(r/4294967296),i=r;t.setUint32(e,n),t.setUint32(e+4,i)}function of(t,e){const r=t.getInt32(e),n=t.getUint32(e+4);return r*4294967296+n}function Zv(t,e){const r=t.getUint32(e),n=t.getUint32(e+4);return r*4294967296+n}const Jv=-1,Xv=4294967296-1,Qv=17179869184-1;function eE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Qv)if(e===0&&t<=Xv){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,n=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|r&3),s.setUint32(4,n),i}else{const r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,e),sf(n,4,t),r}}function tE(t){const e=t.getTime(),r=Math.floor(e/1e3),n=(e-r*1e3)*1e6,i=Math.floor(n/1e9);return{sec:r+i,nsec:n-i*1e9}}function rE(t){if(t instanceof Date){const e=tE(t);return eE(e)}else return null}function nE(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 r=e.getUint32(0),n=e.getUint32(4),i=(r&3)*4294967296+n,s=r>>>2;return{sec:i,nsec:s}}case 12:{const r=of(e,4),n=e.getUint32(0);return{sec:r,nsec:n}}default:throw new ot(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function iE(t){const e=nE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const sE={type:Jv,encode:rE,decode:iE};class Ss{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(sE)}register({type:e,encode:r,decode:n}){if(e>=0)this.encoders[e]=r,this.decoders[e]=n;else{const i=-1-e;this.builtInEncoders[i]=r,this.builtInDecoders[i]=n}}tryToEncode(e,r){for(let n=0;n<this.builtInEncoders.length;n++){const i=this.builtInEncoders[n];if(i!=null){const s=i(e,r);if(s!=null){const o=-1-n;return new _s(o,s)}}}for(let n=0;n<this.encoders.length;n++){const i=this.encoders[n];if(i!=null){const s=i(e,r);if(s!=null){const o=n;return new _s(o,s)}}}return e instanceof _s?e:null}decode(e,r,n){const i=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return i?i(e,r,n):new _s(r,e)}}Ss.defaultCodec=new Ss;function oE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ca(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):oE(t)?new Uint8Array(t):Uint8Array.from(t)}const aE=100,cE=2048;class Ra{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Ss.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??aE,this.initialBufferSize=e?.initialBufferSize??cE,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 Ra({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,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);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,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),n=new Uint8Array(r),i=new DataView(r);n.set(this.bytes),this.view=i,this.bytes=n}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 n=kv(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),jv(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,r){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const n=Ca(e);this.writeU8a(n)}encodeArray(e,r){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const i of e)this.doEncode(i,r+1)}countWithoutUndefined(e,r){let n=0;for(const i of r)e[i]!==void 0&&n++;return n}encodeMap(e,r){const n=Object.keys(e);this.sortKeys&&n.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of n){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),i=n.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(n);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}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),Yv(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),sf(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 uE(t,e){return new Ra(e).encodeSharedRef(t)}function Na(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const lE=16,hE=16;class fE{constructor(e=lE,r=hE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,n){const i=this.caches[n-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<n;a++)if(o[a]!==e[r+a])continue e;return s.str}return null}store(e,r){const n=this.caches[e.length-1],i={bytes:e,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,r,n){const i=this.find(e,r,n);if(i!=null)return this.hit++,i;this.miss++;const s=nf(e,r,n),o=Uint8Array.prototype.slice.call(e,r,r+n);return this.store(o,s),s}}const Ua="array",ci="map_key",af="map_value",dE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ot("The type of key must be string or number but "+typeof t)};class pE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=Ua,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=ci,r.readCount=0,r.size=e,r.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===Ua){const n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===ci||e.type===af){const n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const ui=-1,Fa=new DataView(new ArrayBuffer(0)),gE=new Uint8Array(Fa.buffer);try{Fa.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 cf=new RangeError("Insufficient data"),yE=new fE;class ka{constructor(e){this.totalPos=0,this.pos=0,this.view=Fa,this.bytes=gE,this.headByte=ui,this.stack=new pE,this.entered=!1,this.extensionCodec=e?.extensionCodec??Ss.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??ai,this.maxBinLength=e?.maxBinLength??ai,this.maxArrayLength=e?.maxArrayLength??ai,this.maxMapLength=e?.maxMapLength??ai,this.maxExtLength=e?.maxExtLength??ai,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:yE,this.mapKeyConverter=e?.mapKeyConverter??dE}clone(){return new ka({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=ui,this.stack.reset()}setBuffer(e){const r=Ca(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ui&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),n=Ca(e),i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}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 r=!1,n;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Na(i)} at ${o} (${s} 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,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let n=r,i=-1;for await(const s of e){if(r&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==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 r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else{const i=e-160;r=this.decodeString(i,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const i=this.lookU8();r=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();r=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();r=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e===196){const i=this.lookU8();r=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();r=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();r=this.decodeBinary(i,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();r=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();r=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();r=this.decodeExtension(i,4)}else throw new ot(`Unrecognized type byte: ${Na(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const i=n.top();if(i.type===Ua)if(i.array[i.position]=r,i.position++,i.position===i.size)r=i.array,n.release(i);else continue e;else if(i.type===ci){if(r==="__proto__")throw new ot("The key __proto__ is not allowed");i.key=this.mapKeyConverter(r),i.type=af;continue e}else if(i.map[i.key]=r,i.readCount++,i.readCount===i.size)r=i.map,n.release(i);else{i.key=null,i.type=ci;continue e}}return r}}readHeadByte(){return this.headByte===ui&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ui}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 ot(`Unrecognized array type byte: ${Na(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ot(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ot(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new ot(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw cf;const n=this.pos+r;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,n,e):i=Gv(this.bytes,n,e),this.pos+=r+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ci:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new ot(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw cf;const n=this.pos+r,i=this.bytes.subarray(n,n+e);return this.pos+=r+e,i}decodeExtension(e,r){if(e>this.maxExtLength)throw new ot(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+r),i=this.decodeBinary(e,r+1);return this.extensionCodec.decode(i,n,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=Zv(this.view,this.pos);return this.pos+=8,e}readI64(){const e=of(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 wE(t,e){return new ka(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Is(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function La(t,...e){if(!Is(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 uf(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function lf(t){if(typeof t!="function")throw new Error("function expected");return!0}function br(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function li(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function As(t){if(!Array.isArray(t))throw new Error("array expected")}function Ds(t,e){if(!uf(!0,e))throw new Error(`${t}: array of strings expected`)}function Ma(t,e){if(!uf(!1,e))throw new Error(`${t}: array of numbers expected`)}function at(...t){const e=s=>s,r=(s,o)=>a=>s(o(a)),n=t.map(s=>s.encode).reduceRight(r,e),i=t.map(s=>s.decode).reduce(r,e);return{encode:n,decode:i}}function ct(t){const e=typeof t=="string"?t.split(""):t,r=e.length;Ds("alphabet",e);const n=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(As(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(As(i),i.map(s=>{br("alphabet.decode",s);const o=n.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function ut(t=""){return br("join",t),{encode:e=>(Ds("join.decode",e),e.join(t)),decode:e=>(br("join.decode",e),e.split(t))}}function $s(t,e="="){return li(t),br("padding",e),{encode(r){for(Ds("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){Ds("padding.decode",r);let n=r.length;if(n*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if((n-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function hf(t){return lf(t),{encode:e=>e,decode:e=>t(e)}}function ff(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(As(t),!t.length)return[];let n=0;const i=[],s=Array.from(t,a=>{if(li(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const l=s[u],h=e*a,f=h+l;if(!Number.isSafeInteger(f)||h/e!==a||f-l!==h)throw new Error("convertRadix: carry overflow");const p=f/r;a=f%r;const d=Math.floor(p);if(s[u]=d,!Number.isSafeInteger(d)||d*r+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:n=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const df=(t,e)=>e===0?t:df(e,t%e),Os=(t,e)=>t+(e-df(t,e)),Bs=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function za(t,e,r,n){if(As(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Os(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Os(e,r)}`);let i=0,s=0;const o=Bs[e],a=Bs[r]-1,c=[];for(const u of t){if(li(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=r;s-=r)c.push((i>>s-r&a)>>>0);const l=Bs[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<r-s&a,!n&&s>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&s>0&&c.push(i>>>0),c}function bE(t){li(t);const e=2**8;return{encode:r=>{if(!Is(r))throw new Error("radix.encode input should be Uint8Array");return ff(Array.from(r),e,t)},decode:r=>(Ma("radix.decode",r),Uint8Array.from(ff(r,t,e)))}}function yt(t,e=!1){if(li(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Os(8,t)>32||Os(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Is(r))throw new Error("radix2.encode input should be Uint8Array");return za(Array.from(r),8,t,!e)},decode:r=>(Ma("radix2.decode",r),Uint8Array.from(za(r,t,8,e)))}}function pf(t){return lf(t),function(...e){try{return t.apply(null,e)}catch{}}}at(yt(4),ct("0123456789ABCDEF"),ut(""));const mE=at(yt(5),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),$s(5),ut(""));at(yt(5),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ut("")),at(yt(5),ct("0123456789ABCDEFGHIJKLMNOPQRSTUV"),$s(5),ut("")),at(yt(5),ct("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ut("")),at(yt(5),ct("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ut(""),hf(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const gf=(()=>typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function")(),yf=(t,e)=>{br("base64",t);const r=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,n=e?"base64url":"base64";if(t.length>0&&!r.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:n,lastChunkHandling:"strict"})};gf||at(yt(6),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),$s(6),ut("")),at(yt(6),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ut("")),gf||at(yt(6),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),$s(6),ut("")),at(yt(6),ct("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ut(""));const qa=t=>at(bE(58),ct(t),ut(""));qa("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),qa("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),qa("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const ja=at(ct("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ut("")),wf=[996825010,642813549,513874426,1027748829,705979059];function hi(t){const e=t>>25;let r=(t&33554431)<<5;for(let n=0;n<wf.length;n++)(e>>n&1)===1&&(r^=wf[n]);return r}function bf(t,e,r=1){const n=t.length;let i=1;for(let s=0;s<n;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=hi(i)^o>>5}i=hi(i);for(let s=0;s<n;s++)i=hi(i)^t.charCodeAt(s)&31;for(let s of e)i=hi(i)^s;for(let s=0;s<6;s++)i=hi(i);return i^=r,ja.encode(za([i%Bs[30]],30,5,!1))}function mf(t){const e=t==="bech32"?1:734539939,r=yt(5),n=r.decode,i=r.encode,s=pf(n);function o(h,f,p=90){br("bech32.encode prefix",h),Is(f)&&(f=Array.from(f)),Ma("bech32.encode",f);const d=h.length;if(d===0)throw new TypeError(`Invalid prefix length ${d}`);const g=d+7+f.length;if(p!==!1&&g>p)throw new TypeError(`Length ${g} exceeds limit ${p}`);const y=h.toLowerCase(),_=bf(y,f,e);return`${y}1${ja.encode(f)}${_}`}function a(h,f=90){br("bech32.decode input",h);const p=h.length;if(p<8||f!==!1&&p>f)throw new TypeError(`invalid string length: ${p} (${h}). Expected (8..${f})`);const d=h.toLowerCase();if(h!==d&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=d.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=d.slice(0,g),_=d.slice(g+1);if(_.length<6)throw new Error("Data must be at least 6 characters long");const A=ja.decode(_).slice(0,-6),m=bf(y,A,e);if(!_.endsWith(m))throw new Error(`Invalid checksum in ${h}: expected "${m}"`);return{prefix:y,words:A}}const c=pf(a);function u(h){const{prefix:f,words:p}=a(h,!1);return{prefix:f,words:p,bytes:n(p)}}function l(h,f){return o(h,i(f))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:i}}mf("bech32"),mf("bech32m");const vE=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),EE={encode(t){return La(t),t.toHex()},decode(t){return br("hex",t),Uint8Array.fromHex(t)}};vE||at(yt(4),ct("0123456789abcdef"),ut(""),hf(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));function Va(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function vf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Va(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=vf(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return Va(r)}function xE(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(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,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var m=(A-_)*l+1>>>0,v=new Uint8Array(m);_!==A;){for(var x=d[_],B=0,R=m-1;(x!==0||B<y)&&R!==-1;R--,B++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=B,_++}for(var C=m-y;C!==m&&v[C]===0;)C++;for(var b=c.repeat(g);C<m;++C)b+=t.charAt(v[C]);return b}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,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,m=new Uint8Array(A);d[g];){var v=r[d.charCodeAt(g)];if(v===255)return;for(var x=0,B=A-1;(v!==0||x<_)&&B!==-1;B--,x++)v+=a*m[B]>>>0,m[B]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&m[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),b=y;R!==A;)C[b++]=m[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var _E=xE,SE=_E;const Ef=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")},IE=t=>new TextEncoder().encode(t),AE=t=>new TextDecoder().decode(t);class DE{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $E{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 xf(this,e)}}class OE{constructor(e){this.decoders=e}or(e){return xf(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const xf=(t,e)=>new OE({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class BE{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new DE(e,r,n),this.decoder=new $E(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ts=({name:t,prefix:e,encode:r,decode:n})=>new BE(t,e,r,n),di=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=SE(r,e);return Ts({prefix:t,name:e,encode:n,decode:s=>Ef(i(s))})},TE=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},PE=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},$e=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Ts({prefix:e,name:t,encode(i){return PE(i,n,r)},decode(i){return TE(i,n,r,t)}}),CE=Ts({prefix:"\0",name:"identity",encode:t=>AE(t),decode:t=>IE(t)});var RE=Object.freeze({__proto__:null,identity:CE});const NE=$e({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var UE=Object.freeze({__proto__:null,base2:NE});const FE=$e({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var kE=Object.freeze({__proto__:null,base8:FE});const LE=di({prefix:"9",name:"base10",alphabet:"0123456789"});var ME=Object.freeze({__proto__:null,base10:LE});const zE=$e({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),qE=$e({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var jE=Object.freeze({__proto__:null,base16:zE,base16upper:qE});const VE=$e({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),KE=$e({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),HE=$e({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),WE=$e({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),GE=$e({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),YE=$e({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),ZE=$e({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),JE=$e({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),XE=$e({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var QE=Object.freeze({__proto__:null,base32:VE,base32upper:KE,base32pad:HE,base32padupper:WE,base32hex:GE,base32hexupper:YE,base32hexpad:ZE,base32hexpadupper:JE,base32z:XE});const e3=di({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),t3=di({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var r3=Object.freeze({__proto__:null,base36:e3,base36upper:t3});const n3=di({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),i3=di({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var s3=Object.freeze({__proto__:null,base58btc:n3,base58flickr:i3});const o3=$e({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),a3=$e({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),c3=$e({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),u3=$e({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var l3=Object.freeze({__proto__:null,base64:o3,base64pad:a3,base64url:c3,base64urlpad:u3});const _f=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),h3=_f.reduce((t,e,r)=>(t[r]=e,t),[]),f3=_f.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function d3(t){return t.reduce((e,r)=>(e+=h3[r],e),"")}function p3(t){const e=[];for(const r of t){const n=f3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const g3=Ts({prefix:"\u{1F680}",name:"base256emoji",encode:d3,decode:p3});var y3=Object.freeze({__proto__:null,base256emoji:g3}),w3=If,Sf=128,b3=127,m3=~b3,v3=Math.pow(2,31);function If(t,e,r){e=e||[],r=r||0;for(var n=r;t>=v3;)e[r++]=t&255|Sf,t/=128;for(;t&m3;)e[r++]=t&255|Sf,t>>>=7;return e[r]=t|0,If.bytes=r-n+1,e}var E3=Ka,x3=128,Af=127;function Ka(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Ka.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Af)<<i:(o&Af)*Math.pow(2,i),i+=7}while(o>=x3);return Ka.bytes=s-n,r}var _3=Math.pow(2,7),S3=Math.pow(2,14),I3=Math.pow(2,21),A3=Math.pow(2,28),D3=Math.pow(2,35),$3=Math.pow(2,42),O3=Math.pow(2,49),B3=Math.pow(2,56),T3=Math.pow(2,63),P3=function(t){return t<_3?1:t<S3?2:t<I3?3:t<A3?4:t<D3?5:t<$3?6:t<O3?7:t<B3?8:t<T3?9:10},C3={encode:w3,decode:E3,encodingLength:P3},Df=C3;const $f=(t,e,r=0)=>(Df.encode(t,e,r),e),Of=t=>Df.encodingLength(t),Ha=(t,e)=>{const r=e.byteLength,n=Of(t),i=n+Of(r),s=new Uint8Array(i+r);return $f(t,s,0),$f(r,s,n),s.set(e,i),new R3(t,r,e,s)};class R3{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Bf=({name:t,code:e,encode:r})=>new N3(t,e,r);class N3{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ha(this.code,r):r.then(n=>Ha(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Tf=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),U3=Bf({name:"sha2-256",code:18,encode:Tf("SHA-256")}),F3=Bf({name:"sha2-512",code:19,encode:Tf("SHA-512")});var k3=Object.freeze({__proto__:null,sha256:U3,sha512:F3});const Pf=0,L3="identity",Cf=Ef;var M3=Object.freeze({__proto__:null,identity:{code:Pf,name:L3,encode:Cf,digest:t=>Ha(Pf,Cf(t))}});new TextEncoder,new TextDecoder;const Rf={...RE,...UE,...kE,...ME,...jE,...QE,...r3,...s3,...l3,...y3};({...k3,...M3});function Nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Uf=Nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Wa=Nf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=vf(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Ff={utf8:Uf,"utf-8":Uf,hex:Rf.base16,latin1:Wa,ascii:Wa,binary:Wa,...Rf};function wt(t,e="utf8"){const r=Ff[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Va(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Qe(t,e="utf8"){const r=Ff[e];if(!r)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"):r.encoder.encode(t).substring(1)}const z3={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"}},q3="Input must be an string, Buffer or Uint8Array";function j3(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(q3);return e}function V3(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 K3(t,e,r){let n=`
18
- `+t+" = ";for(let i=0;i<e.length;i+=2){if(r===32)n+=Ps(e[i]).toUpperCase(),n+=" ",n+=Ps(e[i+1]).toUpperCase();else if(r===64)n+=Ps(e[i+1]).toUpperCase(),n+=Ps(e[i]).toUpperCase();else throw new Error("Invalid size "+r);i%6===4?n+=`
19
- `+new Array(t.length+4).join(" "):i<e.length-2&&(n+=" ")}console.log(n)}function H3(t,e,r){let n=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-n)+"ms"),n=s;for(let o=0;o<r;o++){const a=t(i),c=new Date().getTime(),u=c-n;n=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 kf={normalizeInput:j3,toHex:V3,debugPrint:K3,testSpeed:H3};const Cs=kf;function Rs(t,e,r){const n=t[e]+t[r];let i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function Lf(t,e,r,n){let i=t[e]+r;r<0&&(i+=4294967296);let s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function Mf(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function mr(t,e,r,n,i,s){const o=pi[i],a=pi[i+1],c=pi[s],u=pi[s+1];Rs(G,t,e),Lf(G,t,o,a);let l=G[n]^G[t],h=G[n+1]^G[t+1];G[n]=h,G[n+1]=l,Rs(G,r,n),l=G[e]^G[r],h=G[e+1]^G[r+1],G[e]=l>>>24^h<<8,G[e+1]=h>>>24^l<<8,Rs(G,t,e),Lf(G,t,c,u),l=G[n]^G[t],h=G[n+1]^G[t+1],G[n]=l>>>16^h<<16,G[n+1]=h>>>16^l<<16,Rs(G,r,n),l=G[e]^G[r],h=G[e+1]^G[r+1],G[e]=h>>>31^l<<1,G[e+1]=l>>>31^h<<1}const zf=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),W3=[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],Fe=new Uint8Array(W3.map(function(t){return t*2})),G=new Uint32Array(32),pi=new Uint32Array(32);function qf(t,e){let r=0;for(r=0;r<16;r++)G[r]=t.h[r],G[r+16]=zf[r];for(G[24]=G[24]^t.t,G[25]=G[25]^t.t/4294967296,e&&(G[28]=~G[28],G[29]=~G[29]),r=0;r<32;r++)pi[r]=Mf(t.b,4*r);for(r=0;r<12;r++)mr(0,8,16,24,Fe[r*16+0],Fe[r*16+1]),mr(2,10,18,26,Fe[r*16+2],Fe[r*16+3]),mr(4,12,20,28,Fe[r*16+4],Fe[r*16+5]),mr(6,14,22,30,Fe[r*16+6],Fe[r*16+7]),mr(0,10,20,30,Fe[r*16+8],Fe[r*16+9]),mr(2,12,22,24,Fe[r*16+10],Fe[r*16+11]),mr(4,14,16,26,Fe[r*16+12],Fe[r*16+13]),mr(6,8,18,28,Fe[r*16+14],Fe[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^G[r]^G[r+16]}const vr=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 jf(t,e,r,n){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(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(n&&n.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};vr.fill(0),vr[0]=t,e&&(vr[1]=e.length),vr[2]=1,vr[3]=1,r&&vr.set(r,32),n&&vr.set(n,48);for(let s=0;s<16;s++)i.h[s]=zf[s]^Mf(vr,s*4);return e&&(Ga(i,e),i.c=128),i}function Ga(t,e){for(let r=0;r<e.length;r++)t.c===128&&(t.t+=t.c,qf(t,!1),t.c=0),t.b[t.c++]=e[r]}function Vf(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;qf(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3);return e}function Kf(t,e,r,n,i){r=r||64,t=Cs.normalizeInput(t),n&&(n=Cs.normalizeInput(n)),i&&(i=Cs.normalizeInput(i));const s=jf(r,e,n,i);return Ga(s,t),Vf(s)}function G3(t,e,r,n,i){const s=Kf(t,e,r,n,i);return Cs.toHex(s)}var Y3={blake2b:Kf,blake2bHex:G3,blake2bInit:jf,blake2bUpdate:Ga,blake2bFinal:Vf};const Hf=kf;function Z3(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Er(t,e,r,n,i,s){ee[t]=ee[t]+ee[e]+i,ee[n]=Ns(ee[n]^ee[t],16),ee[r]=ee[r]+ee[n],ee[e]=Ns(ee[e]^ee[r],12),ee[t]=ee[t]+ee[e]+s,ee[n]=Ns(ee[n]^ee[t],8),ee[r]=ee[r]+ee[n],ee[e]=Ns(ee[e]^ee[r],7)}function Ns(t,e){return t>>>e^t<<32-e}const Wf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=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]),ee=new Uint32Array(16),Oe=new Uint32Array(16);function Gf(t,e){let r=0;for(r=0;r<8;r++)ee[r]=t.h[r],ee[r+8]=Wf[r];for(ee[12]^=t.t,ee[13]^=t.t/4294967296,e&&(ee[14]=~ee[14]),r=0;r<16;r++)Oe[r]=Z3(t.b,4*r);for(r=0;r<10;r++)Er(0,4,8,12,Oe[ke[r*16+0]],Oe[ke[r*16+1]]),Er(1,5,9,13,Oe[ke[r*16+2]],Oe[ke[r*16+3]]),Er(2,6,10,14,Oe[ke[r*16+4]],Oe[ke[r*16+5]]),Er(3,7,11,15,Oe[ke[r*16+6]],Oe[ke[r*16+7]]),Er(0,5,10,15,Oe[ke[r*16+8]],Oe[ke[r*16+9]]),Er(1,6,11,12,Oe[ke[r*16+10]],Oe[ke[r*16+11]]),Er(2,7,8,13,Oe[ke[r*16+12]],Oe[ke[r*16+13]]),Er(3,4,9,14,Oe[ke[r*16+14]],Oe[ke[r*16+15]]);for(r=0;r<8;r++)t.h[r]^=ee[r]^ee[r+8]}function Yf(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const r=e?e.length:0;if(e&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");const n={h:new Uint32Array(Wf),b:new Uint8Array(64),c:0,t:0,outlen:t};return n.h[0]^=16842752^r<<8^t,r>0&&(Ya(n,e),n.c=64),n}function Ya(t,e){for(let r=0;r<e.length;r++)t.c===64&&(t.t+=t.c,Gf(t,!1),t.c=0),t.b[t.c++]=e[r]}function Zf(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;Gf(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3)&255;return e}function Jf(t,e,r){r=r||32,t=Hf.normalizeInput(t);const n=Yf(r,e);return Ya(n,t),Zf(n)}function J3(t,e,r){const n=Jf(t,e,r);return Hf.toHex(n)}var X3={blake2s:Jf,blake2sHex:J3,blake2sInit:Yf,blake2sUpdate:Ya,blake2sFinal:Zf};const gi=Y3,yi=X3;var Q3={blake2b:gi.blake2b,blake2bHex:gi.blake2bHex,blake2bInit:gi.blake2bInit,blake2bUpdate:gi.blake2bUpdate,blake2bFinal:gi.blake2bFinal,blake2s:yi.blake2s,blake2sHex:yi.blake2sHex,blake2sInit:yi.blake2sInit,blake2sUpdate:yi.blake2sUpdate,blake2sFinal:yi.blake2sFinal};const ex=":";function Us(t){const[e,r]=t.split(ex);return{namespace:e,reference:r}}function Xf(t,e){return t.includes(":")?[t]:e.chains||[]}var tx=Object.defineProperty,rx=Object.defineProperties,nx=Object.getOwnPropertyDescriptors,Qf=Object.getOwnPropertySymbols,ix=Object.prototype.hasOwnProperty,sx=Object.prototype.propertyIsEnumerable,Za=(t,e,r)=>e in t?tx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ed=(t,e)=>{for(var r in e||(e={}))ix.call(e,r)&&Za(t,r,e[r]);if(Qf)for(var r of Qf(e))sx.call(e,r)&&Za(t,r,e[r]);return t},ox=(t,e)=>rx(t,nx(e)),td=(t,e,r)=>Za(t,typeof e!="symbol"?e+"":e,r);const ax="ReactNative",lt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},cx="js";function Fs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function xr(){return!Hr()&&!!Zo()&&navigator.product===ax}function ux(){return xr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function lx(){return xr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Sn(){return!Fs()&&!!Zo()&&!!Hr()}function wi(){return xr()?lt.reactNative:Fs()?lt.node:Sn()?lt.browser:lt.unknown}function rd(){var t;try{return xr()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function hx(t,e){const r=new URLSearchParams(t);for(const n of Object.keys(e).sort())if(e.hasOwnProperty(n)){const i=e[n];i!==void 0&&r.set(n,i)}return r.toString()}function fx(t){var e,r;const n=nd();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),ox(ed(ed({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:n.icons})}catch(i){return console.warn("Error populating app metadata",i),t||n}}function nd(){return Gl()||{name:"",description:"",url:"",icons:[""]}}function dx(){if(wi()===lt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:n}=global.Platform;return[r,n].join("-")}const t=dm();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 px(){var t;const e=wi();return e===lt.browser?[e,((t=Wl())==null?void 0:t.host)||"unknown"].join(":"):e}function id(t,e,r){const n=dx(),i=px();return[[t,e].join("-"),[cx,r].join("-"),n,i].join("/")}function gx({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=id(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=hx(u[1]||"",h);return u[0]+"?"+f}function Xr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Ja(t){return Object.fromEntries(t.entries())}function Xa(t){return new Map(Object.entries(t))}function Qr(t=M.FIVE_MINUTES,e){const r=M.toMiliseconds(t||M.FIVE_MINUTES);let n,i,s,o;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),n=a,i=c})}}function Lt(t,e,r){return new Promise(async(n,i)=>{const s=setTimeout(()=>i(new Error(r)),e);try{const o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function sd(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 yx(t){return sd("topic",t)}function wx(t){return sd("id",t)}function od(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function me(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function _r(t){return Date.now()>=M.toMiliseconds(t)}function ne(t,e){return`${t}${e?`:${e}`:""}`}function en(t=[],e=[]){return[...new Set([...t,...e])]}async function bx({id:t,topic:e,wcDeepLink:r}){var n;try{if(!r)return;const i=typeof r=="string"?JSON.parse(r):r,s=i?.href;if(typeof s!="string")return;const o=mx(s,t,e),a=wi();if(a===lt.browser){if(!((n=Hr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}vx(o)}else a===lt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function mx(t,e,r){const n=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${Sx(n,!0)}`}else i=`${i}/wc?${n}`;return i}function vx(t){let e="_self";_x()?e="_top":(xx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Ex(t,e){let r="";try{if(Sn()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function ad(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function cd(){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 Qa(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function xx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function _x(){try{return window.self!==window.top}catch{return!1}}function Sx(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function ud(t){return Buffer.from(t,"base64").toString("utf-8")}function Ix(t){return new Promise(e=>setTimeout(e,t))}class Ax{constructor({limit:e}){td(this,"limit"),td(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}}const ks=BigInt(2**32-1),ld=BigInt(32);function hd(t,e=!1){return e?{h:Number(t&ks),l:Number(t>>ld&ks)}:{h:Number(t>>ld&ks)|0,l:Number(t&ks)|0}}function fd(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=hd(t[s],e);[n[s],i[s]]=[o,a]}return[n,i]}const dd=(t,e,r)=>t>>>r,pd=(t,e,r)=>t<<32-r|e>>>r,Sr=(t,e,r)=>t>>>r|e<<32-r,Ir=(t,e,r)=>t<<32-r|e>>>r,bi=(t,e,r)=>t<<64-r|e>>>r-32,mi=(t,e,r)=>t>>>r-32|e<<64-r,Dx=(t,e)=>e,$x=(t,e)=>t,Ox=(t,e,r)=>t<<r|e>>>32-r,Bx=(t,e,r)=>e<<r|t>>>32-r,Tx=(t,e,r)=>e<<r-32|t>>>64-r,Px=(t,e,r)=>t<<r-32|e>>>64-r;function Bt(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const ec=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),tc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,Cx=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Rx=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,Nx=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Ux=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,In=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function rc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function bt(t,...e){if(!rc(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){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");tr(t.outputLen),tr(t.blockLen)}function Ar(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 ic(t,e){bt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function vi(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function mt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mt(t,e){return t<<32-e|t>>>e}const gd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function yd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const rr=gd?t=>t:t=>yd(t);function Fx(t){for(let e=0;e<t.length;e++)t[e]=yd(t[e]);return t}const Dr=gd?t=>t:Fx,wd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",kx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ei(t){if(bt(t),wd)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=kx[t[r]];return e}const nr={_0:48,_9:57,A:65,F:70,a:97,f:102};function bd(t){if(t>=nr._0&&t<=nr._9)return t-nr._0;if(t>=nr.A&&t<=nr.F)return t-(nr.A-10);if(t>=nr.a&&t<=nr.f)return t-(nr.a-10)}function oc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(wd)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=bd(t.charCodeAt(s)),a=bd(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Lx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Tt(t){return typeof t=="string"&&(t=Lx(t)),bt(t),t}function tn(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];bt(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class Ls{}function xi(t){const e=n=>t().update(Tt(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Mx(t){const e=(n,i)=>t(i).update(Tt(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function An(t=32){if(In&&typeof In.getRandomValues=="function")return In.getRandomValues(new Uint8Array(t));if(In&&typeof In.randomBytes=="function")return Uint8Array.from(In.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const zx=BigInt(0),_i=BigInt(1),qx=BigInt(2),jx=BigInt(7),Vx=BigInt(256),Kx=BigInt(113),md=[],vd=[],Ed=[];for(let t=0,e=_i,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],md.push(2*(5*n+r)),vd.push((t+1)*(t+2)/2%64);let i=zx;for(let s=0;s<7;s++)e=(e<<_i^(e>>jx)*Kx)%Vx,e&qx&&(i^=_i<<(_i<<BigInt(s))-_i);Ed.push(i)}const xd=fd(Ed,!0),Hx=xd[0],Wx=xd[1],_d=(t,e,r)=>r>32?Tx(t,e,r):Ox(t,e,r),Sd=(t,e,r)=>r>32?Px(t,e,r):Bx(t,e,r);function Gx(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[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=r[c],l=r[c+1],h=_d(u,l,1)^r[a],f=Sd(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=vd[o],c=_d(i,s,a),u=Sd(i,s,a),l=md[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=Hx[n],t[1]^=Wx[n]}mt(r)}class ac extends Ls{constructor(e,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,tr(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=vi(this.state)}clone(){return this._cloneInto()}keccak(){Dr(this.state32),Gx(this.state32,this.rounds),Dr(this.state32),this.posOut=0,this.pos=0}update(e){Ar(this),e=Tt(e),bt(e);const{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Ar(this,!1),bt(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=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 tr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ic(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,mt(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ac(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Yx=(t,e,r)=>xi(()=>new ac(e,t,r)),Zx=Yx(1,136,256/8);function Jx(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function Xx(t,e,r){return t&e^~t&r}function Qx(t,e,r){return t&e^t&r^e&r}class Id extends Ls{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=sc(this.buffer)}update(e){Ar(this),e=Tt(e),bt(e);const{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=sc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ar(this),ic(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,mt(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let h=o;h<i;h++)r[h]=0;Jx(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=sc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const $r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),e_=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]),Or=new Uint32Array(64);class t_ extends Id{constructor(e=32){super(64,e,8,!1),this.A=$r[0]|0,this.B=$r[1]|0,this.C=$r[2]|0,this.D=$r[3]|0,this.E=$r[4]|0,this.F=$r[5]|0,this.G=$r[6]|0,this.H=$r[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Or[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=Or[h-15],p=Or[h-2],d=Mt(f,7)^Mt(f,18)^f>>>3,g=Mt(p,17)^Mt(p,19)^p>>>10;Or[h]=g+Or[h-7]+d+Or[h-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Mt(a,6)^Mt(a,11)^Mt(a,25),p=l+f+Xx(a,c,u)+e_[h]+Or[h]|0,d=(Mt(n,2)^Mt(n,13)^Mt(n,22))+Qx(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+d|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){mt(Or)}destroy(){this.set(0,0,0,0,0,0,0,0),mt(this.buffer)}}const Ad=fd(["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))),r_=Ad[0],n_=Ad[1],Br=new Uint32Array(80),Tr=new Uint32Array(80);class cc extends Id{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,r){for(let m=0;m<16;m++,r+=4)Br[m]=e.getUint32(r),Tr[m]=e.getUint32(r+=4);for(let m=16;m<80;m++){const v=Br[m-15]|0,x=Tr[m-15]|0,B=Sr(v,x,1)^Sr(v,x,8)^dd(v,x,7),R=Ir(v,x,1)^Ir(v,x,8)^pd(v,x,7),C=Br[m-2]|0,b=Tr[m-2]|0,T=Sr(C,b,19)^bi(C,b,61)^dd(C,b,6),I=Ir(C,b,19)^mi(C,b,61)^pd(C,b,6),$=Cx(R,I,Tr[m-7],Tr[m-16]),P=Rx($,B,T,Br[m-7],Br[m-16]);Br[m]=P|0,Tr[m]=$|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let m=0;m<80;m++){const v=Sr(h,f,14)^Sr(h,f,18)^bi(h,f,41),x=Ir(h,f,14)^Ir(h,f,18)^mi(h,f,41),B=h&p^~h&g,R=f&d^~f&y,C=Nx(A,x,R,n_[m],Tr[m]),b=Ux(C,_,v,B,r_[m],Br[m]),T=C|0,I=Sr(n,i,28)^bi(n,i,34)^bi(n,i,39),$=Ir(n,i,28)^mi(n,i,34)^mi(n,i,39),P=n&s^n&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Bt(u|0,l|0,b|0,T|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const E=ec(T,$,F);n=tc(E,b,I,P),i=E|0}({h:n,l:i}=Bt(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=Bt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Bt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Bt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Bt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Bt(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Bt(this.Gh|0,this.Gl|0,g|0,y|0),{h:_,l:A}=Bt(this.Hh|0,this.Hl|0,_|0,A|0),this.set(n,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){mt(Br,Tr)}destroy(){mt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class i_ extends cc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const ze=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class s_ extends cc{constructor(){super(32),this.Ah=ze[0]|0,this.Al=ze[1]|0,this.Bh=ze[2]|0,this.Bl=ze[3]|0,this.Ch=ze[4]|0,this.Cl=ze[5]|0,this.Dh=ze[6]|0,this.Dl=ze[7]|0,this.Eh=ze[8]|0,this.El=ze[9]|0,this.Fh=ze[10]|0,this.Fl=ze[11]|0,this.Gh=ze[12]|0,this.Gl=ze[13]|0,this.Hh=ze[14]|0,this.Hl=ze[15]|0}}const Ms=xi(()=>new t_),o_=xi(()=>new cc),a_=xi(()=>new i_),c_=xi(()=>new s_),u_=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]),ve=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),q=new Uint32Array(32);function Pr(t,e,r,n,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*r],p=q[2*r+1],d=q[2*n],g=q[2*n+1],y=ec(c,l,o);u=tc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Dx(g,d),Dl:$x(g)},{h:p,l:f}=Bt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:Sr(h,l,24),Bl:Ir(h,l,24)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*r]=f,q[2*r+1]=p,q[2*n]=d,q[2*n+1]=g}function Cr(t,e,r,n,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*r],p=q[2*r+1],d=q[2*n],g=q[2*n+1],y=ec(c,l,o);u=tc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Sr(g,d,16),Dl:Ir(g,d,16)},{h:p,l:f}=Bt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:bi(h,l,63),Bl:mi(h,l,63)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*r]=f,q[2*r+1]=p,q[2*n]=d,q[2*n+1]=g}function l_(t,e={},r,n,i){if(tr(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class h_ extends Ls{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,tr(e),tr(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=vi(this.buffer)}update(e){Ar(this),e=Tt(e),bt(e);const{blockLen:r,buffer:n,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===r&&(Dr(i),this.compress(i,0,!1),Dr(i),this.pos=0);const u=Math.min(r-this.pos,s-c),l=o+c;if(u===r&&!(l%4)&&c+u<s){const h=new Uint32Array(a,l,Math.floor((s-c)/4));Dr(h);for(let f=0;c+r<s;f+=i.length,c+=r)this.length+=r,this.compress(h,f,!1);Dr(h);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){Ar(this),ic(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,mt(this.buffer.subarray(r)),Dr(n),this.compress(n,0,!0),Dr(n);const i=vi(e);this.get().forEach((s,o)=>i[o]=rr(s))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=s,e.finished=i,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class f_ extends h_{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=ve[0]|0,this.v0h=ve[1]|0,this.v1l=ve[2]|0,this.v1h=ve[3]|0,this.v2l=ve[4]|0,this.v2h=ve[5]|0,this.v3l=ve[6]|0,this.v3h=ve[7]|0,this.v4l=ve[8]|0,this.v4h=ve[9]|0,this.v5l=ve[10]|0,this.v5h=ve[11]|0,this.v6l=ve[12]|0,this.v6h=ve[13]|0,this.v7l=ve[14]|0,this.v7h=ve[15]|0,l_(r,e,64,16,16);let{key:n,personalization:i,salt:s}=e,o=0;if(n!==void 0&&(n=Tt(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Tt(s);const a=vi(s);this.v4l^=rr(a[0]),this.v4h^=rr(a[1]),this.v5l^=rr(a[2]),this.v5h^=rr(a[3])}if(i!==void 0){i=Tt(i);const a=vi(i);this.v6l^=rr(a[0]),this.v6h^=rr(a[1]),this.v7l^=rr(a[2]),this.v7h^=rr(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:h,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,r,n,i,s,o,a,c,u,l,h,f,p,d,g,y){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=h|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=g|0,this.v7h=y|0}compress(e,r,n){this.get().forEach((c,u)=>q[u]=c),q.set(ve,16);let{h:i,l:s}=hd(BigInt(this.length));q[24]=ve[8]^s,q[25]=ve[9]^i,n&&(q[28]=~q[28],q[29]=~q[29]);let o=0;const a=u_;for(let c=0;c<12;c++)Pr(0,4,8,12,e,r+2*a[o++]),Cr(0,4,8,12,e,r+2*a[o++]),Pr(1,5,9,13,e,r+2*a[o++]),Cr(1,5,9,13,e,r+2*a[o++]),Pr(2,6,10,14,e,r+2*a[o++]),Cr(2,6,10,14,e,r+2*a[o++]),Pr(3,7,11,15,e,r+2*a[o++]),Cr(3,7,11,15,e,r+2*a[o++]),Pr(0,5,10,15,e,r+2*a[o++]),Cr(0,5,10,15,e,r+2*a[o++]),Pr(1,6,11,12,e,r+2*a[o++]),Cr(1,6,11,12,e,r+2*a[o++]),Pr(2,7,8,13,e,r+2*a[o++]),Cr(2,7,8,13,e,r+2*a[o++]),Pr(3,4,9,14,e,r+2*a[o++]),Cr(3,4,9,14,e,r+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],mt(q)}destroy(){this.destroyed=!0,mt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const d_=Mx(t=>new f_(t)),p_="https://rpc.walletconnect.org/v1";function Dd(t){const e=`Ethereum Signed Message:
20
- ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Zx(r)).toString("hex")}async function g_(t,e,r,n,i,s){switch(r.t){case"eip191":return await y_(t,e,r.s);case"eip1271":return await w_(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function y_(t,e,r){return(await p2({hash:Dd(e),signature:r})).toLowerCase()===t.toLowerCase()}async function w_(t,e,r,n,i,s){const o=Us(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Dd(e)).substring(2),f=a+h+c+l+u,p=await fetch(`${s||p_}/?chainId=${n}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:b_(),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 b_(){return Date.now()+Math.floor(Math.random()*1e3)}function m_(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const n=r[0];if(n===0)throw new Error("No signatures found");const i=1+n*64;if(r.length<i)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return oi.encode(s)}function v_(t){const e=new Uint8Array(Buffer.from(t,"base64")),r=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);n.set(r),n.set(e,r.length);const i=d_(n,{dkLen:32});return oi.encode(i)}function $d(t){const e=new Uint8Array(Ms(E_(t)));return oi.encode(e)}function E_(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 Od(t){const e=Buffer.from(t,"base64"),r=wE(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const n=uE(r),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(n)]),o=c_(s);return mE.encode(o).replace(/=+$/,"")}function uc(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),Buffer.from(e)}function x_(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),r=Buffer.from(t.signed.authInfoBytes,"base64"),n=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(uc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(uc(r.length)),i.push(r),i.push(Buffer.from([26])),i.push(uc(n.length)),i.push(n);const s=Buffer.concat(i),o=Ms(s);return Buffer.from(o).toString("hex").toUpperCase()}var __=Object.defineProperty,S_=Object.defineProperties,I_=Object.getOwnPropertyDescriptors,Bd=Object.getOwnPropertySymbols,A_=Object.prototype.hasOwnProperty,D_=Object.prototype.propertyIsEnumerable,Td=(t,e,r)=>e in t?__(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$_=(t,e)=>{for(var r in e||(e={}))A_.call(e,r)&&Td(t,r,e[r]);if(Bd)for(var r of Bd(e))D_.call(e,r)&&Td(t,r,e[r]);return t},O_=(t,e)=>S_(t,I_(e));const B_="did:pkh:",lc=t=>t?.split(":"),T_=t=>{const e=t&&lc(t);if(e)return t.includes(B_)?e[3]:e[1]},hc=t=>{const e=t&&lc(t);if(e)return e[2]+":"+e[3]},zs=t=>{const e=t&&lc(t);if(e)return e.pop()};async function Pd(t){const{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=Cd(i,i.iss),o=zs(i.iss);return await g_(o,s,n,hc(i.iss),r)}const Cd=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,n=zs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${T_(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,h=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=>`
21
- - ${g}`).join("")}`:void 0,d=qs(t.resources);if(d){const g=Si(d);i=M_(i,g)}return[r,n,"",i,"",s,o,a,c,u,l,h,f,p].filter(g=>g!=null).join(`
22
- `)};function P_(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function C_(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function rn(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(r=>{const n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{const s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function R_(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:N_(e,r,n)}}}function N_(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function Rd(t){return rn(t),`urn:recap:${P_(t).replace(/=/g,"")}`}function Si(t){const e=C_(t.replace("urn:recap:",""));return rn(e),e}function U_(t,e,r){const n=R_(t,e,r);return Rd(n)}function F_(t){return t&&t.includes("urn:recap:")}function k_(t,e){const r=Si(t),n=Si(e),i=L_(r,n);return Rd(i)}function L_(t,e){rn(t),rn(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[i]=O_($_({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function M_(t="",e){rn(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const n=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(i++,`(${i}) '${h}': '${u[h].join("', '")}' for '${a}'.`));n.push(l.join(", ").replace(".,","."))});const s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function Nd(t){var e;const r=Si(t);rn(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Ud(t){const e=Si(t);rn(e);const r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function qs(t){if(!t)return;const e=t?.[t.length-1];return F_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Fd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function fc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function dc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function et(t,...e){if(!Fd(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 kd(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 z_(t,e){et(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Rr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Dn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function q_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const j_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function V_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function pc(t){if(typeof t=="string")t=V_(t);else if(Fd(t))t=gc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function K_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function H_(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}const W_=(t,e)=>{function r(n,...i){if(et(n),!j_)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?et(u):et(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&et(i[1]);const o=e(n,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");et(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,et(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(et(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function Ld(t,e,r=!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(r&&!Y_(e))throw new Error("invalid output, must be aligned");return e}function Md(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function G_(t,e,r){fc(r);const n=new Uint8Array(16),i=q_(n);return Md(i,0,BigInt(e),r),Md(i,8,BigInt(t),r),n}function Y_(t){return t.byteOffset%4===0}function gc(t){return Uint8Array.from(t)}const zd=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),Z_=zd("expand 16-byte k"),J_=zd("expand 32-byte k"),X_=Rr(Z_),Q_=Rr(J_);function te(t,e){return t<<e|t>>>32-e}function yc(t){return t.byteOffset%4===0}const js=64,e8=16,qd=2**32-1,jd=new Uint32Array;function t8(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(js),l=Rr(u),h=yc(i)&&yc(s),f=h?Rr(i):jd,p=h?Rr(s):jd;for(let d=0;d<c;o++){if(t(e,r,n,l,o,a),o>=qd)throw new Error("arx: counter overflow");const g=Math.min(js,c-d);if(h&&g===js){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let _=0,A;_<e8;_++)A=y+_,p[A]=f[A]^l[_];d+=js;continue}for(let y=0,_;y<g;y++)_=d+y,s[_]=i[_]^u[y];d+=g}}function r8(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=K_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return dc(i),dc(o),fc(s),fc(r),(a,c,u,l,h=0)=>{et(a),et(c),et(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),et(l),dc(h),h<0||h>=qd)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=gc(a)),y=Q_;else if(d===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),y=X_,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);yc(c)||p.push(c=gc(c));const _=Rr(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(y,_,Rr(c.subarray(0,16)),_),c=c.subarray(16)}const A=16-i;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){const v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,p.push(c)}const m=Rr(c);return t8(t,y,_,m,u,l,h,o),Dn(...p),l}}const Be=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class n8{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=pc(e),et(e,32);const r=Be(e,0),n=Be(e,2),i=Be(e,4),s=Be(e,6),o=Be(e,8),a=Be(e,10),c=Be(e,12),u=Be(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>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 l=0;l<8;l++)this.pad[l]=Be(e,16+2*l)}process(e,r,n=!1){const i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],_=Be(e,r+0),A=Be(e,r+2),m=Be(e,r+4),v=Be(e,r+6),x=Be(e,r+8),B=Be(e,r+10),R=Be(e,r+12),C=Be(e,r+14);let b=s[0]+(_&8191),T=s[1]+((_>>>13|A<<3)&8191),I=s[2]+((A>>>10|m<<6)&8191),$=s[3]+((m>>>7|v<<9)&8191),P=s[4]+((v>>>4|x<<12)&8191),F=s[5]+(x>>>1&8191),E=s[6]+((x>>>14|B<<2)&8191),w=s[7]+((B>>>11|R<<5)&8191),S=s[8]+((R>>>8|C<<8)&8191),O=s[9]+(C>>>5|i),D=0,N=D+b*a+T*(5*y)+I*(5*g)+$*(5*d)+P*(5*p);D=N>>>13,N&=8191,N+=F*(5*f)+E*(5*h)+w*(5*l)+S*(5*u)+O*(5*c),D+=N>>>13,N&=8191;let U=D+b*c+T*a+I*(5*y)+$*(5*g)+P*(5*d);D=U>>>13,U&=8191,U+=F*(5*p)+E*(5*f)+w*(5*h)+S*(5*l)+O*(5*u),D+=U>>>13,U&=8191;let L=D+b*u+T*c+I*a+$*(5*y)+P*(5*g);D=L>>>13,L&=8191,L+=F*(5*d)+E*(5*p)+w*(5*f)+S*(5*h)+O*(5*l),D+=L>>>13,L&=8191;let j=D+b*l+T*u+I*c+$*a+P*(5*y);D=j>>>13,j&=8191,j+=F*(5*g)+E*(5*d)+w*(5*p)+S*(5*f)+O*(5*h),D+=j>>>13,j&=8191;let V=D+b*h+T*l+I*u+$*c+P*a;D=V>>>13,V&=8191,V+=F*(5*y)+E*(5*g)+w*(5*d)+S*(5*p)+O*(5*f),D+=V>>>13,V&=8191;let K=D+b*f+T*h+I*l+$*u+P*c;D=K>>>13,K&=8191,K+=F*a+E*(5*y)+w*(5*g)+S*(5*d)+O*(5*p),D+=K>>>13,K&=8191;let H=D+b*p+T*f+I*h+$*l+P*u;D=H>>>13,H&=8191,H+=F*c+E*a+w*(5*y)+S*(5*g)+O*(5*d),D+=H>>>13,H&=8191;let Z=D+b*d+T*p+I*f+$*h+P*l;D=Z>>>13,Z&=8191,Z+=F*u+E*c+w*a+S*(5*y)+O*(5*g),D+=Z>>>13,Z&=8191;let Q=D+b*g+T*d+I*p+$*f+P*h;D=Q>>>13,Q&=8191,Q+=F*l+E*u+w*c+S*a+O*(5*y),D+=Q>>>13,Q&=8191;let W=D+b*y+T*g+I*d+$*p+P*f;D=W>>>13,W&=8191,W+=F*h+E*l+w*u+S*c+O*a,D+=W>>>13,W&=8191,D=(D<<2)+D|0,D=D+N|0,N=D&8191,D=D>>>13,U+=D,s[0]=N,s[1]=U,s[2]=L,s[3]=j,s[4]=V,s[5]=K,s[6]=H,s[7]=Z,s[8]=Q,s[9]=W}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[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]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Dn(n)}update(e){kd(this),e=pc(e),et(e);const{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Dn(this.h,this.r,this.buffer,this.pad)}digestInto(e){kd(this),z_(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}function i8(t){const e=(n,i)=>t(i).update(pc(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const s8=i8(t=>new n8(t));function o8(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],_=e[7],A=i,m=r[0],v=r[1],x=r[2],B=o,R=a,C=c,b=u,T=l,I=h,$=f,P=p,F=d,E=g,w=y,S=_,O=A,D=m,N=v,U=x;for(let j=0;j<s;j+=2)B=B+T|0,O=te(O^B,16),F=F+O|0,T=te(T^F,12),B=B+T|0,O=te(O^B,8),F=F+O|0,T=te(T^F,7),R=R+I|0,D=te(D^R,16),E=E+D|0,I=te(I^E,12),R=R+I|0,D=te(D^R,8),E=E+D|0,I=te(I^E,7),C=C+$|0,N=te(N^C,16),w=w+N|0,$=te($^w,12),C=C+$|0,N=te(N^C,8),w=w+N|0,$=te($^w,7),b=b+P|0,U=te(U^b,16),S=S+U|0,P=te(P^S,12),b=b+P|0,U=te(U^b,8),S=S+U|0,P=te(P^S,7),B=B+I|0,U=te(U^B,16),w=w+U|0,I=te(I^w,12),B=B+I|0,U=te(U^B,8),w=w+U|0,I=te(I^w,7),R=R+$|0,O=te(O^R,16),S=S+O|0,$=te($^S,12),R=R+$|0,O=te(O^R,8),S=S+O|0,$=te($^S,7),C=C+P|0,D=te(D^C,16),F=F+D|0,P=te(P^F,12),C=C+P|0,D=te(D^C,8),F=F+D|0,P=te(P^F,7),b=b+T|0,N=te(N^b,16),E=E+N|0,T=te(T^E,12),b=b+T|0,N=te(N^b,8),E=E+N|0,T=te(T^E,7);let L=0;n[L++]=o+B|0,n[L++]=a+R|0,n[L++]=c+C|0,n[L++]=u+b|0,n[L++]=l+T|0,n[L++]=h+I|0,n[L++]=f+$|0,n[L++]=p+P|0,n[L++]=d+F|0,n[L++]=g+E|0,n[L++]=y+w|0,n[L++]=_+S|0,n[L++]=A+O|0,n[L++]=m+D|0,n[L++]=v+N|0,n[L++]=x+U|0}const a8=r8(o8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),c8=new Uint8Array(16),Vd=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(c8.subarray(r))},u8=new Uint8Array(32);function Kd(t,e,r,n,i){const s=t(e,r,u8),o=s8.create(s);i&&Vd(o,i),Vd(o,n);const a=G_(n.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Dn(s,a),c}const l8=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=Ld(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Kd(t,e,r,a,n);return s.set(c,o),Dn(c),s},decrypt(i,s){s=Ld(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Kd(t,e,r,o,n);if(!H_(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),Dn(c),s}}),Hd=W_({blockSize:64,nonceLength:12,tagLength:16},l8(a8));class Wd extends Ls{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,nc(e);const n=Tt(r);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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),mt(s)}update(e){return Ar(this),this.iHash.update(e),this}digestInto(e){Ar(this),bt(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:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Vs=(t,e,r)=>new Wd(t,e).update(r).digest();Vs.create=(t,e)=>new Wd(t,e);function h8(t,e,r){return nc(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Vs(t,Tt(r),Tt(e))}const wc=Uint8Array.from([0]),Gd=Uint8Array.of();function f8(t,e,r,n=32){nc(t),tr(n);const i=t.outputLen;if(n>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/i);r===void 0&&(r=Gd);const o=new Uint8Array(s*i),a=Vs.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)wc[0]=l+1,c.update(l===0?Gd:u).update(r).update(wc).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),mt(u,wc),o.slice(0,n)}const d8=(t,e,r,n,i)=>f8(t,h8(t,e,r),n,i),Ks=Ms,bc=BigInt(0),mc=BigInt(1);function Hs(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Ws(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Yd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?bc:BigInt("0x"+t)}function Gs(t){return Yd(Ei(t))}function Ys(t){return bt(t),Yd(Ei(Uint8Array.from(t).reverse()))}function vc(t,e){return oc(t.toString(16).padStart(e*2,"0"))}function Ec(t,e){return vc(t,e).reverse()}function tt(t,e,r){let n;if(typeof e=="string")try{n=oc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(rc(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}const xc=t=>typeof t=="bigint"&&bc<=t;function p8(t,e,r){return xc(t)&&xc(e)&&xc(r)&&e<=t&&t<r}function _c(t,e,r,n){if(!p8(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function g8(t){let e;for(e=0;t>bc;t>>=mc,e+=1);return e}const Zs=t=>(mc<<BigInt(t))-mc;function y8(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const n=f=>new Uint8Array(f),i=f=>Uint8Array.of(f);let s=n(t),o=n(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...f)=>r(o,s,...f),l=(f=n(0))=>{o=u(i(0),f),s=u(),f.length!==0&&(o=u(i(1),f),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){s=u();const d=s.slice();p.push(d),f+=s.length}return tn(...p)};return(f,p)=>{c(),l(f);let d;for(;!(d=p(h()));)l();return c(),d}}function Js(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function Zd(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const rt=BigInt(0),We=BigInt(1),nn=BigInt(2),w8=BigInt(3),Jd=BigInt(4),Xd=BigInt(5),Qd=BigInt(8);function vt(t,e){const r=t%e;return r>=rt?r:e+r}function Pt(t,e,r){let n=t;for(;e-- >rt;)n*=n,n%=r;return n}function ep(t,e){if(t===rt)throw new Error("invert: expected non-zero number");if(e<=rt)throw new Error("invert: expected positive modulus, got "+e);let r=vt(t,e),n=e,i=rt,s=We;for(;r!==rt;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==We)throw new Error("invert: does not exist");return vt(i,e)}function tp(t,e){const r=(t.ORDER+We)/Jd,n=t.pow(e,r);if(!t.eql(t.sqr(n),e))throw new Error("Cannot find square root");return n}function b8(t,e){const r=(t.ORDER-Xd)/Qd,n=t.mul(e,nn),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,nn),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function m8(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-We,r=0;for(;e%nn===rt;)e/=nn,r++;let n=nn;const i=$n(t);for(;np(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return tp;let s=i.pow(n,e);const o=(e+We)/nn;return function(a,c){if(a.is0(c))return c;if(np(a,c)!==1)throw new Error("Cannot find square root");let u=r,l=a.mul(a.ONE,s),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let p=1,d=a.sqr(h);for(;!a.eql(d,a.ONE);)if(p++,d=a.sqr(d),p===u)throw new Error("Cannot find square root");const g=We<<BigInt(u-p-1),y=a.pow(l,g);u=p,l=a.sqr(y),h=a.mul(h,l),f=a.mul(f,y)}return f}}function v8(t){return t%Jd===w8?tp:t%Qd===Xd?b8:m8(t)}const E8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function x8(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=E8.reduce((n,i)=>(n[i]="function",n),e);return Js(t,r),t}function _8(t,e,r){if(r<rt)throw new Error("invalid exponent, negatives unsupported");if(r===rt)return t.ONE;if(r===We)return e;let n=t.ONE,i=e;for(;r>rt;)r&We&&(n=t.mul(n,i)),i=t.sqr(i),r>>=We;return n}function rp(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),s),n}function np(t,e){const r=(t.ORDER-We)/nn,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function S8(t,e){e!==void 0&&tr(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function $n(t,e,r=!1,n={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const l=e;l.BITS&&(i=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(r=l.isLE)}else typeof e=="number"&&(i=e),n.sqrt&&(s=n.sqrt);const{nBitLength:o,nByteLength:a}=S8(t,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const u=Object.freeze({ORDER:t,isLE:r,BITS:o,BYTES:a,MASK:Zs(o),ZERO:rt,ONE:We,create:l=>vt(l,t),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return rt<=l&&l<t},is0:l=>l===rt,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&We)===We,neg:l=>vt(-l,t),eql:(l,h)=>l===h,sqr:l=>vt(l*l,t),add:(l,h)=>vt(l+h,t),sub:(l,h)=>vt(l-h,t),mul:(l,h)=>vt(l*h,t),pow:(l,h)=>_8(u,l,h),div:(l,h)=>vt(l*ep(h,t),t),sqrN:l=>l*l,addN:(l,h)=>l+h,subN:(l,h)=>l-h,mulN:(l,h)=>l*h,inv:l=>ep(l,t),sqrt:s||(l=>(c||(c=v8(t)),c(u,l))),toBytes:l=>r?Ec(l,a):vc(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return r?Ys(l):Gs(l)},invertBatch:l=>rp(u,l),cmov:(l,h,f)=>f?h:l});return Object.freeze(u)}function ip(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 sp(t){const e=ip(t);return e+Math.ceil(e/2)}function I8(t,e,r=!1){const n=t.length,i=ip(e),s=sp(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Ys(t):Gs(t),a=vt(o,e-We)+We;return r?Ec(a,i):vc(a,i)}const On=BigInt(0),sn=BigInt(1);function Ii(t,e){const r=e.negate();return t?r:e}function A8(t,e,r){const n=e==="pz"?s=>s.pz:s=>s.ez,i=rp(t.Fp,r.map(n));return r.map((s,o)=>s.toAffine(i[o])).map(t.fromAffine)}function op(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Sc(t,e){op(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,s=Zs(t),o=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function ap(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),c=t>>o;a>n&&(a-=s,c+=sn);const u=e*n,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function D8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function $8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Ic=new WeakMap,cp=new WeakMap;function Ac(t){return cp.get(t)||1}function up(t){if(t!==On)throw new Error("invalid wNAF")}function O8(t,e){return{constTimeNegate:Ii,hasPrecomputes(r){return Ac(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>On;)n&sn&&(i=i.add(s)),s=s.double(),n>>=sn;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Sc(n,e),o=[];let a=r,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){let s=t.ZERO,o=t.BASE;const a=Sc(r,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=ap(i,c,a);i=u,h?o=o.add(Ii(p,n[d])):s=s.add(Ii(f,n[l]))}return up(i),{p:s,f:o}},wNAFUnsafe(r,n,i,s=t.ZERO){const o=Sc(r,e);for(let a=0;a<o.windows&&i!==On;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=ap(i,a,o);if(i=c,!l){const f=n[u];s=s.add(h?f.negate():f)}}return up(i),s},getPrecomputes(r,n,i){let s=Ic.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&(typeof i=="function"&&(s=i(s)),Ic.set(n,s))),s},wNAFCached(r,n,i){const s=Ac(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Ac(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){op(n,e),cp.set(r,n),Ic.delete(r)}}}function B8(t,e,r,n){let i=e,s=t.ZERO,o=t.ZERO;for(;r>On||n>On;)r&sn&&(s=s.add(i)),n&sn&&(o=o.add(i)),i=i.double(),r>>=sn,n>>=sn;return{p1:s,p2:o}}function T8(t,e,r,n){D8(r,t),$8(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=g8(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Zs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=n[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(r[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[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 lp(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return x8(e),e}else return $n(t)}function P8(t,e,r={}){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>On))throw new Error(`CURVE.${o} must be positive bigint`)}const n=lp(e.p,r.Fp),i=lp(e.n,r.Fn),s=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const o of s)if(!n.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:n,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const Ai=BigInt(0),Bn=BigInt(1),Xs=BigInt(2);function C8(t){return Js(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function R8(t){const e=C8(t),{P:r,type:n,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||An,u=a?255:448,l=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?Xs**BigInt(254):Xs**BigInt(447),d=a?BigInt(8)*Xs**BigInt(251)-Bn:BigInt(4)*Xs**BigInt(445)-Bn,g=p+d+Bn,y=b=>vt(b,r),_=A(h);function A(b){return Ec(y(b),l)}function m(b){const T=tt("u coordinate",b,l);return a&&(T[31]&=127),y(Ys(T))}function v(b){return Ys(i(tt("scalar",b,l)))}function x(b,T){const I=C(m(T),v(b));if(I===Ai)throw new Error("invalid private or public key received");return A(I)}function B(b){return x(b,_)}function R(b,T,I){const $=y(b*(T-I));return T=y(T-$),I=y(I+$),{x_2:T,x_3:I}}function C(b,T){_c("u",b,Ai,r),_c("scalar",T,p,g);const I=T,$=b;let P=Bn,F=Ai,E=b,w=Bn,S=Ai;for(let D=BigInt(u-1);D>=Ai;D--){const N=I>>D&Bn;S^=N,{x_2:P,x_3:E}=R(S,P,E),{x_2:F,x_3:w}=R(S,F,w),S=N;const U=P+F,L=y(U*U),j=P-F,V=y(j*j),K=L-V,H=E+w,Z=E-w,Q=y(Z*U),W=y(H*j),ae=Q+W,ge=Q-W;E=y(ae*ae),w=y($*y(ge*ge)),P=y(L*V),F=y(K*(L+y(f*K)))}({x_2:P,x_3:E}=R(S,P,E)),{x_2:F,x_3:w}=R(S,F,w);const O=s(F);return y(P*O)}return{scalarMult:x,scalarMultBase:B,getSharedSecret:(b,T)=>x(b,T),getPublicKey:b=>B(b),utils:{randomPrivateKey:()=>c(l)},GuBytes:_.slice()}}BigInt(0);const N8=BigInt(1),hp=BigInt(2),U8=BigInt(3),F8=BigInt(5),k8=BigInt(8),fp={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:k8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function L8(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=fp.p,o=t*t%s*t%s,a=Pt(o,hp,s)*o%s,c=Pt(a,N8,s)*t%s,u=Pt(c,F8,s)*c%s,l=Pt(u,e,s)*u%s,h=Pt(l,r,s)*l%s,f=Pt(h,n,s)*h%s,p=Pt(f,i,s)*f%s,d=Pt(p,i,s)*f%s,g=Pt(d,e,s)*u%s;return{pow_p_5_8:Pt(g,hp,s)*t%s,b2:o}}function M8(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Dc=(()=>{const t=fp.p;return R8({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:n}=L8(e);return vt(Pt(r,U8,t)*n,t)},adjustScalarBytes:M8})})();function dp(t){t.lowS!==void 0&&Hs("lowS",t.lowS),t.prehash!==void 0&&Hs("prehash",t.prehash)}class z8 extends Error{constructor(e=""){super(e)}}const ir={Err:z8,_tlv:{encode:(t,e)=>{const{Err:r}=ir;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=Ws(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Ws(i.length/2|128):"";return Ws(t)+s+i+e},decode(t,e){const{Err:r}=ir;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=ir;if(t<Di)throw new e("integer: negative integers are not allowed");let r=Ws(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=ir;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 Gs(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=ir,i=tt("signature",t),{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=ir,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},Di=BigInt(0),$i=BigInt(1),q8=BigInt(2),Qs=BigInt(3),j8=BigInt(4);function V8(t,e,r){function n(i){const s=t.sqr(i),o=t.mul(s,i);return t.add(t.add(o,t.mul(i,e)),r)}return n}function pp(t,e,r){const{BYTES:n}=t;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=tt("private key",s);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(n);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 ${n}, got ${typeof s}`)}}if(r&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function K8(t,e={}){const{Fp:r,Fn:n}=P8("weierstrass",t,e),{h:i,n:s}=t;Js(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!r.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(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(C,b,T){const{x:I,y:$}=b.toAffine(),P=r.toBytes(I);if(Hs("isCompressed",T),T){a();const F=!r.isOdd($);return tn(gp(F),P)}else return tn(Uint8Array.of(4),P,r.toBytes($))}function u(C){bt(C);const b=r.BYTES,T=b+1,I=2*b+1,$=C.length,P=C[0],F=C.subarray(1);if($===T&&(P===2||P===3)){const E=r.fromBytes(F);if(!r.isValid(E))throw new Error("bad point: is not on curve, wrong x");const w=f(E);let S;try{S=r.sqrt(w)}catch(D){const N=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}a();const O=r.isOdd(S);return(P&1)===1!==O&&(S=r.neg(S)),{x:E,y:S}}else if($===I&&P===4){const E=r.fromBytes(F.subarray(b*0,b*1)),w=r.fromBytes(F.subarray(b*1,b*2));if(!p(E,w))throw new Error("bad point: is not on curve");return{x:E,y:w}}else throw new Error(`bad point: got length ${$}, expected compressed=${T} or uncompressed=${I}`)}const l=e.toBytes||c,h=e.fromBytes||u,f=V8(r,t.a,t.b);function p(C,b){const T=r.sqr(b),I=f(C);return r.eql(T,I)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const d=r.mul(r.pow(t.a,Qs),j8),g=r.mul(r.sqr(t.b),BigInt(27));if(r.is0(r.add(d,g)))throw new Error("bad curve params: a or b");function y(C,b,T=!1){if(!r.isValid(b)||T&&r.is0(b))throw new Error(`bad point coordinate ${C}`);return b}function _(C){if(!(C instanceof x))throw new Error("ProjectivePoint expected")}const A=Zd((C,b)=>{const{px:T,py:I,pz:$}=C;if(r.eql($,r.ONE))return{x:T,y:I};const P=C.is0();b==null&&(b=P?r.ONE:r.inv($));const F=r.mul(T,b),E=r.mul(I,b),w=r.mul($,b);if(P)return{x:r.ZERO,y:r.ZERO};if(!r.eql(w,r.ONE))throw new Error("invZ was invalid");return{x:F,y:E}}),m=Zd(C=>{if(C.is0()){if(e.allowInfinityPoint&&!r.is0(C.py))return;throw new Error("bad point: ZERO")}const{x:b,y:T}=C.toAffine();if(!r.isValid(b)||!r.isValid(T))throw new Error("bad point: x or y not field elements");if(!p(b,T))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(C,b,T,I,$){return T=new x(r.mul(T.px,C),T.py,T.pz),b=Ii(I,b),T=Ii($,T),b.add(T)}class x{constructor(b,T,I){this.px=y("x",b),this.py=y("y",T,!0),this.pz=y("z",I),Object.freeze(this)}static fromAffine(b){const{x:T,y:I}=b||{};if(!b||!r.isValid(T)||!r.isValid(I))throw new Error("invalid affine point");if(b instanceof x)throw new Error("projective point not allowed");return r.is0(T)&&r.is0(I)?x.ZERO:new x(T,I,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(b){return A8(x,"pz",b)}static fromBytes(b){return bt(b),x.fromHex(b)}static fromHex(b){const T=x.fromAffine(h(tt("pointHex",b)));return T.assertValidity(),T}static fromPrivateKey(b){const T=pp(n,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return x.BASE.multiply(T(b))}static msm(b,T){return T8(x,n,b,T)}precompute(b=8,T=!0){return R.setWindowSize(this,b),T||this.multiply(Qs),this}_setWindowSize(b){this.precompute(b)}assertValidity(){m(this)}hasEvenY(){const{y:b}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(b)}equals(b){_(b);const{px:T,py:I,pz:$}=this,{px:P,py:F,pz:E}=b,w=r.eql(r.mul(T,E),r.mul(P,$)),S=r.eql(r.mul(I,E),r.mul(F,$));return w&&S}negate(){return new x(this.px,r.neg(this.py),this.pz)}double(){const{a:b,b:T}=t,I=r.mul(T,Qs),{px:$,py:P,pz:F}=this;let E=r.ZERO,w=r.ZERO,S=r.ZERO,O=r.mul($,$),D=r.mul(P,P),N=r.mul(F,F),U=r.mul($,P);return U=r.add(U,U),S=r.mul($,F),S=r.add(S,S),E=r.mul(b,S),w=r.mul(I,N),w=r.add(E,w),E=r.sub(D,w),w=r.add(D,w),w=r.mul(E,w),E=r.mul(U,E),S=r.mul(I,S),N=r.mul(b,N),U=r.sub(O,N),U=r.mul(b,U),U=r.add(U,S),S=r.add(O,O),O=r.add(S,O),O=r.add(O,N),O=r.mul(O,U),w=r.add(w,O),N=r.mul(P,F),N=r.add(N,N),O=r.mul(N,U),E=r.sub(E,O),S=r.mul(N,D),S=r.add(S,S),S=r.add(S,S),new x(E,w,S)}add(b){_(b);const{px:T,py:I,pz:$}=this,{px:P,py:F,pz:E}=b;let w=r.ZERO,S=r.ZERO,O=r.ZERO;const D=t.a,N=r.mul(t.b,Qs);let U=r.mul(T,P),L=r.mul(I,F),j=r.mul($,E),V=r.add(T,I),K=r.add(P,F);V=r.mul(V,K),K=r.add(U,L),V=r.sub(V,K),K=r.add(T,$);let H=r.add(P,E);return K=r.mul(K,H),H=r.add(U,j),K=r.sub(K,H),H=r.add(I,$),w=r.add(F,E),H=r.mul(H,w),w=r.add(L,j),H=r.sub(H,w),O=r.mul(D,K),w=r.mul(N,j),O=r.add(w,O),w=r.sub(L,O),O=r.add(L,O),S=r.mul(w,O),L=r.add(U,U),L=r.add(L,U),j=r.mul(D,j),K=r.mul(N,K),L=r.add(L,j),j=r.sub(U,j),j=r.mul(D,j),K=r.add(K,j),U=r.mul(L,K),S=r.add(S,U),U=r.mul(H,K),w=r.mul(V,w),w=r.sub(w,U),U=r.mul(V,L),O=r.mul(H,O),O=r.add(O,U),new x(w,S,O)}subtract(b){return this.add(b.negate())}is0(){return this.equals(x.ZERO)}multiply(b){const{endo:T}=e;if(!n.isValidNot0(b))throw new Error("invalid scalar: out of range");let I,$;const P=F=>R.wNAFCached(this,F,x.normalizeZ);if(T){const{k1neg:F,k1:E,k2neg:w,k2:S}=T.splitScalar(b),{p:O,f:D}=P(E),{p:N,f:U}=P(S);$=D.add(U),I=v(T.beta,O,N,F,w)}else{const{p:F,f:E}=P(b);I=F,$=E}return x.normalizeZ([I,$])[0]}multiplyUnsafe(b){const{endo:T}=e,I=this;if(!n.isValid(b))throw new Error("invalid scalar: out of range");if(b===Di||I.is0())return x.ZERO;if(b===$i)return I;if(R.hasPrecomputes(this))return this.multiply(b);if(T){const{k1neg:$,k1:P,k2neg:F,k2:E}=T.splitScalar(b),{p1:w,p2:S}=B8(x,I,P,E);return v(T.beta,w,S,$,F)}else return R.wNAFCachedUnsafe(I,b)}multiplyAndAddUnsafe(b,T,I){const $=this.multiplyUnsafe(T).add(b.multiplyUnsafe(I));return $.is0()?void 0:$}toAffine(b){return A(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return i===$i?!0:b?b(x,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:b}=e;return i===$i?this:b?b(x,this):this.multiplyUnsafe(i)}toBytes(b=!0){return Hs("isCompressed",b),this.assertValidity(),l(x,this,b)}toRawBytes(b=!0){return this.toBytes(b)}toHex(b=!0){return Ei(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}x.BASE=new x(t.Gx,t.Gy,r.ONE),x.ZERO=new x(r.ZERO,r.ONE,r.ZERO),x.Fp=r,x.Fn=n;const B=n.BITS,R=O8(x,e.endo?Math.ceil(B/2):B);return x}function gp(t){return Uint8Array.of(t?2:3)}function H8(t,e,r={}){Js(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=e.randomBytes||An,i=e.hmac||((I,...$)=>Vs(e.hash,I,tn(...$))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o;function u(I){const $=a>>$i;return I>$}function l(I){return u(I)?o.neg(I):I}function h(I,$){if(!o.isValidNot0($))throw new Error(`invalid signature ${I}: out of range 1..CURVE.n`)}class f{constructor($,P,F){h("r",$),h("s",P),this.r=$,this.s=P,F!=null&&(this.recovery=F),Object.freeze(this)}static fromCompact($){const P=o.BYTES,F=tt("compactSignature",$,P*2);return new f(o.fromBytes(F.subarray(0,P)),o.fromBytes(F.subarray(P,P*2)))}static fromDER($){const{r:P,s:F}=ir.toSig(tt("DER",$));return new f(P,F)}assertValidity(){}addRecoveryBit($){return new f(this.r,this.s,$)}recoverPublicKey($){const P=s.ORDER,{r:F,s:E,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*q8<P&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=w===2||w===3?F+a:F;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const O=s.toBytes(S),D=t.fromHex(tn(gp((w&1)===0),O)),N=o.inv(S),U=m(tt("msgHash",$)),L=o.create(-U*N),j=o.create(E*N),V=t.BASE.multiplyUnsafe(L).add(D.multiplyUnsafe(j));if(V.is0())throw new Error("point at infinify");return V.assertValidity(),V}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o.neg(this.s),this.recovery):this}toBytes($){if($==="compact")return tn(o.toBytes(this.r),o.toBytes(this.s));if($==="der")return oc(ir.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ei(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ei(this.toBytes("compact"))}}const p=pp(o,r.allowedPrivateKeyLengths,r.wrapPrivateKey),d={isValidPrivateKey(I){try{return p(I),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const I=a;return I8(n(sp(I)),I)},precompute(I=8,$=t.BASE){return $.precompute(I,!1)}};function g(I,$=!0){return t.fromPrivateKey(I).toBytes($)}function y(I){if(typeof I=="bigint")return!1;if(I instanceof t)return!0;const $=tt("key",I).length,P=s.BYTES,F=P+1,E=2*P+1;if(!(r.allowedPrivateKeyLengths||o.BYTES===F))return $===F||$===E}function _(I,$,P=!0){if(y(I)===!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(I)).toBytes(P)}const A=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const $=Gs(I),P=I.length*8-c;return P>0?$>>BigInt(P):$},m=e.bits2int_modN||function(I){return o.create(A(I))},v=Zs(c);function x(I){return _c("num < 2^"+c,I,Di,v),o.toBytes(I)}function B(I,$,P=R){if(["recovered","canonical"].some(V=>V in P))throw new Error("sign() legacy options not supported");const{hash:F}=e;let{lowS:E,prehash:w,extraEntropy:S}=P;E==null&&(E=!0),I=tt("msgHash",I),dp(P),w&&(I=tt("prehashed msgHash",F(I)));const O=m(I),D=p($),N=[x(D),x(O)];if(S!=null&&S!==!1){const V=S===!0?n(s.BYTES):S;N.push(tt("extraEntropy",V))}const U=tn(...N),L=O;function j(V){const K=A(V);if(!o.isValidNot0(K))return;const H=o.inv(K),Z=t.BASE.multiply(K).toAffine(),Q=o.create(Z.x);if(Q===Di)return;const W=o.create(H*o.create(L+Q*D));if(W===Di)return;let ae=(Z.x===Q?0:2)|Number(Z.y&$i),ge=W;return E&&u(W)&&(ge=l(W),ae^=1),new f(Q,ge,ae)}return{seed:U,k2sig:j}}const R={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function b(I,$,P=R){const{seed:F,k2sig:E}=B(I,$,P);return y8(e.hash.outputLen,o.BYTES,i)(F,E)}t.BASE.precompute(8);function T(I,$,P,F=C){const E=I;$=tt("msgHash",$),P=tt("publicKey",P),dp(F);const{lowS:w,prehash:S,format:O}=F;if("strict"in F)throw new Error("options.strict was renamed to lowS");if(O!==void 0&&!["compact","der","js"].includes(O))throw new Error('format must be "compact", "der" or "js"');const D=typeof E=="string"||rc(E),N=!D&&!O&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!D&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,L;try{if(N)if(O===void 0||O==="js")U=new f(E.r,E.s);else throw new Error("invalid format");if(D){try{O!=="compact"&&(U=f.fromDER(E))}catch(ae){if(!(ae instanceof ir.Err))throw ae}!U&&O!=="der"&&(U=f.fromCompact(E))}L=t.fromHex(P)}catch{return!1}if(!U||w&&U.hasHighS())return!1;S&&($=e.hash($));const{r:j,s:V}=U,K=m($),H=o.inv(V),Z=o.create(K*H),Q=o.create(j*H),W=t.BASE.multiplyUnsafe(Z).add(L.multiplyUnsafe(Q));return W.is0()?!1:o.create(W.x)===j}return Object.freeze({getPublicKey:g,getSharedSecret:_,sign:b,verify:T,utils:d,Point:t,Signature:f})}function W8(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},r=t.Fp,n=$n(e.n,t.nBitLength),i={Fp:r,Fn:n,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:i}}function G8(t){const{CURVE:e,curveOpts:r}=W8(t),n={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,ecdsaOpts:n}}function Y8(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function Z8(t){const{CURVE:e,curveOpts:r,ecdsaOpts:n}=G8(t),i=K8(e,r),s=H8(i,n,r);return Y8(t,s)}function $c(t,e){const r=n=>Z8({...t,hash:n});return{...r(e),create:r}}const yp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},wp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},bp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},J8=$n(yp.p),X8=$n(wp.p),Q8=$n(bp.p),eS=$c({...yp,Fp:J8,lowS:!1},Ms);$c({...wp,Fp:X8,lowS:!1},a_),$c({...bp,Fp:Q8,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},o_);const tS=eS,mp="base10",Ge="base16",nt="base64pad",Nr="base64url",Oi="utf8",vp=0,sr=1,Bi=2,rS=0,Ep=1,Ti=12,Oc=32;function nS(){const t=Dc.utils.randomPrivateKey(),e=Dc.getPublicKey(t);return{privateKey:Qe(t,Ge),publicKey:Qe(e,Ge)}}function Bc(){const t=An(Oc);return Qe(t,Ge)}function iS(t,e){const r=Dc.getSharedSecret(wt(t,Ge),wt(e,Ge)),n=d8(Ks,r,void 0,void 0,Oc);return Qe(n,Ge)}function eo(t){const e=Ks(wt(t,Ge));return Qe(e,Ge)}function Et(t){const e=Ks(wt(t,Oi));return Qe(e,Ge)}function xp(t){return wt(`${t}`,mp)}function on(t){return Number(Qe(t,mp))}function _p(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Sp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function sS(t){const e=xp(typeof t.type<"u"?t.type:vp);if(on(e)===sr&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?wt(t.senderPublicKey,Ge):void 0,n=typeof t.iv<"u"?wt(t.iv,Ge):An(Ti),i=wt(t.symKey,Ge),s=Hd(i,n).encrypt(wt(t.message,Oi)),o=Ip({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===Nr?_p(o):o}function oS(t){const e=wt(t.symKey,Ge),{sealed:r,iv:n}=Pi({encoded:t.encoded,encoding:t.encoding}),i=Hd(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return Qe(i,Oi)}function aS(t,e){const r=xp(Bi),n=An(Ti),i=wt(t,Oi),s=Ip({type:r,sealed:i,iv:n});return e===Nr?_p(s):s}function cS(t,e){const{sealed:r}=Pi({encoded:t,encoding:e});return Qe(r,Oi)}function Ip(t){if(on(t.type)===Bi)return Qe(fi([t.type,t.sealed]),nt);if(on(t.type)===sr){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Qe(fi([t.type,t.senderPublicKey,t.iv,t.sealed]),nt)}return Qe(fi([t.type,t.iv,t.sealed]),nt)}function Pi(t){const e=(t.encoding||nt)===Nr?Sp(t.encoded):t.encoded,r=wt(e,nt),n=r.slice(rS,Ep),i=Ep;if(on(n)===sr){const c=i+Oc,u=c+Ti,l=r.slice(i,c),h=r.slice(c,u),f=r.slice(u);return{type:n,sealed:f,iv:h,senderPublicKey:l}}if(on(n)===Bi){const c=r.slice(i),u=An(Ti);return{type:n,sealed:c,iv:u}}const s=i+Ti,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function uS(t,e){const r=Pi({encoded:t,encoding:e?.encoding});return Ap({type:on(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Qe(r.senderPublicKey,Ge):void 0,receiverPublicKey:e?.receiverPublicKey})}function Ap(t){const e=t?.type||vp;if(e===sr){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 Dp(t){return t.type===sr&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function $p(t){return t.type===Bi}function lS(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return fi([new Uint8Array([4]),e,r])}function hS(t,e){const[r,n,i]=t.split("."),s=Buffer.from(Sp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=Ks(c),l=lS(e);if(!tS.verify(fi([o,a]),u,l))throw new Error("Invalid signature");return Yo(t).payload}const fS="irn";function to(t){return t?.relay||{protocol:fS}}function Tn(t){const e=z3[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function dS(t,e="-"){const r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){const s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Op(t){if(!t.includes("wc:")){const u=ud(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(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(s),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:pS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:dS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function pS(t){return t.startsWith("//")?t.substring(2):t}function gS(t,e="-"){const r="relay",n={};return Object.keys(t).forEach(i=>{const s=i,o=r+e+s;t[s]&&(n[o]=t[s])}),n}function Bp(t){const e=new URLSearchParams,r=gS(t.relay);Object.keys(r).sort().forEach(i=>{e.set(i,r[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const n=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${n}`}function ro(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var yS=Object.defineProperty,wS=Object.defineProperties,bS=Object.getOwnPropertyDescriptors,Tp=Object.getOwnPropertySymbols,mS=Object.prototype.hasOwnProperty,vS=Object.prototype.propertyIsEnumerable,Pp=(t,e,r)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ES=(t,e)=>{for(var r in e||(e={}))mS.call(e,r)&&Pp(t,r,e[r]);if(Tp)for(var r of Tp(e))vS.call(e,r)&&Pp(t,r,e[r]);return t},xS=(t,e)=>wS(t,bS(e));function Pn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function _S(t){const e=[];return Object.values(t).forEach(r=>{e.push(...Pn(r.accounts))}),e}function SS(t,e){const r=[];return Object.values(t).forEach(n=>{Pn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function IS(t,e){const r=[];return Object.values(t).forEach(n=>{Pn(n.accounts).includes(e)&&r.push(...n.events)}),r}function Cp(t){return t.includes(":")}function AS(t){return Cp(t)?t.split(":")[0]:t}function Rp(t){var e,r,n;const i={};if(!Ci(t))return i;for(const[s,o]of Object.entries(t)){const a=Cp(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=AS(s);i[l]=xS(ES({},i[l]),{chains:en(a,(e=i[l])==null?void 0:e.chains),methods:en(c,(r=i[l])==null?void 0:r.methods),events:en(u,(n=i[l])==null?void 0:n.events)})}return i}function DS(t){const e={};return t?.forEach(r=>{var n;const[i,s]=r.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(r),(n=e[i].chains)==null||n.push(`${i}:${s}`)}),e}function Np(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=DS(e);for(const[n,i]of Object.entries(r))i.methods?i.methods=en(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}function $S(t,e){var r,n,i,s,o,a;const c=Rp(t),u=Rp(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:en((r=c[f])==null?void 0:r.chains,(n=u[f])==null?void 0:n.chains),methods:en((i=c[f])==null?void 0:i.methods,(s=u[f])==null?void 0:s.methods),events:en((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}const OS={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}},BS={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 z(t,e){const{message:r,code:n}=BS[t];return{message:e?`${r} ${e}`:r,code:n}}function fe(t,e){const{message:r,code:n}=OS[t];return{message:e?`${r} ${e}`:r,code:n}}function Cn(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ci(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ee(t){return typeof t>"u"}function ye(t,e){return e&&Ee(t)?!0:typeof t=="string"&&!!t.trim().length}function Tc(t,e){return e&&Ee(t)?!0:typeof t=="number"&&!isNaN(t)}function TS(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return Xr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Pn(a),h=r[o];(!Xr(Xf(o,h),l)||!Xr(h.methods,c)||!Xr(h.events,u))&&(s=!1)}),s):!1}function no(t){return ye(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function PS(t){if(ye(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&no(r)}}return!1}function CS(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(ye(t,!1)){if(e(t))return!0;const r=ud(t);return e(r)}}catch{}return!1}function RS(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function NS(t){return t?.topic}function US(t,e){let r=null;return ye(t?.publicKey,!1)||(r=z("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function Up(t){let e=!0;return Cn(t)?t.length&&(e=t.every(r=>ye(r,!1))):e=!1,e}function FS(t,e,r){let n=null;return Cn(e)&&e.length?e.forEach(i=>{n||no(i)||(n=fe("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):no(t)||(n=fe("UNSUPPORTED_CHAINS",`${r}, 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"] }`)),n}function kS(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=FS(i,Xf(i,s),`${e} ${r}`);o&&(n=o)}),n}function LS(t,e){let r=null;return Cn(t)?t.forEach(n=>{r||PS(n)||(r=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function MS(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=LS(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function zS(t,e){let r=null;return Up(t?.methods)?Up(t?.events)||(r=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function Fp(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=zS(n,`${e}, namespace`);i&&(r=i)}),r}function qS(t,e,r){let n=null;if(t&&Ci(t)){const i=Fp(t,e);i&&(n=i);const s=kS(t,e,r);s&&(n=s)}else n=z("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function Pc(t,e){let r=null;if(t&&Ci(t)){const n=Fp(t,e);n&&(r=n);const i=MS(t,e);i&&(r=i)}else r=z("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function kp(t){return ye(t.protocol,!0)}function jS(t,e){let r=!1;return e&&!t?r=!0:t&&Cn(t)&&t.length&&t.forEach(n=>{r=kp(n)}),r}function VS(t){return typeof t=="number"}function it(t){return typeof t<"u"&&typeof t!==null}function KS(t){return!(!t||typeof t!="object"||!t.code||!Tc(t.code,!1)||!t.message||!ye(t.message,!1))}function HS(t){return!(Ee(t)||!ye(t.method,!1))}function WS(t){return!(Ee(t)||Ee(t.result)&&Ee(t.error)||!Tc(t.id,!1)||!ye(t.jsonrpc,!1))}function GS(t){return!(Ee(t)||!ye(t.name,!1))}function Lp(t,e){return!(!no(e)||!_S(t).includes(e))}function YS(t,e,r){return ye(r,!1)?SS(t,e).includes(r):!1}function ZS(t,e,r){return ye(r,!1)?IS(t,e).includes(r):!1}function Mp(t,e,r){let n=null;const i=JS(t),s=XS(e),o=Object.keys(i),a=Object.keys(s),c=zp(Object.keys(t)),u=zp(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(n=z("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
14
+ ***************************************************************************** */var mo=function(t,e){return mo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},mo(t,e)};function N0(t,e){mo(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var vo=function(){return vo=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},vo.apply(this,arguments)};function F0(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function k0(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function L0(t,e){return function(r,n){e(r,n,t)}}function M0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function q0(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(f){o(f)}}function c(l){try{u(n.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function j0(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function z0(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function K0(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Eo(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Au(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function V0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Au(arguments[e]));return t}function H0(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Hn(t){return this instanceof Hn?(this.v=t,this):new Hn(t)}function W0(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(n[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof Hn?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function G0(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Hn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Z0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Eo=="function"?Eo(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function Y0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function X0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function J0(t){return t&&t.__esModule?t:{default:t}}function Q0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function ey(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var ty=Object.freeze({__proto__:null,__extends:N0,get __assign(){return vo},__rest:F0,__decorate:k0,__param:L0,__metadata:M0,__awaiter:q0,__generator:j0,__createBinding:z0,__exportStar:K0,__values:Eo,__read:Au,__spread:V0,__spreadArrays:H0,__await:Hn,__asyncGenerator:W0,__asyncDelegator:G0,__asyncValues:Z0,__makeTemplateObject:Y0,__importStar:X0,__importDefault:J0,__classPrivateFieldGet:Q0,__classPrivateFieldSet:ey}),Gi=gu(ty),xo={},Wn={},$u;function ry(){if($u)return Wn;$u=1,Object.defineProperty(Wn,"__esModule",{value:!0}),Wn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return Wn.delay=t,Wn}var Lr={},_o={},Mr={},Ou;function ny(){return Ou||(Ou=1,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.ONE_THOUSAND=Mr.ONE_HUNDRED=void 0,Mr.ONE_HUNDRED=100,Mr.ONE_THOUSAND=1e3),Mr}var So={},Bu;function iy(){return Bu||(Bu=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}(So)),So}var Tu;function Pu(){return Tu||(Tu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(ny(),t),e.__exportStar(iy(),t)}(_o)),_o}var Ru;function sy(){if(Ru)return Lr;Ru=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.fromMiliseconds=Lr.toMiliseconds=void 0;const t=Pu();function e(n){return n*t.ONE_THOUSAND}Lr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return Lr.fromMiliseconds=r,Lr}var Cu;function oy(){return Cu||(Cu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(ry(),t),e.__exportStar(sy(),t)}(xo)),xo}var pn={},Uu;function ay(){if(Uu)return pn;Uu=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const n=this.get(r);if(typeof n.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const i=Date.now()-n.started;this.timestamps.set(r,{started:n.started,elapsed:i})}get(r){const n=this.timestamps.get(r);if(typeof n>"u")throw new Error(`No timestamp found for label: ${r}`);return n}elapsed(r){const n=this.get(r);return n.elapsed||Date.now()-n.started}}return pn.Watch=t,pn.default=t,pn}var Io={},Gn={},Nu;function cy(){if(Nu)return Gn;Nu=1,Object.defineProperty(Gn,"__esModule",{value:!0}),Gn.IWatch=void 0;class t{}return Gn.IWatch=t,Gn}var Fu;function uy(){return Fu||(Fu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Gi.__exportStar(cy(),t)}(Io)),Io}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Gi;e.__exportStar(oy(),t),e.__exportStar(ay(),t),e.__exportStar(uy(),t),e.__exportStar(Pu(),t)})(M);class qr{}class ly extends qr{constructor(e){super()}}const ku=M.FIVE_SECONDS,jr={pulse:"heartbeat_pulse"};class Do extends ly{constructor(e){super(e),this.events=new Ce.exports.EventEmitter,this.interval=ku,this.interval=e?.interval||ku}static async init(e){const r=new Do(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(jr.pulse)}}const hy=/"(?:_|\\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*:/,fy=/"(?: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*:/,dy=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function py(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){gy(t);return}return e}function gy(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Zi(t,e={}){if(typeof t!="string")return t;const r=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return r.slice(1,-1);if(r.length<=9){const n=r.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;if(n==="undefined")return;if(n==="null")return null;if(n==="nan")return Number.NaN;if(n==="infinity")return Number.POSITIVE_INFINITY;if(n==="-infinity")return Number.NEGATIVE_INFINITY}if(!dy.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(hy.test(t)||fy.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,py)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}function yy(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return yy(t(...e))}catch(r){return Promise.reject(r)}}function wy(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function by(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Yi(t){if(wy(t))return String(t);if(by(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Yi(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function Lu(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const Ao="base64:";function my(t){if(typeof t=="string")return t;Lu();const e=Buffer.from(t).toString("base64");return Ao+e}function vy(t){return typeof t!="string"||!t.startsWith(Ao)?t:(Lu(),Buffer.from(t.slice(Ao.length),"base64"))}function Xe(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Ey(...t){return Xe(t.join(":"))}function Xi(t){return t=Xe(t),t?t+":":""}function c$(t){return t}const xy="memory",_y=()=>{const t=new Map;return{name:xy,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Sy(t={}){const e={mounts:{"":t.driver||_y()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},n=(u,l)=>e.mountpoints.filter(f=>f.startsWith(u)||l&&u.startsWith(f)).map(f=>({relativeBase:u.length>f.length?u.slice(f.length):void 0,mountpoint:f,driver:e.mounts[f]})),i=(u,l)=>{if(e.watching){l=Xe(l);for(const f of e.watchListeners)f(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Mu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,f)=>{const h=new Map,d=p=>{let g=h.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},h.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",w=Xe(g?p:p.key),S=g?void 0:p.value,D=g||!p.options?l:{...l,...p.options},E=r(w);d(E).items.push({key:w,value:S,relativeKey:E.relativeKey,options:D})}return Promise.all([...h.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=Xe(u);const{relativeKey:f,driver:h}=r(u);return xe(h.hasItem,f,l)},getItem(u,l={}){u=Xe(u);const{relativeKey:f,driver:h}=r(u);return xe(h.getItem,f,l).then(d=>Zi(d))},getItems(u,l){return a(u,l,f=>f.driver.getItems?xe(f.driver.getItems,f.items.map(h=>({key:h.relativeKey,options:h.options})),l).then(h=>h.map(d=>({key:Ey(f.base,d.key),value:Zi(d.value)}))):Promise.all(f.items.map(h=>xe(f.driver.getItem,h.relativeKey,h.options).then(d=>({key:h.key,value:Zi(d)})))))},getItemRaw(u,l={}){u=Xe(u);const{relativeKey:f,driver:h}=r(u);return h.getItemRaw?xe(h.getItemRaw,f,l):xe(h.getItem,f,l).then(d=>vy(d))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=Xe(u);const{relativeKey:h,driver:d}=r(u);d.setItem&&(await xe(d.setItem,h,Yi(l),f),d.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return xe(f.driver.setItems,f.items.map(h=>({key:h.relativeKey,value:Yi(h.value),options:h.options})),l);f.driver.setItem&&await Promise.all(f.items.map(h=>xe(f.driver.setItem,h.relativeKey,Yi(h.value),h.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=Xe(u);const{relativeKey:h,driver:d}=r(u);if(d.setItemRaw)await xe(d.setItemRaw,h,l,f);else if(d.setItem)await xe(d.setItem,h,my(l),f);else return;d.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Xe(u);const{relativeKey:f,driver:h}=r(u);h.removeItem&&(await xe(h.removeItem,f,l),(l.removeMeta||l.removeMata)&&await xe(h.removeItem,f+"$",l),h.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Xe(u);const{relativeKey:f,driver:h}=r(u),d=Object.create(null);if(h.getMeta&&Object.assign(d,await xe(h.getMeta,f,l)),!l.nativeOnly){const p=await xe(h.getItem,f+"$",l).then(g=>Zi(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Xi(u);const f=n(u,!0);let h=[];const d=[];for(const p of f){const g=await xe(p.driver.getKeys,p.relativeBase,l);for(const w of g){const S=p.mountpoint+Xe(w);h.some(D=>S.startsWith(D))||d.push(S)}h=[p.mountpoint,...h.filter(w=>!w.startsWith(p.mountpoint))]}return u?d.filter(p=>p.startsWith(u)&&p[p.length-1]!=="$"):d.filter(p=>p[p.length-1]!=="$")},async clear(u,l={}){u=Xi(u),await Promise.all(n(u,!1).map(async f=>{if(f.driver.clear)return xe(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const h=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(h.map(d=>f.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>qu(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=Xi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,h)=>h.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(Mu(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=Xi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),l&&await qu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=Xe(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Xe(u),n(u,l.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,f={})=>c.setItem(u,l,f),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function Mu(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function qu(t){typeof t.dispose=="function"&&await xe(t.dispose)}function zr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function ju(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const n=zr(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}let $o;function Zn(){return $o||($o=ju("keyval-store","keyval")),$o}function zu(t,e=Zn()){return e("readonly",r=>zr(r.get(t)))}function Iy(t,e,r=Zn()){return r("readwrite",n=>(n.put(e,t),zr(n.transaction)))}function Dy(t,e=Zn()){return e("readwrite",r=>(r.delete(t),zr(r.transaction)))}function Ay(t=Zn()){return t("readwrite",e=>(e.clear(),zr(e.transaction)))}function $y(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},zr(t.transaction)}function Oy(t=Zn()){return t("readonly",e=>{if(e.getAllKeys)return zr(e.getAllKeys());const r=[];return $y(e,n=>r.push(n.key)).then(()=>r)})}const By=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Ty=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,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(n,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function gn(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Ty(t)}catch{return t}}function Kr(t){return typeof t=="string"?t:By(t)||""}const Py="idb-keyval";var Ry=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=ju(t.dbName,t.storeName)),{name:Py,options:t,async hasItem(i){return!(typeof await zu(r(i),n)>"u")},async getItem(i){return await zu(r(i),n)??null},setItem(i,s){return Iy(r(i),s,n)},removeItem(i){return Dy(r(i),n)},getKeys(){return Oy(n)},clear(){return Ay(n)}}};const Cy="WALLET_CONNECT_V2_INDEXED_DB",Uy="keyvaluestorage";class Ny{constructor(){this.indexedDb=Sy({driver:Ry({dbName:Cy,storeName:Uy})})}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 r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Kr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Ji={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,n){this[r]=String(n)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(n){r[n]=void 0,delete r[n]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Oo<"u"&&Oo.localStorage?Ji.exports=Oo.localStorage:typeof window<"u"&&window.localStorage?Ji.exports=window.localStorage:Ji.exports=new e})();function Fy(t){var e;return[t[0],gn((e=t[1])!=null?e:"")]}class ky{constructor(){this.localStorage=Ji.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Fy)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return gn(r)}async setItem(e,r){this.localStorage.setItem(e,Kr(r))}async removeItem(e){this.localStorage.removeItem(e)}}const Ly="wc_storage_version",Ku=1,My=async(t,e,r)=>{const n=Ly,i=await e.getItem(n);if(i&&i>=Ku){r(e);return}const s=await t.getKeys();if(!s.length){r(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(n,Ku),r(e),qy(t,o)},qy=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class jy{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new ky;this.storage=e;try{const r=new Ny;My(e,r,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,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}}function zy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Ky=Vy;function Vy(t,e,r){var n=r&&r.stringify||zy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=n(t);for(var a=1;a<s;a++)o[a]=n(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,f=-1,h=t&&t.length||0,d=0;d<h;){if(t.charCodeAt(d)===37&&d+1<h){switch(f=f>-1?f:0,t.charCodeAt(d+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Number(e[l]),f=d+2,d++;break;case 105:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Math.floor(Number(e[l])),f=d+2,d++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<d&&(u+=t.slice(f,d));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=d+2,d++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=d+2,d++;break}u+=n(e[l]),f=d+2,d++;break;case 115:if(l>=c)break;f<d&&(u+=t.slice(f,d)),u+=String(e[l]),f=d+2,d++;break;case 37:f<d&&(u+=t.slice(f,d)),u+="%",f=d+2,d++,l--;break}++l}++d}return f===-1?t:(f<h&&(u+=t.slice(f)),u)}const Vu=Ky;var Wt=Ut;const Yn=tw().console||{},Hy={mapHttpRequest:es,mapHttpResponse:es,wrapRequestSerializer:To,wrapResponseSerializer:To,wrapErrorSerializer:To,req:es,res:es,err:Xy};function Wy(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Ut(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 r=t.browser.write||Yn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=Wy(t.browser.serialize,n);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof r=="function"&&(r.error=r.fatal=r.warn=r.info=r.debug=r.trace=r),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(r);c.log||(c.log=Xn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:f,set:h});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:Jy(t)};c.levels=Ut.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=Xn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=d,e&&(c._logEvent=Bo());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function f(){return this._level}function h(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,yn(u,c,"error","log"),yn(u,c,"fatal","error"),yn(u,c,"warn","error"),yn(u,c,"info","log"),yn(u,c,"debug","log"),yn(u,c,"trace","log")}function d(p,g){if(!p)throw new Error("missing bindings for child Pino");g=g||{},i&&p.serializers&&(g.serializers=p.serializers);const w=g.serializers;if(i&&w){var S=Object.assign({},n,w),D=t.browser.serialize===!0?Object.keys(S):i;delete p.serializers,Qi([p],D,S,this._stdErrSerialize)}function E(O){this._childLevel=(O._childLevel|0)+1,this.error=wn(O,p,"error"),this.fatal=wn(O,p,"fatal"),this.warn=wn(O,p,"warn"),this.info=wn(O,p,"info"),this.debug=wn(O,p,"debug"),this.trace=wn(O,p,"trace"),S&&(this.serializers=S,this._serialize=D),e&&(this._logEvent=Bo([].concat(O._logEvent.bindings,p)))}return E.prototype=this,new E(this)}return c}Ut.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"}},Ut.stdSerializers=Hy,Ut.stdTimeFunctions=Object.assign({},{nullTime:Hu,epochTime:Wu,unixTime:Qy,isoTime:ew});function yn(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?Xn:i[r]?i[r]:Yn[r]||Yn[n]||Xn,Gy(t,e,r)}function Gy(t,e,r){!t.transmit&&e[r]===Xn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Yn?Yn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Qi(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,Zy(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Ut.levels.values[u],f=Ut.levels.values[r];if(f<l)return;Yy(this,{ts:s,methodLevel:r,methodValue:f,transmitLevel:u,transmitValue:Ut.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function Zy(t,e,r,n){t._serialize&&Qi(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=Ut.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?Vu(i.shift(),i):void 0}else typeof s=="string"&&(s=Vu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function Qi(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=Ut.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in r&&(t[i][s]=r[s](t[i][s]))}function wn(t,e,r){return function(){const n=new Array(1+arguments.length);n[0]=e;for(var i=1;i<n.length;i++)n[i]=arguments[i-1];return t[r].apply(this,n)}}function Yy(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Qi(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=r.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,n(s,t._logEvent,a),t._logEvent=Bo(c)}function Bo(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Xy(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function Jy(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Hu:Wu}function es(){return{}}function To(t){return t}function Xn(){}function Hu(){return!1}function Wu(){return Date.now()}function Qy(){return Math.round(Date.now()/1e3)}function ew(){return new Date(Date.now()).toISOString()}function tw(){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 rw={level:"info"},Jn="custom_context",Po=1e3*1024;class nw{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}}class Gu{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new nw(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.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 r=this.head;for(;r!==null;)e.push(r.value),r=r.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 r=e.value;return e=e.next,{done:!1,value:r}}}}}class Zu{constructor(e,r=Po){this.level=e??"error",this.levelValue=Wt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new Gu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Wt.levels.values.error?console.error(e):r===Wt.levels.values.warn?console.warn(e):r===Wt.levels.values.debug?console.debug(e):r===Wt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Kr({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new Gu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Kr({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class iw{constructor(e,r=Po){this.baseChunkLogger=new Zu(e,r)}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 r=URL.createObjectURL(this.logsToBlob(e)),n=document.createElement("a");n.href=r,n.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(n),n.click(),document.body.removeChild(n),URL.revokeObjectURL(r)}}class sw{constructor(e,r=Po){this.baseChunkLogger=new Zu(e,r)}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 ow=Object.defineProperty,aw=Object.defineProperties,cw=Object.getOwnPropertyDescriptors,Yu=Object.getOwnPropertySymbols,uw=Object.prototype.hasOwnProperty,lw=Object.prototype.propertyIsEnumerable,Xu=(t,e,r)=>e in t?ow(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ts=(t,e)=>{for(var r in e||(e={}))uw.call(e,r)&&Xu(t,r,e[r]);if(Yu)for(var r of Yu(e))lw.call(e,r)&&Xu(t,r,e[r]);return t},rs=(t,e)=>aw(t,cw(e));function Ro(t){return rs(ts({},t),{level:t?.level||rw.level})}function hw(t,e=Jn){return t[e]||""}function fw(t,e,r=Jn){return t[r]=e,t}function Je(t,e=Jn){let r="";return typeof t.bindings>"u"?r=hw(t,e):r=t.bindings().context||"",r}function dw(t,e,r=Jn){const n=Je(t,r);return n.trim()?`${n}/${e}`:e}function He(t,e,r=Jn){const n=dw(t,e,r),i=t.child({context:n});return fw(i,n,r)}function pw(t){var e,r;const n=new iw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Wt(rs(ts({},t.opts),{level:"trace",browser:rs(ts({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function gw(t){var e;const r=new sw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Wt(rs(ts({},t.opts),{level:"trace"})),chunkLoggerController:r}}function yw(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?pw(t):gw(t)}var ww=Object.defineProperty,bw=(t,e,r)=>e in t?ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ju=(t,e,r)=>bw(t,typeof e!="symbol"?e+"":e,r);class mw extends qr{constructor(e){super(),this.opts=e,Ju(this,"protocol","wc"),Ju(this,"version",2)}}var vw=Object.defineProperty,Ew=(t,e,r)=>e in t?vw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xw=(t,e,r)=>Ew(t,typeof e!="symbol"?e+"":e,r);class _w extends qr{constructor(e,r){super(),this.core=e,this.logger=r,xw(this,"records",new Map)}}class Sw{constructor(e,r){this.logger=e,this.core=r}}class Iw extends qr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class Dw extends qr{constructor(e){super()}}class Aw{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}}class $w extends qr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class Ow extends qr{constructor(e,r){super(),this.core=e,this.logger=r}}class Bw{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}}class Tw{constructor(e,r){this.projectId=e,this.logger=r}}class Pw{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}}var Rw=Object.defineProperty,Cw=(t,e,r)=>e in t?Rw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Qu=(t,e,r)=>Cw(t,typeof e!="symbol"?e+"":e,r);class Uw{constructor(e){this.opts=e,Qu(this,"protocol","wc"),Qu(this,"version",2)}}class Nw{constructor(e){this.client=e}}function Fw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function el(t,...e){if(!Fw(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 tl(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 kw(t,e){el(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const bn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Co=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Lw(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function rl(t){return typeof t=="string"&&(t=Lw(t)),el(t),t}class Mw{clone(){return this._cloneInto()}}function qw(t){const e=n=>t().update(rl(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function nl(t=32){if(bn&&typeof bn.getRandomValues=="function")return bn.getRandomValues(new Uint8Array(t));if(bn&&typeof bn.randomBytes=="function")return bn.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function jw(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}class zw extends Mw{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){tl(this);const{view:r,buffer:n,blockLen:i}=this;e=rl(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Co(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tl(this),kw(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(n,0),o=0);for(let f=o;f<i;f++)r[f]=0;jw(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%r&&e.buffer.set(n),e}}const ns=BigInt(2**32-1),Uo=BigInt(32);function il(t,e=!1){return e?{h:Number(t&ns),l:Number(t>>Uo&ns)}:{h:Number(t>>Uo&ns)|0,l:Number(t&ns)|0}}function Kw(t,e=!1){let r=new Uint32Array(t.length),n=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=il(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const Vw=(t,e)=>BigInt(t>>>0)<<Uo|BigInt(e>>>0),Hw=(t,e,r)=>t>>>r,Ww=(t,e,r)=>t<<32-r|e>>>r,Gw=(t,e,r)=>t>>>r|e<<32-r,Zw=(t,e,r)=>t<<32-r|e>>>r,Yw=(t,e,r)=>t<<64-r|e>>>r-32,Xw=(t,e,r)=>t>>>r-32|e<<64-r,Jw=(t,e)=>e,Qw=(t,e)=>t,e1=(t,e,r)=>t<<r|e>>>32-r,t1=(t,e,r)=>e<<r|t>>>32-r,r1=(t,e,r)=>e<<r-32|t>>>64-r,n1=(t,e,r)=>t<<r-32|e>>>64-r;function i1(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const s1=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),o1=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,a1=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),c1=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,u1=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),l1=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,J={fromBig:il,split:Kw,toBig:Vw,shrSH:Hw,shrSL:Ww,rotrSH:Gw,rotrSL:Zw,rotrBH:Yw,rotrBL:Xw,rotr32H:Jw,rotr32L:Qw,rotlSH:e1,rotlSL:t1,rotlBH:r1,rotlBL:n1,add:i1,add3L:s1,add3H:o1,add4L:a1,add4H:c1,add5H:l1,add5L:u1},[h1,f1]=(()=>J.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))))(),fr=new Uint32Array(80),dr=new Uint32Array(80);class d1 extends zw{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:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w]}set(e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)fr[E]=e.getUint32(r),dr[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const O=fr[E-15]|0,R=dr[E-15]|0,C=J.rotrSH(O,R,1)^J.rotrSH(O,R,8)^J.shrSH(O,R,7),U=J.rotrSL(O,R,1)^J.rotrSL(O,R,8)^J.shrSL(O,R,7),N=fr[E-2]|0,$=dr[E-2]|0,G=J.rotrSH(N,$,19)^J.rotrBH(N,$,61)^J.shrSH(N,$,6),W=J.rotrSL(N,$,19)^J.rotrBL(N,$,61)^J.shrSL(N,$,6),P=J.add4L(U,W,dr[E-7],dr[E-16]),v=J.add4H(P,C,G,fr[E-7],fr[E-16]);fr[E]=v|0,dr[E]=P|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:w,Hh:S,Hl:D}=this;for(let E=0;E<80;E++){const O=J.rotrSH(f,h,14)^J.rotrSH(f,h,18)^J.rotrBH(f,h,41),R=J.rotrSL(f,h,14)^J.rotrSL(f,h,18)^J.rotrBL(f,h,41),C=f&d^~f&g,U=h&p^~h&w,N=J.add5L(D,R,U,f1[E],dr[E]),$=J.add5H(N,S,O,C,h1[E],fr[E]),G=N|0,W=J.rotrSH(n,i,28)^J.rotrBH(n,i,34)^J.rotrBH(n,i,39),P=J.rotrSL(n,i,28)^J.rotrBL(n,i,34)^J.rotrBL(n,i,39),v=n&s^n&a^s&a,m=i&o^i&c^o&c;S=g|0,D=w|0,g=d|0,w=p|0,d=f|0,p=h|0,{h:f,l:h}=J.add(u|0,l|0,$|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const y=J.add3L(G,P,m);n=J.add3H(y,$,W,v),i=y|0}({h:n,l:i}=J.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=J.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=J.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=J.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=J.add(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=J.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=J.add(this.Gh|0,this.Gl|0,g|0,w|0),{h:S,l:D}=J.add(this.Hh|0,this.Hl|0,S|0,D|0),this.set(n,i,s,o,a,c,u,l,f,h,d,p,g,w,S,D)}roundClean(){fr.fill(0),dr.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 p1=qw(()=>new d1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const No=BigInt(0),sl=BigInt(1),g1=BigInt(2);function Fo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ko(t){if(!Fo(t))throw new Error("Uint8Array expected")}function Lo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const y1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mo(t){ko(t);let e="";for(let r=0;r<t.length;r++)e+=y1[t[r]];return e}function ol(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?No:BigInt("0x"+t)}const Gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function al(t){if(t>=Gt._0&&t<=Gt._9)return t-Gt._0;if(t>=Gt.A&&t<=Gt.F)return t-(Gt.A-10);if(t>=Gt.a&&t<=Gt.f)return t-(Gt.a-10)}function cl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=al(t.charCodeAt(s)),a=al(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function w1(t){return ol(Mo(t))}function is(t){return ko(t),ol(Mo(Uint8Array.from(t).reverse()))}function ul(t,e){return cl(t.toString(16).padStart(e*2,"0"))}function qo(t,e){return ul(t,e).reverse()}function Zt(t,e,r){let n;if(typeof e=="string")try{n=cl(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Fo(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}function ll(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];ko(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}const jo=t=>typeof t=="bigint"&&No<=t;function b1(t,e,r){return jo(t)&&jo(e)&&jo(r)&&e<=t&&t<r}function Qn(t,e,r,n){if(!b1(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function m1(t){let e;for(e=0;t>No;t>>=sl,e+=1);return e}const v1=t=>(g1<<BigInt(t-1))-sl,E1={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"||Fo(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,r={}){const n=(i,s,o)=>{const a=E1[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))n(i,s,!1);for(const[i,s]of Object.entries(r))n(i,s,!0);return t}function hl(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const _e=BigInt(0),de=BigInt(1),Vr=BigInt(2),x1=BigInt(3),Ko=BigInt(4),fl=BigInt(5),dl=BigInt(8);function we(t,e){const r=t%e;return r>=_e?r:e+r}function _1(t,e,r){if(e<_e)throw new Error("invalid exponent, negatives unsupported");if(r<=_e)throw new Error("invalid modulus");if(r===de)return _e;let n=de;for(;e>_e;)e&de&&(n=n*t%r),t=t*t%r,e>>=de;return n}function Nt(t,e,r){let n=t;for(;e-- >_e;)n*=n,n%=r;return n}function pl(t,e){if(t===_e)throw new Error("invert: expected non-zero number");if(e<=_e)throw new Error("invert: expected positive modulus, got "+e);let r=we(t,e),n=e,i=_e,s=de;for(;r!==_e;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==de)throw new Error("invert: does not exist");return we(i,e)}function S1(t){const e=(t-de)/Vr;let r,n,i;for(r=t-de,n=0;r%Vr===_e;r/=Vr,n++);for(i=Vr;i<t&&_1(i,e,t)!==t-de;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+de)/Ko;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 s=(r+de)/Vr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=n,u=o.pow(o.mul(o.ONE,i),r),l=o.pow(a,s),f=o.pow(a,r);for(;!o.eql(f,o.ONE);){if(o.eql(f,o.ZERO))return o.ZERO;let h=1;for(let p=o.sqr(f);h<c&&!o.eql(p,o.ONE);h++)p=o.sqr(p);const d=o.pow(u,de<<BigInt(c-h-1));u=o.sqr(d),l=o.mul(l,d),f=o.mul(f,u),c=h}return l}}function I1(t){if(t%Ko===x1){const e=(t+de)/Ko;return function(r,n){const i=r.pow(n,e);if(!r.eql(r.sqr(i),n))throw new Error("Cannot find square root");return i}}if(t%dl===fl){const e=(t-fl)/dl;return function(r,n){const i=r.mul(n,Vr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,Vr),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),n))throw new Error("Cannot find square root");return c}}return S1(t)}const D1=(t,e)=>(we(t,e)&de)===de,A1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=A1.reduce((n,i)=>(n[i]="function",n),e);return zo(t,r)}function O1(t,e,r){if(r<_e)throw new Error("invalid exponent, negatives unsupported");if(r===_e)return t.ONE;if(r===de)return e;let n=t.ONE,i=e;for(;r>_e;)r&de&&(n=t.mul(n,i)),i=t.sqr(i),r>>=de;return n}function B1(t,e){const r=new Array(e.length),n=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),i=t.inv(n);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),i),r}function gl(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function yl(t,e,r=!1,n={}){if(t<=_e)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=gl(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:i,BYTES:s,MASK:v1(i),ZERO:_e,ONE:de,create:c=>we(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return _e<=c&&c<t},is0:c=>c===_e,isOdd:c=>(c&de)===de,neg:c=>we(-c,t),eql:(c,u)=>c===u,sqr:c=>we(c*c,t),add:(c,u)=>we(c+u,t),sub:(c,u)=>we(c-u,t),mul:(c,u)=>we(c*u,t),pow:(c,u)=>O1(a,c,u),div:(c,u)=>we(c*pl(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>pl(c,t),sqrt:n.sqrt||(c=>(o||(o=I1(t)),o(a,c))),invertBatch:c=>B1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?qo(c,s):ul(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?is(c):w1(c)}});return Object.freeze(a)}const wl=BigInt(0),ss=BigInt(1);function Vo(t,e){const r=e.negate();return t?r:e}function bl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ho(t,e){bl(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function T1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function P1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Wo=new WeakMap,ml=new WeakMap;function Go(t){return ml.get(t)||1}function R1(t,e){return{constTimeNegate:Vo,hasPrecomputes(r){return Go(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>wl;)n&ss&&(i=i.add(s)),s=s.double(),n>>=ss;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Ho(n,e),o=[];let a=r,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,n,i){const{windows:s,windowSize:o}=Ho(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,f=BigInt(r);for(let h=0;h<s;h++){const d=h*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=ss);const g=d,w=d+Math.abs(p)-1,S=h%2!==0,D=p<0;p===0?c=c.add(Vo(S,n[g])):a=a.add(Vo(D,n[w]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Ho(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let f=0;f<o;f++){const h=f*a;if(i===wl)break;let d=Number(i&c);if(i>>=l,d>a&&(d-=u,i+=ss),d===0)continue;let p=n[h+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(r,n,i){let s=Wo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&Wo.set(n,i(s))),s},wNAFCached(r,n,i){const s=Go(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Go(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){bl(n,e),ml.set(r,n),Wo.delete(r)}}}function C1(t,e,r,n){if(T1(r,t),P1(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=m1(BigInt(r.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let f=u;f>=0;f-=o){c.fill(i);for(let d=0;d<n.length;d++){const p=n[d],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(r[d])}let h=i;for(let d=c.length-1,p=i;d>0;d--)p=p.add(c[d]),h=h.add(p);if(l=l.add(h),f!==0)for(let d=0;d<o;d++)l=l.double()}return l}function U1(t){return $1(t.Fp),zo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...gl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const At=BigInt(0),Qe=BigInt(1),os=BigInt(2),N1=BigInt(8),F1={zip215:!0};function k1(t){const e=U1(t);return zo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function L1(t){const e=k1(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=os<<BigInt(a*8)-Qe,l=r.create,f=yl(e.n,e.nBitLength),h=e.uvRatio||((y,b)=>{try{return{isValid:!0,value:r.sqrt(y*r.inv(b))}}catch{return{isValid:!1,value:At}}}),d=e.adjustScalarBytes||(y=>y),p=e.domain||((y,b,_)=>{if(Lo("phflag",_),b.length||_)throw new Error("Contexts/pre-hash are not supported");return y});function g(y,b){Qn("coordinate "+y,b,At,u)}function w(y){if(!(y instanceof E))throw new Error("ExtendedPoint expected")}const S=hl((y,b)=>{const{ex:_,ey:A,ez:x}=y,I=y.is0();b==null&&(b=I?N1:r.inv(x));const B=l(_*b),T=l(A*b),j=l(x*b);if(I)return{x:At,y:Qe};if(j!==Qe)throw new Error("invZ was invalid");return{x:B,y:T}}),D=hl(y=>{const{a:b,d:_}=e;if(y.is0())throw new Error("bad point: ZERO");const{ex:A,ey:x,ez:I,et:B}=y,T=l(A*A),j=l(x*x),L=l(I*I),k=l(L*L),z=l(T*b),H=l(L*l(z+j)),Z=l(k+l(_*l(T*j)));if(H!==Z)throw new Error("bad point: equation left != right (1)");const V=l(A*x),Y=l(I*B);if(V!==Y)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(b,_,A,x){this.ex=b,this.ey=_,this.ez=A,this.et=x,g("x",b),g("y",_),g("z",A),g("t",x),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof E)throw new Error("extended point not allowed");const{x:_,y:A}=b||{};return g("x",_),g("y",A),new E(_,A,Qe,l(_*A))}static normalizeZ(b){const _=r.invertBatch(b.map(A=>A.ez));return b.map((A,x)=>A.toAffine(_[x])).map(E.fromAffine)}static msm(b,_){return C1(E,f,b,_)}_setWindowSize(b){C.setWindowSize(this,b)}assertValidity(){D(this)}equals(b){w(b);const{ex:_,ey:A,ez:x}=this,{ex:I,ey:B,ez:T}=b,j=l(_*T),L=l(I*x),k=l(A*T),z=l(B*x);return j===L&&k===z}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:b}=e,{ex:_,ey:A,ez:x}=this,I=l(_*_),B=l(A*A),T=l(os*l(x*x)),j=l(b*I),L=_+A,k=l(l(L*L)-I-B),z=j+B,H=z-T,Z=j-B,V=l(k*H),Y=l(z*Z),he=l(k*Z),Ve=l(H*z);return new E(V,Y,Ve,he)}add(b){w(b);const{a:_,d:A}=e,{ex:x,ey:I,ez:B,et:T}=this,{ex:j,ey:L,ez:k,et:z}=b;if(_===BigInt(-1)){const m0=l((I-x)*(L+j)),v0=l((I+x)*(L-j)),pu=l(v0-m0);if(pu===At)return this.double();const E0=l(B*os*z),x0=l(T*os*k),_0=x0+E0,S0=v0+m0,I0=x0-E0,i$=l(_0*pu),s$=l(S0*I0),o$=l(_0*I0),a$=l(pu*S0);return new E(i$,s$,a$,o$)}const H=l(x*j),Z=l(I*L),V=l(T*A*z),Y=l(B*k),he=l((x+I)*(j+L)-H-Z),Ve=Y-V,yt=Y+V,hr=l(Z-_*H),du=l(he*Ve),t$=l(yt*hr),r$=l(he*hr),n$=l(Ve*yt);return new E(du,t$,n$,r$)}subtract(b){return this.add(b.negate())}wNAF(b){return C.wNAFCached(this,b,E.normalizeZ)}multiply(b){const _=b;Qn("scalar",_,Qe,n);const{p:A,f:x}=this.wNAF(_);return E.normalizeZ([A,x])[0]}multiplyUnsafe(b,_=E.ZERO){const A=b;return Qn("scalar",A,At,n),A===At?R:this.is0()||A===Qe?this:C.wNAFCachedUnsafe(this,A,E.normalizeZ,_)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,n).is0()}toAffine(b){return S(this,b)}clearCofactor(){const{h:b}=e;return b===Qe?this:this.multiplyUnsafe(b)}static fromHex(b,_=!1){const{d:A,a:x}=e,I=r.BYTES;b=Zt("pointHex",b,I),Lo("zip215",_);const B=b.slice(),T=b[I-1];B[I-1]=T&-129;const j=is(B),L=_?u:r.ORDER;Qn("pointHex.y",j,At,L);const k=l(j*j),z=l(k-Qe),H=l(A*k-x);let{isValid:Z,value:V}=h(z,H);if(!Z)throw new Error("Point.fromHex: invalid y coordinate");const Y=(V&Qe)===Qe,he=(T&128)!==0;if(!_&&V===At&&he)throw new Error("Point.fromHex: x=0 and x_0=1");return he!==Y&&(V=l(-V)),E.fromAffine({x:V,y:j})}static fromPrivateKey(b){return $(b).point}toRawBytes(){const{x:b,y:_}=this.toAffine(),A=qo(_,r.BYTES);return A[A.length-1]|=b&Qe?128:0,A}toHex(){return Mo(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,Qe,l(e.Gx*e.Gy)),E.ZERO=new E(At,Qe,Qe,At);const{BASE:O,ZERO:R}=E,C=R1(E,a*8);function U(y){return we(y,n)}function N(y){return U(is(y))}function $(y){const b=r.BYTES;y=Zt("private key",y,b);const _=Zt("hashed private key",s(y),2*b),A=d(_.slice(0,b)),x=_.slice(b,2*b),I=N(A),B=O.multiply(I),T=B.toRawBytes();return{head:A,prefix:x,scalar:I,point:B,pointBytes:T}}function G(y){return $(y).pointBytes}function W(y=new Uint8Array,...b){const _=ll(...b);return N(s(p(_,Zt("context",y),!!i)))}function P(y,b,_={}){y=Zt("message",y),i&&(y=i(y));const{prefix:A,scalar:x,pointBytes:I}=$(b),B=W(_.context,A,y),T=O.multiply(B).toRawBytes(),j=W(_.context,T,I,y),L=U(B+j*x);Qn("signature.s",L,At,n);const k=ll(T,qo(L,r.BYTES));return Zt("result",k,r.BYTES*2)}const v=F1;function m(y,b,_,A=v){const{context:x,zip215:I}=A,B=r.BYTES;y=Zt("signature",y,2*B),b=Zt("message",b),_=Zt("publicKey",_,B),I!==void 0&&Lo("zip215",I),i&&(b=i(b));const T=is(y.slice(B,2*B));let j,L,k;try{j=E.fromHex(_,I),L=E.fromHex(y.slice(0,B),I),k=O.multiplyUnsafe(T)}catch{return!1}if(!I&&j.isSmallOrder())return!1;const z=W(x,L.toRawBytes(),j.toRawBytes(),b);return L.add(j.multiplyUnsafe(z)).subtract(k).clearCofactor().equals(E.ZERO)}return O._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:P,verify:m,ExtendedPoint:E,utils:{getExtendedPublicKey:$,randomPrivateKey:()=>o(r.BYTES),precompute(y=8,b=E.BASE){return b._setWindowSize(y),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const Zo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),vl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const M1=BigInt(1),El=BigInt(2);BigInt(3);const q1=BigInt(5),j1=BigInt(8);function z1(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Zo,o=t*t%s*t%s,a=Nt(o,El,s)*o%s,c=Nt(a,M1,s)*t%s,u=Nt(c,q1,s)*c%s,l=Nt(u,e,s)*u%s,f=Nt(l,r,s)*l%s,h=Nt(f,n,s)*f%s,d=Nt(h,i,s)*h%s,p=Nt(d,i,s)*h%s,g=Nt(p,e,s)*u%s;return{pow_p_5_8:Nt(g,El,s)*t%s,b2:o}}function K1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function V1(t,e){const r=Zo,n=we(e*e*e,r),i=we(n*n*e,r),s=z1(t*i).pow_p_5_8;let o=we(t*n*s,r);const a=we(e*o*o,r),c=o,u=we(o*vl,r),l=a===t,f=a===we(-t,r),h=a===we(-t*vl,r);return l&&(o=c),(f||h)&&(o=u),D1(o,r)&&(o=we(-o,r)),{isValid:l||f,value:o}}const H1=(()=>yl(Zo,void 0,!0))(),W1=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:H1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:j1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:p1,randomBytes:nl,adjustScalarBytes:K1,uvRatio:V1}))(),xl=(()=>L1(W1))(),G1="EdDSA",Z1="JWT",as=".",cs="base64url",_l="utf8",Sl="utf8",Y1=":",X1="did",J1="key",Il="base58btc",Q1="z",eb="K36",tb=32;function Yo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Dl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Yo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Al(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Dl(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return Yo(r)}function rb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,S=0,D=p.length;S!==D&&p[S]===0;)S++,g++;for(var E=(D-S)*l+1>>>0,O=new Uint8Array(E);S!==D;){for(var R=p[S],C=0,U=E-1;(R!==0||C<w)&&U!==-1;U--,C++)R+=256*O[U]>>>0,O[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=C,S++}for(var N=E-w;N!==E&&O[N]===0;)N++;for(var $=c.repeat(g);N<E;++N)$+=t.charAt(O[N]);return $}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,S=0;p[g]===c;)w++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var O=r[p.charCodeAt(g)];if(O===255)return;for(var R=0,C=D-1;(O!==0||R<S)&&C!==-1;C--,R++)O+=a*E[C]>>>0,E[C]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=R,g++}if(p[g]!==" "){for(var U=D-S;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(w+(D-U)),$=w;U!==D;)N[$++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var nb=rb,ib=nb;const $l=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")},sb=t=>new TextEncoder().encode(t),ob=t=>new TextDecoder().decode(t);class ab{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class cb{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 Ol(this,e)}}class ub{constructor(e){this.decoders=e}or(e){return Ol(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Ol=(t,e)=>new ub({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class lb{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new ab(e,r,n),this.decoder=new cb(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const us=({name:t,prefix:e,encode:r,decode:n})=>new lb(t,e,r,n),ei=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=ib(r,e);return us({prefix:t,name:e,encode:n,decode:s=>$l(i(s))})},hb=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},fb=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Ie=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>us({prefix:e,name:t,encode(i){return fb(i,n,r)},decode(i){return hb(i,n,r,t)}}),db=us({prefix:"\0",name:"identity",encode:t=>ob(t),decode:t=>sb(t)});var pb=Object.freeze({__proto__:null,identity:db});const gb=Ie({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var yb=Object.freeze({__proto__:null,base2:gb});const wb=Ie({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var bb=Object.freeze({__proto__:null,base8:wb});const mb=ei({prefix:"9",name:"base10",alphabet:"0123456789"});var vb=Object.freeze({__proto__:null,base10:mb});const Eb=Ie({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),xb=Ie({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _b=Object.freeze({__proto__:null,base16:Eb,base16upper:xb});const Sb=Ie({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ib=Ie({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Db=Ie({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ab=Ie({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),$b=Ie({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ob=Ie({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Bb=Ie({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Tb=Ie({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Pb=Ie({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Rb=Object.freeze({__proto__:null,base32:Sb,base32upper:Ib,base32pad:Db,base32padupper:Ab,base32hex:$b,base32hexupper:Ob,base32hexpad:Bb,base32hexpadupper:Tb,base32z:Pb});const Cb=ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Ub=ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Nb=Object.freeze({__proto__:null,base36:Cb,base36upper:Ub});const Fb=ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),kb=ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Lb=Object.freeze({__proto__:null,base58btc:Fb,base58flickr:kb});const Mb=Ie({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),qb=Ie({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),jb=Ie({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),zb=Ie({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Kb=Object.freeze({__proto__:null,base64:Mb,base64pad:qb,base64url:jb,base64urlpad:zb});const Bl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Vb=Bl.reduce((t,e,r)=>(t[r]=e,t),[]),Hb=Bl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Wb(t){return t.reduce((e,r)=>(e+=Vb[r],e),"")}function Gb(t){const e=[];for(const r of t){const n=Hb[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const Zb=us({prefix:"\u{1F680}",name:"base256emoji",encode:Wb,decode:Gb});var Yb=Object.freeze({__proto__:null,base256emoji:Zb}),Xb=Pl,Tl=128,Jb=127,Qb=~Jb,em=Math.pow(2,31);function Pl(t,e,r){e=e||[],r=r||0;for(var n=r;t>=em;)e[r++]=t&255|Tl,t/=128;for(;t&Qb;)e[r++]=t&255|Tl,t>>>=7;return e[r]=t|0,Pl.bytes=r-n+1,e}var tm=Xo,rm=128,Rl=127;function Xo(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Xo.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Rl)<<i:(o&Rl)*Math.pow(2,i),i+=7}while(o>=rm);return Xo.bytes=s-n,r}var nm=Math.pow(2,7),im=Math.pow(2,14),sm=Math.pow(2,21),om=Math.pow(2,28),am=Math.pow(2,35),cm=Math.pow(2,42),um=Math.pow(2,49),lm=Math.pow(2,56),hm=Math.pow(2,63),fm=function(t){return t<nm?1:t<im?2:t<sm?3:t<om?4:t<am?5:t<cm?6:t<um?7:t<lm?8:t<hm?9:10},dm={encode:Xb,decode:tm,encodingLength:fm},Cl=dm;const Ul=(t,e,r=0)=>(Cl.encode(t,e,r),e),Nl=t=>Cl.encodingLength(t),Jo=(t,e)=>{const r=e.byteLength,n=Nl(t),i=n+Nl(r),s=new Uint8Array(i+r);return Ul(t,s,0),Ul(r,s,n),s.set(e,i),new pm(t,r,e,s)};class pm{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Fl=({name:t,code:e,encode:r})=>new gm(t,e,r);class gm{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Jo(this.code,r):r.then(n=>Jo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const kl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ym=Fl({name:"sha2-256",code:18,encode:kl("SHA-256")}),wm=Fl({name:"sha2-512",code:19,encode:kl("SHA-512")});var bm=Object.freeze({__proto__:null,sha256:ym,sha512:wm});const Ll=0,mm="identity",Ml=$l;var vm=Object.freeze({__proto__:null,identity:{code:Ll,name:mm,encode:Ml,digest:t=>Jo(Ll,Ml(t))}});new TextEncoder,new TextDecoder;const ql={...pb,...yb,...bb,...vb,..._b,...Rb,...Nb,...Lb,...Kb,...Yb};({...bm,...vm});function jl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const zl=jl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Qo=jl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Dl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Kl={utf8:zl,"utf-8":zl,hex:ql.base16,latin1:Qo,ascii:Qo,binary:Qo,...ql};function ls(t,e="utf8"){const r=Kl[e];if(!r)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"):r.encoder.encode(t).substring(1)}function mn(t,e="utf8"){const r=Kl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Yo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function Vl(t){return gn(ls(mn(t,cs),_l))}function hs(t){return ls(mn(Kr(t),_l),cs)}function Hl(t){const e=mn(eb,Il),r=Q1+ls(Al([e,t]),Il);return[X1,J1,r].join(Y1)}function Em(t){return ls(t,cs)}function xm(t){return mn(t,cs)}function _m(t){return mn([hs(t.header),hs(t.payload)].join(as),Sl)}function Sm(t){return[hs(t.header),hs(t.payload),Em(t.signature)].join(as)}function ea(t){const e=t.split(as),r=Vl(e[0]),n=Vl(e[1]),i=xm(e[2]),s=mn(e.slice(0,2).join(as),Sl);return{header:r,payload:n,signature:i,data:s}}function Wl(t=nl(tb)){const e=xl.getPublicKey(t);return{secretKey:Al([t,e]),publicKey:e}}async function Im(t,e,r,n,i=M.fromMiliseconds(Date.now())){const s={alg:G1,typ:Z1},o=Hl(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=_m({header:s,payload:c}),l=xl.sign(u,n.secretKey.slice(0,32));return Sm({header:s,payload:c,signature:l})}var Gl=function(t,e,r){if(r||arguments.length===2)for(var n=0,i=e.length,s;n<i;n++)(s||!(n in e))&&(s||(s=Array.prototype.slice.call(e,0,n)),s[n]=e[n]);return t.concat(s||Array.prototype.slice.call(e))},Dm=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),Am=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),$m=function(){function t(e,r,n,i){this.name=e,this.version=r,this.os=n,this.bot=i,this.type="bot-device"}return t}(),Om=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Bm=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Tm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Pm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Zl=3,Rm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Tm]],Yl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function Cm(t){return t?Xl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Bm:typeof navigator<"u"?Xl(navigator.userAgent):Fm()}function Um(t){return t!==""&&Rm.reduce(function(e,r){var n=r[0],i=r[1];if(e)return e;var s=i.exec(t);return!!s&&[n,s]},!1)}function Xl(t){var e=Um(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Om;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<Zl&&(i=Gl(Gl([],i,!0),km(Zl-i.length),!0)):i=[];var s=i.join("."),o=Nm(t),a=Pm.exec(t);return a&&a[1]?new $m(r,s,o,a[1]):new Dm(r,s,o)}function Nm(t){for(var e=0,r=Yl.length;e<r;e++){var n=Yl[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function Fm(){var t=typeof process<"u"&&process.version;return t?new Am(process.version.slice(1)):null}function km(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.getLocalStorage=ce.getLocalStorageOrThrow=ce.getCrypto=ce.getCryptoOrThrow=Jl=ce.getLocation=ce.getLocationOrThrow=ta=ce.getNavigator=ce.getNavigatorOrThrow=Wr=ce.getDocument=ce.getDocumentOrThrow=ce.getFromWindowOrThrow=ce.getFromWindow=void 0;function Hr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ce.getFromWindow=Hr;function vn(t){const e=Hr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ce.getFromWindowOrThrow=vn;function Lm(){return vn("document")}ce.getDocumentOrThrow=Lm;function Mm(){return Hr("document")}var Wr=ce.getDocument=Mm;function qm(){return vn("navigator")}ce.getNavigatorOrThrow=qm;function jm(){return Hr("navigator")}var ta=ce.getNavigator=jm;function zm(){return vn("location")}ce.getLocationOrThrow=zm;function Km(){return Hr("location")}var Jl=ce.getLocation=Km;function Vm(){return vn("crypto")}ce.getCryptoOrThrow=Vm;function Hm(){return Hr("crypto")}ce.getCrypto=Hm;function Wm(){return vn("localStorage")}ce.getLocalStorageOrThrow=Wm;function Gm(){return Hr("localStorage")}ce.getLocalStorage=Gm;var ra={};Object.defineProperty(ra,"__esModule",{value:!0});var Ql=ra.getWindowMetadata=void 0;const eh=ce;function Zm(){let t,e;try{t=eh.getDocumentOrThrow(),e=eh.getLocationOrThrow()}catch{return null}function r(){const f=t.getElementsByTagName("link"),h=[];for(let d=0;d<f.length;d++){const p=f[d],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const w=p.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let S=e.protocol+"//"+e.host;if(w.indexOf("/")===0)S+=w;else{const D=e.pathname.split("/");D.pop();const E=D.join("/");S+=E+"/"+w}h.push(S)}else if(w.indexOf("//")===0){const S=e.protocol+w;h.push(S)}else h.push(w)}}return h}function n(...f){const h=t.getElementsByTagName("meta");for(let d=0;d<h.length;d++){const p=h[d],g=["itemprop","property","name"].map(w=>p.getAttribute(w)).filter(w=>w?f.includes(w):!1);if(g.length&&g){const w=p.getAttribute("content");if(w)return w}}return""}function i(){let f=n("name","og:site_name","og:title","twitter:title");return f||(f=t.title),f}function s(){return n("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=r();return{description:a,url:c,icons:u,name:o}}Ql=ra.getWindowMetadata=Zm;function ti(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function na(t){return ti(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const th="2.36.0";let ia={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${th}`};class Gr extends Error{constructor(e,r={}){const n=(()=>r.cause instanceof Gr?r.cause.details:r.cause?.message?r.cause.message:r.details)(),i=(()=>r.cause instanceof Gr&&r.cause.docsPath||r.docsPath)(),s=ia.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...ia.version?[`Version: ${ia.version}`]:[]].join(`
15
+ `);super(o,r.cause?{cause:r.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=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=e,this.version=th}walk(e){return rh(this,e)}}function rh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?rh(t.cause,e):e?null:t}class nh extends Gr{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function En(t,{dir:e,size:r=32}={}){return typeof t=="string"?Ym(t,{dir:e,size:r}):Xm(t,{dir:e,size:r})}function Ym(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new nh({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function Xm(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new nh({size:t.length,targetSize:r,type:"bytes"});const n=new Uint8Array(r);for(let i=0;i<r;i++){const s=e==="right";n[s?i:r-i-1]=t[s?i:t.length-i-1]}return n}class Jm extends Gr{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class Qm extends Gr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function xn(t,{size:e}){if(na(t)>e)throw new Qm({givenSize:na(t),maxSize:e})}function sa(t,e={}){const{signed:r}=e;e.size&&xn(t,{size:e.size});const n=BigInt(t);if(!r)return n;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return n<=s?n:n-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function e2(t,e={}){return Number(sa(t,e))}const t2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function oa(t,e={}){return typeof t=="number"||typeof t=="bigint"?aa(t,e):typeof t=="string"?i2(t,e):typeof t=="boolean"?r2(t,e):ih(t,e)}function r2(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(xn(r,{size:e.size}),En(r,{size:e.size})):r}function ih(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=t2[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(xn(n,{size:e.size}),En(n,{dir:"right",size:e.size})):n}function aa(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new Jm({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:r,size:n,value:`${t}${c}`})}const a=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?En(a,{size:n}):a}const n2=new TextEncoder;function i2(t,e={}){const r=n2.encode(t);return ih(r,e)}const s2=new TextEncoder;function o2(t,e={}){return typeof t=="number"||typeof t=="bigint"?c2(t,e):typeof t=="boolean"?a2(t,e):ti(t)?oh(t,e):ah(t,e)}function a2(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(xn(r,{size:e.size}),En(r,{size:e.size})):r}const Yt={zero:48,nine:57,A:65,F:70,a:97,f:102};function sh(t){if(t>=Yt.zero&&t<=Yt.nine)return t-Yt.zero;if(t>=Yt.A&&t<=Yt.F)return t-(Yt.A-10);if(t>=Yt.a&&t<=Yt.f)return t-(Yt.a-10)}function oh(t,e={}){let r=t;e.size&&(xn(r,{size:e.size}),r=En(r,{dir:"right",size:e.size}));let n=r.slice(2);n.length%2&&(n=`0${n}`);const i=n.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=sh(n.charCodeAt(a++)),u=sh(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new Gr(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+u}return s}function c2(t,e){const r=aa(t,e);return oh(r)}function ah(t,e={}){const r=s2.encode(t);return typeof e.size=="number"?(xn(r,{size:e.size}),En(r,{dir:"right",size:e.size})):r}const fs=BigInt(2**32-1),ch=BigInt(32);function u2(t,e=!1){return e?{h:Number(t&fs),l:Number(t>>ch&fs)}:{h:Number(t>>ch&fs)|0,l:Number(t&fs)|0}}function l2(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=u2(t[s],e);[n[s],i[s]]=[o,a]}return[n,i]}const h2=(t,e,r)=>t<<r|e>>>32-r,f2=(t,e,r)=>e<<r|t>>>32-r,d2=(t,e,r)=>e<<r-32|t>>>64-r,p2=(t,e,r)=>t<<r-32|e>>>64-r,_n=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ri(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ni(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function wt(t,...e){if(!ri(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 uh(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ni(t.outputLen),ni(t.blockLen)}function Sn(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 lh(t,e){wt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function g2(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function In(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function ca(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Ft(t,e){return t<<32-e|t>>>e}const y2=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function w2(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function b2(t){for(let e=0;e<t.length;e++)t[e]=w2(t[e]);return t}const hh=y2?t=>t:b2,fh=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),m2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Dn(t){if(wt(t),fh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=m2[t[r]];return e}const Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function dh(t){if(t>=Xt._0&&t<=Xt._9)return t-Xt._0;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function ds(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(fh)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=dh(t.charCodeAt(s)),a=dh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function An(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ps(t){return typeof t=="string"&&(t=An(t)),wt(t),t}function Ue(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];wt(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class ua{}function ph(t){const e=n=>t().update(ps(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function gs(t=32){if(_n&&typeof _n.getRandomValues=="function")return _n.getRandomValues(new Uint8Array(t));if(_n&&typeof _n.randomBytes=="function")return Uint8Array.from(_n.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const v2=BigInt(0),ii=BigInt(1),E2=BigInt(2),x2=BigInt(7),_2=BigInt(256),S2=BigInt(113),gh=[],yh=[],wh=[];for(let t=0,e=ii,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],gh.push(2*(5*n+r)),yh.push((t+1)*(t+2)/2%64);let i=v2;for(let s=0;s<7;s++)e=(e<<ii^(e>>x2)*S2)%_2,e&E2&&(i^=ii<<(ii<<BigInt(s))-ii);wh.push(i)}const bh=l2(wh,!0),I2=bh[0],D2=bh[1],mh=(t,e,r)=>r>32?d2(t,e,r):h2(t,e,r),vh=(t,e,r)=>r>32?p2(t,e,r):f2(t,e,r);function A2(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[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=r[c],l=r[c+1],f=mh(u,l,1)^r[a],h=vh(u,l,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=yh[o],c=mh(i,s,a),u=vh(i,s,a),l=gh[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=I2[n],t[1]^=D2[n]}In(r)}class la extends ua{constructor(e,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,ni(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=g2(this.state)}clone(){return this._cloneInto()}keccak(){hh(this.state32),A2(this.state32,this.rounds),hh(this.state32),this.posOut=0,this.pos=0}update(e){Sn(this),e=ps(e),wt(e);const{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Sn(this,!1),wt(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=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 ni(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(lh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,In(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new la(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const $2=(t,e,r)=>ph(()=>new la(e,t,r)),Eh=(()=>$2(1,136,256/8))();function xh(t,e){const r=e||"hex",n=Eh(ti(t,{strict:!1})?o2(t):t);return r==="bytes"?n:oa(n)}class _h extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const ha=new _h(8192);function O2(t,e){if(ha.has(`${t}.${e}`))return ha.get(`${t}.${e}`);const r=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),n=xh(ah(r),"bytes"),i=(e?r.substring(`${e}0x`.length):r).split("");for(let o=0;o<40;o+=2)n[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(n[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return ha.set(`${t}.${e}`,s),s}function B2(t){const e=xh(`0x${t.substring(4)}`).substring(26);return O2(`0x${e}`)}async function T2({hash:t,signature:e}){const r=ti(t)?t:oa(t),{secp256k1:n}=await Promise.resolve().then(function(){return sE});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:h}=e,d=Number(h??f),p=Sh(d);return new n.Signature(sa(u),sa(l)).addRecoveryBit(p)}const o=ti(e)?e:oa(e);if(na(o)!==65)throw new Error("invalid signature length");const a=e2(`0x${o.slice(130)}`),c=Sh(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Sh(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 P2({hash:t,signature:e}){return B2(await T2({hash:t,signature:e}))}function R2(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function C2(t,e,r){return t&e^~t&r}function U2(t,e,r){return t&e^t&r^e&r}class N2 extends ua{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=ca(this.buffer)}update(e){Sn(this),e=ps(e),wt(e);const{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=ca(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Sn(this),lh(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,In(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let f=o;f<i;f++)r[f]=0;R2(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=ca(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const pr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),F2=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]),gr=new Uint32Array(64);class k2 extends N2{constructor(e=32){super(64,e,8,!1),this.A=pr[0]|0,this.B=pr[1]|0,this.C=pr[2]|0,this.D=pr[3]|0,this.E=pr[4]|0,this.F=pr[5]|0,this.G=pr[6]|0,this.H=pr[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)gr[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const h=gr[f-15],d=gr[f-2],p=Ft(h,7)^Ft(h,18)^h>>>3,g=Ft(d,17)^Ft(d,19)^d>>>10;gr[f]=g+gr[f-7]+p+gr[f-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=Ft(a,6)^Ft(a,11)^Ft(a,25),d=l+h+C2(a,c,u)+F2[f]+gr[f]|0,g=(Ft(n,2)^Ft(n,13)^Ft(n,22))+U2(n,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=n,n=d+g|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){In(gr)}destroy(){this.set(0,0,0,0,0,0,0,0),In(this.buffer)}}const ys=ph(()=>new k2),L2="0.1.1";function M2(){return L2}class We extends Error{constructor(e,r={}){const n=(()=>{if(r.cause instanceof We){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),i=(()=>r.cause instanceof We&&r.cause.docsPath||r.docsPath)(),o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...n||i?["",n?`Details: ${n}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
+ `);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{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,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${M2()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Ih(this,e)}}function Ih(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Ih(t.cause,e):e?null:t}function q2(t,e){if($h(t)>e)throw new Z2({givenSize:$h(t),maxSize:e})}const Jt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Dh(t){if(t>=Jt.zero&&t<=Jt.nine)return t-Jt.zero;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function j2(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new Y2({size:t.length,targetSize:n,type:"Bytes"});const i=new Uint8Array(n);for(let s=0;s<n;s++){const o=r==="right";i[o?s:n-s-1]=t[o?s:t.length-s-1]}return i}function fa(t,e){if(pa(t)>e)throw new nv({givenSize:pa(t),maxSize:e})}function Ah(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;const i=t.replace("0x","");if(i.length>n*2)throw new iv({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const z2=new TextEncoder;function K2(t){return t instanceof Uint8Array?t:typeof t=="string"?H2(t):V2(t)}function V2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function H2(t,e={}){const{size:r}=e;let n=t;r&&(fa(t,r),n=da(t,r));let i=n.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Dh(i.charCodeAt(c++)),l=Dh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new We(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function W2(t,e={}){const{size:r}=e,n=z2.encode(t);return typeof r=="number"?(q2(n,r),G2(n,r)):n}function G2(t,e){return j2(t,{dir:"right",size:e})}function $h(t){return t.length}class Z2 extends We{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Y2 extends We{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const X2=new TextEncoder,J2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oh(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function Q2(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(fa(r,e.size),ws(r,e.size)):r}function Bh(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=J2[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(fa(n,e.size),da(n,e.size)):n}function ev(t,e={}){const{signed:r,size:n}=e,i=BigInt(t);let s;n?r?s=(1n<<BigInt(n)*8n-1n)-1n:s=2n**(BigInt(n)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new rv({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:r,size:n,value:`${t}${u}`})}const c=`0x${(r&&i<0?(1n<<BigInt(n*8))+BigInt(i):i).toString(16)}`;return n?ws(c,n):c}function tv(t,e={}){return Bh(X2.encode(t),e)}function ws(t,e){return Ah(t,{dir:"left",size:e})}function da(t,e){return Ah(t,{dir:"right",size:e})}function pa(t){return Math.ceil((t.length-2)/2)}class rv extends We{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${n?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class nv extends We{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class iv extends We{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new _h(128),aa(0,{size:32});function sv(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=Eh(K2(t));return r==="Bytes"?n:Bh(n)}class ov extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const n=this.keys().next().value;n&&this.delete(n)}return this}}const ga={checksum:new ov(8192)}.checksum,av=/^0x[a-fA-F0-9]{40}$/;function Th(t,e={}){const{strict:r=!0}=e;if(!av.test(t))throw new Ph({address:t,cause:new uv});if(r){if(t.toLowerCase()===t)return;if(cv(t)!==t)throw new Ph({address:t,cause:new lv})}}function cv(t){if(ga.has(t))return ga.get(t);Th(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=sv(W2(e),{as:"Bytes"}),n=e.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&n[s]&&(n[s]=n[s].toUpperCase()),(r[s>>1]&15)>=8&&n[s+1]&&(n[s+1]=n[s+1].toUpperCase());const i=`0x${n.join("")}`;return ga.set(t,i),i}class Ph extends We{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class uv extends We{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class lv extends We{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const hv=/^(.*)\[([0-9]*)\]$/,fv=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,dv=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function ya(t,e){if(t.length!==e.length)throw new gv({expectedLength:t.length,givenLength:e.length});const r=[];for(let n=0;n<t.length;n++){const i=t[n],s=e[n];r.push(ya.encode(i,s))}return Oh(...r)}(function(t){function e(r,n,i=!1){if(r==="address"){const c=n;return Th(c),ws(c.toLowerCase(),i?32:0)}if(r==="string")return tv(n);if(r==="bytes")return n;if(r==="bool")return ws(Q2(n),i?32:1);const s=r.match(dv);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return ev(n,{size:i?32:f,signed:u==="int"})}const o=r.match(fv);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(n.length-2)/2)throw new pv({expectedSize:Number.parseInt(u,10),value:n});return da(n,i?32:0)}const a=r.match(hv);if(a&&Array.isArray(n)){const[c,u]=a,l=[];for(let f=0;f<n.length;f++)l.push(e(u,n[f],!0));return l.length===0?"0x":Oh(...l)}throw new yv(r)}t.encode=e})(ya||(ya={}));class pv extends We{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${pa(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class gv extends We{constructor({expectedLength:e,givenLength:r}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${r}`].join(`
17
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class yv extends We{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Rh extends ua{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,uh(e);const n=ps(r);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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),In(s)}update(e){return Sn(this),this.iHash.update(e),this}digestInto(e){Sn(this),wt(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:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ch=(t,e,r)=>new Rh(t,e).update(r).digest();Ch.create=(t,e)=>new Rh(t,e);const wa=BigInt(0),ba=BigInt(1);function bs(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Zr(t,e,r=""){const n=ri(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){const o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function ms(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Uh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wa:BigInt("0x"+t)}function Yr(t){return Uh(Dn(t))}function Nh(t){return wt(t),Uh(Dn(Uint8Array.from(t).reverse()))}function vs(t,e){return ds(t.toString(16).padStart(e*2,"0"))}function Fh(t,e){return vs(t,e).reverse()}function be(t,e,r){let n;if(typeof e=="string")try{n=ds(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ri(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}const ma=t=>typeof t=="bigint"&&wa<=t;function va(t,e,r){return ma(t)&&ma(e)&&ma(r)&&e<=t&&t<r}function wv(t,e,r,n){if(!va(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function kh(t){let e;for(e=0;t>wa;t>>=ba,e+=1);return e}const si=t=>(ba<<BigInt(t))-ba;function bv(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const n=d=>new Uint8Array(d),i=d=>Uint8Array.of(d);let s=n(t),o=n(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...d)=>r(o,s,...d),l=(d=n(0))=>{o=u(i(0),d),s=u(),d.length!==0&&(o=u(i(1),d),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const p=[];for(;d<e;){s=u();const g=s.slice();p.push(g),d+=s.length}return Ue(...p)};return(d,p)=>{c(),l(d);let g;for(;!(g=p(f()));)l();return c(),g}}function mv(t){return typeof t=="function"&&Number.isSafeInteger(t.outputLen)}function Es(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function Lh(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const et=BigInt(0),Ge=BigInt(1),Xr=BigInt(2),Mh=BigInt(3),qh=BigInt(4),jh=BigInt(5),vv=BigInt(7),zh=BigInt(8),Ev=BigInt(9),Kh=BigInt(16);function at(t,e){const r=t%e;return r>=et?r:e+r}function bt(t,e,r){let n=t;for(;e-- >et;)n*=n,n%=r;return n}function Vh(t,e){if(t===et)throw new Error("invert: expected non-zero number");if(e<=et)throw new Error("invert: expected positive modulus, got "+e);let r=at(t,e),n=e,i=et,s=Ge;for(;r!==et;){const a=n/r,c=n%r,u=i-s*a;n=r,r=c,i=s,s=u}if(n!==Ge)throw new Error("invert: does not exist");return at(i,e)}function Ea(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Hh(t,e){const r=(t.ORDER+Ge)/qh,n=t.pow(e,r);return Ea(t,n,e),n}function xv(t,e){const r=(t.ORDER-jh)/zh,n=t.mul(e,Xr),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,Xr),i),a=t.mul(s,t.sub(o,t.ONE));return Ea(t,a,e),a}function _v(t){const e=oi(t),r=Wh(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),o=(t+vv)/Kh;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,n);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),w=a.cmov(u,l,g);return Ea(a,w,c),w}}function Wh(t){if(t<Mh)throw new Error("sqrt is not defined for small field");let e=t-Ge,r=0;for(;e%Xr===et;)e/=Xr,r++;let n=Xr;const i=oi(t);for(;Zh(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Hh;let s=i.pow(n,e);const o=(e+Ge)/Xr;return function(c,u){if(c.is0(u))return u;if(Zh(c,u)!==1)throw new Error("Cannot find square root");let l=r,f=c.mul(c.ONE,s),h=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const w=Ge<<BigInt(l-p-1),S=c.pow(f,w);l=p,f=c.sqr(S),h=c.mul(h,f),d=c.mul(d,S)}return d}}function Sv(t){return t%qh===Mh?Hh:t%zh===jh?xv:t%Kh===Ev?_v(t):Wh(t)}const Iv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Gh(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=Iv.reduce((n,i)=>(n[i]="function",n),e);return Es(t,r),t}function Dv(t,e,r){if(r<et)throw new Error("invalid exponent, negatives unsupported");if(r===et)return t.ONE;if(r===Ge)return e;let n=t.ONE,i=e;for(;r>et;)r&Ge&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ge;return n}function xs(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),s),n}function Zh(t,e){const r=(t.ORDER-Ge)/Xr,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Yh(t,e){e!==void 0&&ni(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function oi(t,e,r=!1,n={}){if(t<=et)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:u}=Yh(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:si(c),ZERO:et,ONE:Ge,allowedLengths:a,create:h=>at(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return et<=h&&h<t},is0:h=>h===et,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ge)===Ge,neg:h=>at(-h,t),eql:(h,d)=>h===d,sqr:h=>at(h*h,t),add:(h,d)=>at(h+d,t),sub:(h,d)=>at(h-d,t),mul:(h,d)=>at(h*d,t),pow:(h,d)=>Dv(f,h,d),div:(h,d)=>at(h*Vh(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>Vh(h,t),sqrt:s||(h=>(l||(l=Sv(t)),l(f,h))),toBytes:h=>r?Fh(h,u):vs(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,r?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=r?Nh(h):Yr(h);if(o&&(p=at(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>xs(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function Xh(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 Jh(t){const e=Xh(t);return e+Math.ceil(e/2)}function Qh(t,e,r=!1){const n=t.length,i=Xh(e),s=Jh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?Nh(t):Yr(t),a=at(o,e-Ge)+Ge;return r?Fh(a,i):vs(a,i)}const $n=BigInt(0),Jr=BigInt(1);function _s(t,e){const r=e.negate();return t?r:e}function xa(t,e){const r=xs(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function ef(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _a(t,e){ef(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,s=si(t),o=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function tf(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),c=t>>o;a>n&&(a-=s,c+=Jr);const u=e*n,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function Av(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function $v(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Sa=new WeakMap,rf=new WeakMap;function Ia(t){return rf.get(t)||1}function nf(t){if(t!==$n)throw new Error("invalid wNAF")}class Ov{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>$n;)r&Jr&&(n=n.add(i)),i=i.double(),r>>=Jr;return n}precomputeWindow(e,r){const{windows:n,windowSize:i}=_a(r,this.bits),s=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=_a(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=tf(n,a,o);n=c,l?s=s.add(_s(h,r[d])):i=i.add(_s(f,r[u]))}return nf(n),{p:i,f:s}}wNAFUnsafe(e,r,n,i=this.ZERO){const s=_a(e,this.bits);for(let o=0;o<s.windows&&n!==$n;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=tf(n,o,s);if(n=a,!u){const f=r[c];i=i.add(l?f.negate():f)}}return nf(n),i}getPrecomputes(e,r,n){let i=Sa.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Sa.set(r,i))),i}cached(e,r,n){const i=Ia(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){const s=Ia(e);return s===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,i)}createCache(e,r){ef(r,this.bits),rf.set(e,r),Sa.delete(e)}hasCache(e){return Ia(e)!==1}}function Bv(t,e,r,n){let i=e,s=t.ZERO,o=t.ZERO;for(;r>$n||n>$n;)r&Jr&&(s=s.add(i)),n&Jr&&(o=o.add(i)),i=i.double(),r>>=Jr,n>>=Jr;return{p1:s,p2:o}}function Tv(t,e,r,n){Av(r,t),$v(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=kh(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=si(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const w=n[g],S=Number(w>>BigInt(d)&u);l[S]=l[S].add(r[g])}let p=o;for(let g=l.length-1,w=o;g>0;g--)w=w.add(l[g]),p=p.add(w);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function sf(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Gh(e),e}else return oi(t,{isLE:r})}function Pv(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>$n))throw new Error(`CURVE.${c} must be positive bigint`)}const i=sf(e.p,r.Fp,n),s=sf(e.n,r.Fn,n),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}const of=(t,e)=>(t+(t>=0?e:-e)/kt)/e;function Rv(t,e,r){const[[n,i],[s,o]]=e,a=of(o*t,r),c=of(-i*t,r);let u=t-a*n-c*s,l=-a*i-c*o;const f=u<$t,h=l<$t;f&&(u=-u),h&&(l=-l);const d=si(Math.ceil(kh(r)/2))+Ne;if(u<$t||u>=d||l<$t||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Da(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Aa(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return bs(r.lowS,"lowS"),bs(r.prehash,"prehash"),r.format!==void 0&&Da(r.format),r}class Cv extends Error{constructor(e=""){super(e)}}const Qt={Err:Cv,_tlv:{encode:(t,e)=>{const{Err:r}=Qt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=ms(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?ms(i.length/2|128):"";return ms(t)+s+i+e},decode(t,e){const{Err:r}=Qt;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=Qt;if(t<$t)throw new e("integer: negative integers are not allowed");let r=ms(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},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 Yr(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=Qt,i=be("signature",t),{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=Qt,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},$t=BigInt(0),Ne=BigInt(1),kt=BigInt(2),On=BigInt(3),$a=BigInt(4);function Qr(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let i=be("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function Uv(t,e={}){const r=Pv("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o,n:a}=s;Es(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=cf(n,i);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:y,y:b}=v.toAffine(),_=n.toBytes(y);if(bs(m,"isCompressed"),m){l();const A=!n.isOdd(b);return Ue(af(A),_)}else return Ue(Uint8Array.of(4),_,n.toBytes(b))}function h(P){Zr(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,y=P.length,b=P[0],_=P.subarray(1);if(y===v&&(b===2||b===3)){const A=n.fromBytes(_);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");const x=g(A);let I;try{I=n.sqrt(x)}catch(j){const L=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+L)}l();const B=n.isOdd(I);return(b&1)===1!==B&&(I=n.neg(I)),{x:A,y:I}}else if(y===m&&b===4){const A=n.BYTES,x=n.fromBytes(_.subarray(0,A)),I=n.fromBytes(_.subarray(A,A*2));if(!w(x,I))throw new Error("bad point: is not on curve");return{x,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=n.sqr(P),m=n.mul(v,P);return n.add(n.add(m,n.mul(P,s.a)),s.b)}function w(P,v){const m=n.sqr(v),y=g(P);return n.eql(m,y)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const S=n.mul(n.pow(s.a,On),$a),D=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(S,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!n.isValid(v)||m&&n.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function O(P){if(!(P instanceof $))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return Rv(P,c.basises,i.ORDER)}const C=Lh((P,v)=>{const{X:m,Y:y,Z:b}=P;if(n.eql(b,n.ONE))return{x:m,y};const _=P.is0();v==null&&(v=_?n.ONE:n.inv(b));const A=n.mul(m,v),x=n.mul(y,v),I=n.mul(b,v);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:A,y:x}}),U=Lh(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!n.isValid(v)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!w(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,y,b){return m=new $(n.mul(m.X,P),m.Y,m.Z),v=_s(y,v),m=_s(b,m),v.add(m)}class ${constructor(v,m,y){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y}=v||{};if(!v||!n.isValid(m)||!n.isValid(y))throw new Error("invalid affine point");if(v instanceof $)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(y)?$.ZERO:new $(m,y,n.ONE)}static fromBytes(v){const m=$.fromAffine(p(Zr(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return $.fromBytes(be("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(On),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(v)}equals(v){O(v);const{X:m,Y:y,Z:b}=this,{X:_,Y:A,Z:x}=v,I=n.eql(n.mul(m,x),n.mul(_,b)),B=n.eql(n.mul(y,x),n.mul(A,b));return I&&B}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,y=n.mul(m,On),{X:b,Y:_,Z:A}=this;let x=n.ZERO,I=n.ZERO,B=n.ZERO,T=n.mul(b,b),j=n.mul(_,_),L=n.mul(A,A),k=n.mul(b,_);return k=n.add(k,k),B=n.mul(b,A),B=n.add(B,B),x=n.mul(v,B),I=n.mul(y,L),I=n.add(x,I),x=n.sub(j,I),I=n.add(j,I),I=n.mul(x,I),x=n.mul(k,x),B=n.mul(y,B),L=n.mul(v,L),k=n.sub(T,L),k=n.mul(v,k),k=n.add(k,B),B=n.add(T,T),T=n.add(B,T),T=n.add(T,L),T=n.mul(T,k),I=n.add(I,T),L=n.mul(_,A),L=n.add(L,L),T=n.mul(L,k),x=n.sub(x,T),B=n.mul(L,j),B=n.add(B,B),B=n.add(B,B),new $(x,I,B)}add(v){O(v);const{X:m,Y:y,Z:b}=this,{X:_,Y:A,Z:x}=v;let I=n.ZERO,B=n.ZERO,T=n.ZERO;const j=s.a,L=n.mul(s.b,On);let k=n.mul(m,_),z=n.mul(y,A),H=n.mul(b,x),Z=n.add(m,y),V=n.add(_,A);Z=n.mul(Z,V),V=n.add(k,z),Z=n.sub(Z,V),V=n.add(m,b);let Y=n.add(_,x);return V=n.mul(V,Y),Y=n.add(k,H),V=n.sub(V,Y),Y=n.add(y,b),I=n.add(A,x),Y=n.mul(Y,I),I=n.add(z,H),Y=n.sub(Y,I),T=n.mul(j,V),I=n.mul(L,H),T=n.add(I,T),I=n.sub(z,T),T=n.add(z,T),B=n.mul(I,T),z=n.add(k,k),z=n.add(z,k),H=n.mul(j,H),V=n.mul(L,V),z=n.add(z,H),H=n.sub(k,H),H=n.mul(j,H),V=n.add(V,H),k=n.mul(z,V),B=n.add(B,k),k=n.mul(Y,V),I=n.mul(Z,I),I=n.sub(I,k),k=n.mul(Z,z),T=n.mul(Y,T),T=n.add(T,k),new $(I,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals($.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let y,b;const _=A=>W.cached(this,A,x=>xa($,x));if(m){const{k1neg:A,k1:x,k2neg:I,k2:B}=R(v),{p:T,f:j}=_(x),{p:L,f:k}=_(B);b=j.add(k),y=N(m.beta,T,L,A,I)}else{const{p:A,f:x}=_(v);y=A,b=x}return xa($,[y,b])[0]}multiplyUnsafe(v){const{endo:m}=e,y=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===$t||y.is0())return $.ZERO;if(v===Ne)return y;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:_,k2neg:A,k2:x}=R(v),{p1:I,p2:B}=Bv($,y,_,x);return N(m.beta,I,B,b,A)}else return W.unsafe(y,v)}multiplyAndAddUnsafe(v,m,y){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===Ne?!0:v?v($,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===Ne?this:v?v($,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return bs(v,"isCompressed"),this.assertValidity(),d($,this,v)}toHex(v=!0){return Dn(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return xa($,v)}static msm(v,m){return Tv($,i,v,m)}static fromPrivateKey(v){return $.BASE.multiply(Qr(i,v))}}$.BASE=new $(s.Gx,s.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;const G=i.BITS,W=new Ov($,e.endo?Math.ceil(G/2):G);return $.BASE.precompute(8),$}function af(t){return Uint8Array.of(t?2:3)}function Nv(t,e){const r=t.ORDER;let n=$t;for(let p=r-Ne;p%kt===$t;p/=kt)n+=Ne;const i=n,s=kt<<i-Ne-Ne,o=s*kt,a=(r-Ne)/o,c=(a-Ne)/kt,u=o-Ne,l=s,f=t.pow(e,a),h=t.pow(e,(a+Ne)/kt);let d=(p,g)=>{let w=f,S=t.pow(g,u),D=t.sqr(S);D=t.mul(D,g);let E=t.mul(p,D);E=t.pow(E,c),E=t.mul(E,S),S=t.mul(E,g),D=t.mul(E,p);let O=t.mul(D,S);E=t.pow(O,l);let R=t.eql(E,t.ONE);S=t.mul(D,h),E=t.mul(O,w),D=t.cmov(S,D,R),O=t.cmov(E,O,R);for(let C=i;C>Ne;C--){let U=C-kt;U=kt<<U-Ne;let N=t.pow(O,U);const $=t.eql(N,t.ONE);S=t.mul(D,w),w=t.mul(w,w),N=t.mul(O,w),D=t.cmov(S,D,$),O=t.cmov(N,O,$)}return{isValid:R,value:D}};if(t.ORDER%$a===On){const p=(t.ORDER-On)/$a,g=t.sqrt(t.neg(e));d=(w,S)=>{let D=t.sqr(S);const E=t.mul(w,S);D=t.mul(D,E);let O=t.pow(D,p);O=t.mul(O,E);const R=t.mul(O,g),C=t.mul(t.sqr(O),S),U=t.eql(C,w);let N=t.cmov(R,O,U);return{isValid:U,value:N}}}return d}function Fv(t,e){Gh(t);const{A:r,B:n,Z:i}=e;if(!t.isValid(r)||!t.isValid(n)||!t.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");const s=Nv(t,i);if(!t.isOdd)throw new Error("Field does not have .isOdd()");return o=>{let a,c,u,l,f,h,d,p;a=t.sqr(o),a=t.mul(a,i),c=t.sqr(a),c=t.add(c,a),u=t.add(c,t.ONE),u=t.mul(u,n),l=t.cmov(i,t.neg(c),!t.eql(c,t.ZERO)),l=t.mul(l,r),c=t.sqr(u),h=t.sqr(l),f=t.mul(h,r),c=t.add(c,f),c=t.mul(c,u),h=t.mul(h,l),f=t.mul(h,n),c=t.add(c,f),d=t.mul(a,u);const{isValid:g,value:w}=s(c,h);p=t.mul(a,o),p=t.mul(p,w),d=t.cmov(d,u,g),p=t.cmov(p,w,g);const S=t.isOdd(o)===t.isOdd(p);p=t.cmov(t.neg(p),p,S);const D=xs(t,[l],!0)[0];return d=t.mul(d,D),{x:d,y:p}}}function cf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function kv(t,e={}){const{Fn:r}=t,n=e.randomBytes||gs,i=Object.assign(cf(t.Fp,r),{seed:Jh(r.ORDER)});function s(d){try{return!!Qr(r,d)}catch{return!1}}function o(d,p){const{publicKey:g,publicKeyUncompressed:w}=i;try{const S=d.length;return p===!0&&S!==g||p===!1&&S!==w?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=n(i.seed)){return Qh(Zr(d,i.seed,"seed"),r.ORDER)}function c(d,p=!0){return t.BASE.multiply(Qr(r,d)).toBytes(p)}function u(d){const p=a(d);return{secretKey:p,publicKey:c(p)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:w}=i;if(r.allowedLengths||p===g)return;const S=be("key",d).length;return S===g||S===w}function f(d,p,g=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const w=Qr(r,d);return t.fromHex(p).multiply(w).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:d=>Qr(r,d),precompute(d=8,p=t.BASE){return p.precompute(d,!1)}},lengths:i})}function Lv(t,e,r={}){uh(e),Es(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||gs,i=r.hmac||((m,...y)=>Ch(e,m,Ue(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=kv(t,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(m){const y=a>>Ne;return m>y}function S(m,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function D(m,y){Da(y);const b=d.signature,_=y==="compact"?b:y==="recovered"?b+1:void 0;return Zr(m,_,`${y} signature`)}class E{constructor(y,b,_){this.r=S("r",y),this.s=S("s",b),_!=null&&(this.recovery=_),Object.freeze(this)}static fromBytes(y,b=g){D(y,b);let _;if(b==="der"){const{r:B,s:T}=Qt.toSig(Zr(y));return new E(B,T)}b==="recovered"&&(_=y[0],b="compact",y=y.subarray(1));const A=o.BYTES,x=y.subarray(0,A),I=y.subarray(A,A*2);return new E(o.fromBytes(x),o.fromBytes(I),_)}static fromHex(y,b){return this.fromBytes(ds(y),b)}addRecoveryBit(y){return new E(this.r,this.s,y)}recoverPublicKey(y){const b=s.ORDER,{r:_,s:A,recovery:x}=this;if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");if(a*kt<b&&x>1)throw new Error("recovery id is ambiguous for h>1 curve");const B=x===2||x===3?_+a:_;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");const T=s.toBytes(B),j=t.fromBytes(Ue(af((x&1)===0),T)),L=o.inv(B),k=R(be("msgHash",y)),z=o.create(-k*L),H=o.create(A*L),Z=t.BASE.multiplyUnsafe(z).add(j.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return w(this.s)}toBytes(y=g){if(Da(y),y==="der")return ds(Qt.hexFromSig(this));const b=o.toBytes(this.r),_=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ue(Uint8Array.of(this.recovery),b,_)}return Ue(b,_)}toHex(y){return Dn(this.toBytes(y))}assertValidity(){}static fromCompact(y){return E.fromBytes(be("sig",y),"compact")}static fromDER(y){return E.fromBytes(be("sig",y),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Dn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Dn(this.toBytes("compact"))}}const O=r.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const b=Yr(y),_=y.length*8-c;return _>0?b>>BigInt(_):b},R=r.bits2int_modN||function(y){return o.create(O(y))},C=si(c);function U(m){return wv("num < 2^"+c,m,$t,C),o.toBytes(m)}function N(m,y){return Zr(m,void 0,"message"),y?Zr(e(m),void 0,"prehashed message"):m}function $(m,y,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:_,prehash:A,extraEntropy:x}=Aa(b,p);m=N(m,A);const I=R(m),B=Qr(o,y),T=[U(B),U(I)];if(x!=null&&x!==!1){const z=x===!0?n(d.secretKey):x;T.push(be("extraEntropy",z))}const j=Ue(...T),L=I;function k(z){const H=O(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===$t)return;const he=o.create(Z*o.create(L+Y*B));if(he===$t)return;let Ve=(V.x===Y?0:2)|Number(V.y&Ne),yt=he;return _&&w(he)&&(yt=o.neg(he),Ve^=1),new E(Y,yt,Ve)}return{seed:j,k2sig:k}}function G(m,y,b={}){m=be("message",m);const{seed:_,k2sig:A}=$(m,y,b);return bv(e.outputLen,o.BYTES,i)(_,A)}function W(m){let y;const b=typeof m=="string"||ri(m),_=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!_)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(_)y=new E(m.r,m.s);else if(b){try{y=E.fromBytes(be("sig",m),"der")}catch(A){if(!(A instanceof Qt.Err))throw A}if(!y)try{y=E.fromBytes(be("sig",m),"compact")}catch{return!1}}return y||!1}function P(m,y,b,_={}){const{lowS:A,prehash:x,format:I}=Aa(_,p);if(b=be("publicKey",b),y=N(be("message",y),x),"strict"in _)throw new Error("options.strict was renamed to lowS");const B=I===void 0?W(m):E.fromBytes(be("sig",m),I);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:j,s:L}=B,k=R(y),z=o.inv(L),H=o.create(k*z),Z=o.create(j*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===j}catch{return!1}}function v(m,y,b={}){const{prehash:_}=Aa(b,p);return y=N(y,_),E.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function Mv(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},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=oi(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function qv(t){const{CURVE:e,curveOpts:r}=Mv(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function jv(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Yh(r.Fn.ORDER,r.Fn.BITS))})}function zv(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=qv(t),s=Uv(e,r),o=Lv(s,n,i);return jv(t,o)}function Kv(t,e){const r=n=>zv({...t,hash:n});return{...r(e),create:r}}const Vv=Yr;function yr(t,e){if(ai(t),ai(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const r=Array.from({length:e}).fill(0);for(let n=e-1;n>=0;n--)r[n]=t&255,t>>>=8;return new Uint8Array(r)}function Hv(t,e){const r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t[n]^e[n];return r}function ai(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function uf(t){if(!ri(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or string");return typeof t=="string"?An(t):t}function Wv(t,e,r,n){wt(t),ai(r),e=uf(e),e.length>255&&(e=n(Ue(An("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=n,o=Math.ceil(r/i);if(r>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=Ue(e,yr(e.length,1)),c=yr(0,s),u=yr(r,2),l=new Array(o),f=n(Ue(c,t,u,yr(0,1),a));l[0]=n(Ue(f,yr(1,1),a));for(let d=1;d<=o;d++){const p=[Hv(f,l[d-1]),yr(d+1,1),a];l[d]=n(Ue(...p))}return Ue(...l).slice(0,r)}function Gv(t,e,r,n,i){if(wt(t),ai(r),e=uf(e),e.length>255){const s=Math.ceil(2*n/8);e=i.create({dkLen:s}).update(An("H2C-OVERSIZE-DST-")).update(e).digest()}if(r>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:r}).update(t).update(yr(r,2)).update(e).update(yr(e.length,1)).digest()}function Oa(t,e,r){Es(r,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:n,k:i,m:s,hash:o,expand:a,DST:c}=r;if(!mv(r.hash))throw new Error("expected valid hash");wt(t),ai(e);const u=n.toString(2).length,l=Math.ceil((u+i)/8),f=e*s*l;let h;if(a==="xmd")h=Wv(t,c,f,o);else if(a==="xof")h=Gv(t,c,f,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let p=0;p<e;p++){const g=new Array(s);for(let w=0;w<s;w++){const S=l*(w+p*s),D=h.subarray(S,S+l);g[w]=at(Vv(D),n)}d[p]=g}return d}function Zv(t,e){const r=e.map(n=>Array.from(n).reverse());return(n,i)=>{const[s,o,a,c]=r.map(f=>f.reduce((h,d)=>t.add(t.mul(h,n),d))),[u,l]=xs(t,[o,c],!0);return n=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:n,y:i}}}const Yv=An("HashToScalar-");function Xv(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function n(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:r,hashToCurve(s,o){const a=Object.assign({},r,o),c=Oa(s,2,a),u=n(c[0]),l=n(c[1]);return i(u.add(l))},encodeToCurve(s,o){const a=r.encodeDST?{DST:r.encodeDST}:{},c=Object.assign({},r,a,o),u=Oa(s,1,c),l=n(u[0]);return i(l)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(n(s))},hashToScalar(s,o){const a=t.Fn.ORDER,c=Object.assign({},r,{p:a,m:1,DST:Yv},o);return Oa(s,1,c)[0][0]}}}const Bn={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Jv={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Qv=BigInt(0),lf=BigInt(1),Ba=BigInt(2);function eE(t){const e=Bn.p,r=BigInt(3),n=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=bt(l,r,e)*l%e,h=bt(f,r,e)*l%e,d=bt(h,Ba,e)*u%e,p=bt(d,i,e)*d%e,g=bt(p,s,e)*p%e,w=bt(g,a,e)*g%e,S=bt(w,c,e)*w%e,D=bt(S,a,e)*g%e,E=bt(D,r,e)*l%e,O=bt(E,o,e)*p%e,R=bt(O,n,e)*u%e,C=bt(R,Ba,e);if(!er.eql(er.sqr(C),t))throw new Error("Cannot find square root");return C}const er=oi(Bn.p,{sqrt:eE}),Ss=Kv({...Bn,Fp:er,lowS:!0,endo:Jv},ys),hf={};function Is(t,...e){let r=hf[t];if(r===void 0){const n=ys(An(t));r=Ue(n,n),hf[t]=r}return ys(Ue(r,...e))}const Ta=t=>t.toBytes(!0).slice(1),Tn=(()=>Ss.Point)(),Pa=t=>t%Ba===Qv;function Ra(t){const{Fn:e,BASE:r}=Tn,n=Qr(e,t),i=r.multiply(n);return{scalar:Pa(i.y)?n:e.neg(n),bytes:Ta(i)}}function ff(t){const e=er;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");const r=e.create(t*t),n=e.create(r*t+BigInt(7));let i=e.sqrt(n);Pa(i)||(i=e.neg(i));const s=Tn.fromAffine({x:t,y:i});return s.assertValidity(),s}const ci=Yr;function df(...t){return Tn.Fn.create(ci(Is("BIP0340/challenge",...t)))}function pf(t){return Ra(t).bytes}function tE(t,e,r=gs(32)){const{Fn:n}=Tn,i=be("message",t),{bytes:s,scalar:o}=Ra(e),a=be("auxRand",r,32),c=n.toBytes(o^ci(Is("BIP0340/aux",a))),u=Is("BIP0340/nonce",c,s,i),{bytes:l,scalar:f}=Ra(u),h=df(l,s,i),d=new Uint8Array(64);if(d.set(l,0),d.set(n.toBytes(n.create(f+h*o)),32),!gf(d,i,s))throw new Error("sign: Invalid signature produced");return d}function gf(t,e,r){const{Fn:n,BASE:i}=Tn,s=be("signature",t,64),o=be("message",e),a=be("publicKey",r,32);try{const c=ff(ci(a)),u=ci(s.subarray(0,32));if(!va(u,lf,Bn.p))return!1;const l=ci(s.subarray(32,64));if(!va(l,lf,Bn.n))return!1;const f=df(n.toBytes(u),Ta(c),o),h=i.multiplyUnsafe(l).add(c.multiplyUnsafe(n.neg(f))),{x:d,y:p}=h.toAffine();return!(h.is0()||!Pa(p)||d!==u)}catch{return!1}}const rE=(()=>{const r=(i=gs(48))=>Qh(i,Bn.n);Ss.utils.randomSecretKey;function n(i){const s=r(i);return{secretKey:s,publicKey:pf(s)}}return{keygen:n,getPublicKey:pf,sign:tE,verify:gf,Point:Tn,utils:{randomSecretKey:r,randomPrivateKey:r,taggedHash:Is,lift_x:ff,pointToBytes:Ta,numberToBytesBE:vs,bytesToNumberBE:Yr,mod:at},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})(),nE=(()=>Zv(er,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))))(),iE=(()=>Fv(er,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:er.create(BigInt("-11"))}))(),Ca=(()=>Xv(Ss.Point,t=>{const{x:e,y:r}=iE(er.create(t[0]));return nE(e,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:er.ORDER,m:1,k:128,expand:"xmd",hash:ys}))();var sE=Object.freeze({__proto__:null,secp256k1:Ss,schnorr:rE,secp256k1_hasher:Ca,hashToCurve:(()=>Ca.hashToCurve)(),encodeToCurve:(()=>Ca.encodeToCurve)()});function oE(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 l=t.charAt(u),f=l.charCodeAt(0);if(e[f]!==255)throw new TypeError(l+" is ambiguous");e[f]=u}const r=t.length,n=t.charAt(0),i=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);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 l=0,f=0,h=0;const d=u.length;for(;h!==d&&u[h]===0;)h++,l++;const p=(d-h)*s+1>>>0,g=new Uint8Array(p);for(;h!==d;){let D=u[h],E=0;for(let O=p-1;(D!==0||E<f)&&O!==-1;O--,E++)D+=256*g[O]>>>0,g[O]=D%r>>>0,D=D/r>>>0;if(D!==0)throw new Error("Non-zero carry");f=E,h++}let w=p-f;for(;w!==p&&g[w]===0;)w++;let S=n.repeat(l);for(;w<p;++w)S+=t.charAt(g[w]);return S}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,h=0;for(;u[l]===n;)f++,l++;const d=(u.length-l)*i+1>>>0,p=new Uint8Array(d);for(;l<u.length;){const D=u.charCodeAt(l);if(D>255)return;let E=e[D];if(E===255)return;let O=0;for(let R=d-1;(E!==0||O<h)&&R!==-1;R--,O++)E+=r*p[R]>>>0,p[R]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");h=O,l++}let g=d-h;for(;g!==d&&p[g]===0;)g++;const w=new Uint8Array(f+(d-g));let S=f;for(;g!==d;)w[S++]=p[g++];return w}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var aE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ui=oE(aE);function cE(t){const e=t.length;let r=0,n=0;for(;n<e;){let i=t.charCodeAt(n++);if(i&4294967168)if(!(i&4294965248))r+=2;else{if(i>=55296&&i<=56319&&n<e){const s=t.charCodeAt(n);(s&64512)===56320&&(++n,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?r+=4:r+=3}else{r++;continue}}return r}function uE(t,e,r){const n=t.length;let i=r,s=0;for(;s<n;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<n){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128):(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128)}else{e[i++]=o;continue}e[i++]=o&63|128}}const lE=new TextEncoder,hE=50;function fE(t,e,r){lE.encodeInto(t,e.subarray(r))}function dE(t,e,r){t.length>hE?fE(t,e,r):uE(t,e,r)}const pE=4096;function yf(t,e,r){let n=e;const i=n+r,s=[];let o="";for(;n<i;){const a=t[n++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[n++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[n++]&63,u=t[n++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[n++]&63,u=t[n++]&63,l=t[n++]&63;let f=(a&7)<<18|c<<12|u<<6|l;f>65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=pE&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const gE=new TextDecoder,yE=200;function wE(t,e,r){const n=t.subarray(e,e+r);return gE.decode(n)}function bE(t,e,r){return r>yE?wE(t,e,r):yf(t,e,r)}class Ds{constructor(e,r){this.type=e,this.data=r}}class ct extends Error{constructor(e){super(e);const r=Object.create(ct.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const li=4294967295;function mE(t,e,r){const n=r/4294967296,i=r;t.setUint32(e,n),t.setUint32(e+4,i)}function wf(t,e,r){const n=Math.floor(r/4294967296),i=r;t.setUint32(e,n),t.setUint32(e+4,i)}function bf(t,e){const r=t.getInt32(e),n=t.getUint32(e+4);return r*4294967296+n}function vE(t,e){const r=t.getUint32(e),n=t.getUint32(e+4);return r*4294967296+n}const EE=-1,xE=4294967296-1,_E=17179869184-1;function SE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=_E)if(e===0&&t<=xE){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,n=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|r&3),s.setUint32(4,n),i}else{const r=new Uint8Array(12),n=new DataView(r.buffer);return n.setUint32(0,e),wf(n,4,t),r}}function IE(t){const e=t.getTime(),r=Math.floor(e/1e3),n=(e-r*1e3)*1e6,i=Math.floor(n/1e9);return{sec:r+i,nsec:n-i*1e9}}function DE(t){if(t instanceof Date){const e=IE(t);return SE(e)}else return null}function AE(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 r=e.getUint32(0),n=e.getUint32(4),i=(r&3)*4294967296+n,s=r>>>2;return{sec:i,nsec:s}}case 12:{const r=bf(e,4),n=e.getUint32(0);return{sec:r,nsec:n}}default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function $E(t){const e=AE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const OE={type:EE,encode:DE,decode:$E};class As{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(OE)}register({type:e,encode:r,decode:n}){if(e>=0)this.encoders[e]=r,this.decoders[e]=n;else{const i=-1-e;this.builtInEncoders[i]=r,this.builtInDecoders[i]=n}}tryToEncode(e,r){for(let n=0;n<this.builtInEncoders.length;n++){const i=this.builtInEncoders[n];if(i!=null){const s=i(e,r);if(s!=null){const o=-1-n;return new Ds(o,s)}}}for(let n=0;n<this.encoders.length;n++){const i=this.encoders[n];if(i!=null){const s=i(e,r);if(s!=null){const o=n;return new Ds(o,s)}}}return e instanceof Ds?e:null}decode(e,r,n){const i=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return i?i(e,r,n):new Ds(r,e)}}As.defaultCodec=new As;function BE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ua(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):BE(t)?new Uint8Array(t):Uint8Array.from(t)}const TE=100,PE=2048;class Na{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??As.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??TE,this.initialBufferSize=e?.initialBufferSize??PE,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 Na({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,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);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,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),n=new Uint8Array(r),i=new DataView(r);n.set(this.bytes),this.view=i,this.bytes=n}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 n=cE(e);this.ensureBufferSizeToWrite(5+n),this.writeStringHeader(n),dE(e,this.bytes,this.pos),this.pos+=n}encodeObject(e,r){const n=this.extensionCodec.tryToEncode(e,this.context);if(n!=null)this.encodeExtension(n);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const n=Ua(e);this.writeU8a(n)}encodeArray(e,r){const n=e.length;if(n<16)this.writeU8(144+n);else if(n<65536)this.writeU8(220),this.writeU16(n);else if(n<4294967296)this.writeU8(221),this.writeU32(n);else throw new Error(`Too large array: ${n}`);for(const i of e)this.doEncode(i,r+1)}countWithoutUndefined(e,r){let n=0;for(const i of r)e[i]!==void 0&&n++;return n}encodeMap(e,r){const n=Object.keys(e);this.sortKeys&&n.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,n):n.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of n){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const n=e.data(this.pos+6),i=n.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(n);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}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),mE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),wf(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 RE(t,e){return new Na(e).encodeSharedRef(t)}function Fa(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const CE=16,UE=16;class NE{constructor(e=CE,r=UE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let n=0;n<this.maxKeyLength;n++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,n){const i=this.caches[n-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<n;a++)if(o[a]!==e[r+a])continue e;return s.str}return null}store(e,r){const n=this.caches[e.length-1],i={bytes:e,str:r};n.length>=this.maxLengthPerKey?n[Math.random()*n.length|0]=i:n.push(i)}decode(e,r,n){const i=this.find(e,r,n);if(i!=null)return this.hit++,i;this.miss++;const s=yf(e,r,n),o=Uint8Array.prototype.slice.call(e,r,r+n);return this.store(o,s),s}}const ka="array",hi="map_key",mf="map_value",FE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ct("The type of key must be string or number but "+typeof t)};class kE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=ka,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=hi,r.readCount=0,r.size=e,r.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===ka){const n=e;n.size=0,n.array=void 0,n.position=0,n.type=void 0}if(e.type===hi||e.type===mf){const n=e;n.size=0,n.map=void 0,n.readCount=0,n.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const fi=-1,La=new DataView(new ArrayBuffer(0)),LE=new Uint8Array(La.buffer);try{La.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 vf=new RangeError("Insufficient data"),ME=new NE;class Ma{constructor(e){this.totalPos=0,this.pos=0,this.view=La,this.bytes=LE,this.headByte=fi,this.stack=new kE,this.entered=!1,this.extensionCodec=e?.extensionCodec??As.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??li,this.maxBinLength=e?.maxBinLength??li,this.maxArrayLength=e?.maxArrayLength??li,this.maxMapLength=e?.maxMapLength??li,this.maxExtLength=e?.maxExtLength??li,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:ME,this.mapKeyConverter=e?.mapKeyConverter??FE}clone(){return new Ma({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=fi,this.stack.reset()}setBuffer(e){const r=Ua(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===fi&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),n=Ua(e),i=new Uint8Array(r.length+n.length);i.set(r),i.set(n,r.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:n}=this;return new RangeError(`Extra ${r.byteLength-n} of ${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}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 r=!1,n;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{n=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return n}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Fa(i)} at ${o} (${s} 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,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let n=r,i=-1;for await(const s of e){if(r&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),n&&(i=this.readArraySize(),n=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==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 r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else{const i=e-160;r=this.decodeString(i,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const i=this.lookU8();r=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();r=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();r=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else r=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else r={}}else if(e===196){const i=this.lookU8();r=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();r=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();r=this.decodeBinary(i,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();r=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();r=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();r=this.decodeExtension(i,4)}else throw new ct(`Unrecognized type byte: ${Fa(e)}`);this.complete();const n=this.stack;for(;n.length>0;){const i=n.top();if(i.type===ka)if(i.array[i.position]=r,i.position++,i.position===i.size)r=i.array,n.release(i);else continue e;else if(i.type===hi){if(r==="__proto__")throw new ct("The key __proto__ is not allowed");i.key=this.mapKeyConverter(r),i.type=mf;continue e}else if(i.map[i.key]=r,i.readCount++,i.readCount===i.size)r=i.map,n.release(i);else{i.key=null,i.type=hi;continue e}}return r}}readHeadByte(){return this.headByte===fi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=fi}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 ct(`Unrecognized array type byte: ${Fa(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw vf;const n=this.pos+r;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,n,e):i=bE(this.bytes,n,e),this.pos+=r+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hi:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw vf;const n=this.pos+r,i=this.bytes.subarray(n,n+e);return this.pos+=r+e,i}decodeExtension(e,r){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const n=this.view.getInt8(this.pos+r),i=this.decodeBinary(e,r+1);return this.extensionCodec.decode(i,n,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=vE(this.view,this.pos);return this.pos+=8,e}readI64(){const e=bf(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 qE(t,e){return new Ma(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function qa(t,...e){if(!$s(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 Ef(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function xf(t){if(typeof t!="function")throw new Error("function expected");return!0}function wr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function di(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Os(t){if(!Array.isArray(t))throw new Error("array expected")}function Bs(t,e){if(!Ef(!0,e))throw new Error(`${t}: array of strings expected`)}function ja(t,e){if(!Ef(!1,e))throw new Error(`${t}: array of numbers expected`)}function ut(...t){const e=s=>s,r=(s,o)=>a=>s(o(a)),n=t.map(s=>s.encode).reduceRight(r,e),i=t.map(s=>s.decode).reduce(r,e);return{encode:n,decode:i}}function lt(t){const e=typeof t=="string"?t.split(""):t,r=e.length;Bs("alphabet",e);const n=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Os(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Os(i),i.map(s=>{wr("alphabet.decode",s);const o=n.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function ht(t=""){return wr("join",t),{encode:e=>(Bs("join.decode",e),e.join(t)),decode:e=>(wr("join.decode",e),e.split(t))}}function Ts(t,e="="){return di(t),wr("padding",e),{encode(r){for(Bs("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){Bs("padding.decode",r);let n=r.length;if(n*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;n>0&&r[n-1]===e;n--)if((n-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,n)}}}function _f(t){return xf(t),{encode:e=>e,decode:e=>t(e)}}function Sf(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(Os(t),!t.length)return[];let n=0;const i=[],s=Array.from(t,a=>{if(di(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=n;u<o;u++){const l=s[u],f=e*a,h=f+l;if(!Number.isSafeInteger(h)||f/e!==a||h-l!==f)throw new Error("convertRadix: carry overflow");const d=h/r;a=h%r;const p=Math.floor(d);if(s[u]=p,!Number.isSafeInteger(p)||p*r+a!==h)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:n=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const If=(t,e)=>e===0?t:If(e,t%e),Ps=(t,e)=>t+(e-If(t,e)),Rs=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function za(t,e,r,n){if(Os(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(Ps(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${Ps(e,r)}`);let i=0,s=0;const o=Rs[e],a=Rs[r]-1,c=[];for(const u of t){if(di(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=r;s-=r)c.push((i>>s-r&a)>>>0);const l=Rs[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<r-s&a,!n&&s>=e)throw new Error("Excess padding");if(!n&&i>0)throw new Error(`Non-zero padding: ${i}`);return n&&s>0&&c.push(i>>>0),c}function jE(t){di(t);const e=2**8;return{encode:r=>{if(!$s(r))throw new Error("radix.encode input should be Uint8Array");return Sf(Array.from(r),e,t)},decode:r=>(ja("radix.decode",r),Uint8Array.from(Sf(r,t,e)))}}function mt(t,e=!1){if(di(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ps(8,t)>32||Ps(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!$s(r))throw new Error("radix2.encode input should be Uint8Array");return za(Array.from(r),8,t,!e)},decode:r=>(ja("radix2.decode",r),Uint8Array.from(za(r,t,8,e)))}}function Df(t){return xf(t),function(...e){try{return t.apply(null,e)}catch{}}}ut(mt(4),lt("0123456789ABCDEF"),ht(""));const zE=ut(mt(5),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ts(5),ht(""));ut(mt(5),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ht("")),ut(mt(5),lt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Ts(5),ht("")),ut(mt(5),lt("0123456789ABCDEFGHIJKLMNOPQRSTUV"),ht("")),ut(mt(5),lt("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),ht(""),_f(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const Af=(()=>typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function")(),$f=(t,e)=>{wr("base64",t);const r=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,n=e?"base64url":"base64";if(t.length>0&&!r.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:n,lastChunkHandling:"strict"})};Af||ut(mt(6),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Ts(6),ht("")),ut(mt(6),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),ht("")),Af||ut(mt(6),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Ts(6),ht("")),ut(mt(6),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),ht(""));const Ka=t=>ut(jE(58),lt(t),ht(""));Ka("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Ka("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),Ka("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const Va=ut(lt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ht("")),Of=[996825010,642813549,513874426,1027748829,705979059];function pi(t){const e=t>>25;let r=(t&33554431)<<5;for(let n=0;n<Of.length;n++)(e>>n&1)===1&&(r^=Of[n]);return r}function Bf(t,e,r=1){const n=t.length;let i=1;for(let s=0;s<n;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=pi(i)^o>>5}i=pi(i);for(let s=0;s<n;s++)i=pi(i)^t.charCodeAt(s)&31;for(let s of e)i=pi(i)^s;for(let s=0;s<6;s++)i=pi(i);return i^=r,Va.encode(za([i%Rs[30]],30,5,!1))}function Tf(t){const e=t==="bech32"?1:734539939,r=mt(5),n=r.decode,i=r.encode,s=Df(n);function o(f,h,d=90){wr("bech32.encode prefix",f),$s(h)&&(h=Array.from(h)),ja("bech32.encode",h);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+h.length;if(d!==!1&&g>d)throw new TypeError(`Length ${g} exceeds limit ${d}`);const w=f.toLowerCase(),S=Bf(w,h,e);return`${w}1${Va.encode(h)}${S}`}function a(f,h=90){wr("bech32.decode input",f);const d=f.length;if(d<8||h!==!1&&d>h)throw new TypeError(`invalid string length: ${d} (${f}). Expected (8..${h})`);const p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=p.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const w=p.slice(0,g),S=p.slice(g+1);if(S.length<6)throw new Error("Data must be at least 6 characters long");const D=Va.decode(S).slice(0,-6),E=Bf(w,D,e);if(!S.endsWith(E))throw new Error(`Invalid checksum in ${f}: expected "${E}"`);return{prefix:w,words:D}}const c=Df(a);function u(f){const{prefix:h,words:d}=a(f,!1);return{prefix:h,words:d,bytes:n(d)}}function l(f,h){return o(f,i(h))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:n,fromWordsUnsafe:s,toWords:i}}Tf("bech32"),Tf("bech32m");const KE=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),VE={encode(t){return qa(t),t.toHex()},decode(t){return wr("hex",t),Uint8Array.fromHex(t)}};KE||ut(mt(4),lt("0123456789abcdef"),ht(""),_f(t=>{if(typeof t!="string"||t.length%2!==0)throw new TypeError(`hex.decode: expected string, got ${typeof t} with length ${t.length}`);return t.toLowerCase()}));function Ha(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Pf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ha(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function gi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Pf(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return Ha(r)}function HE(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,S=0,D=p.length;S!==D&&p[S]===0;)S++,g++;for(var E=(D-S)*l+1>>>0,O=new Uint8Array(E);S!==D;){for(var R=p[S],C=0,U=E-1;(R!==0||C<w)&&U!==-1;U--,C++)R+=256*O[U]>>>0,O[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=C,S++}for(var N=E-w;N!==E&&O[N]===0;)N++;for(var $=c.repeat(g);N<E;++N)$+=t.charAt(O[N]);return $}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,S=0;p[g]===c;)w++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var O=r[p.charCodeAt(g)];if(O===255)return;for(var R=0,C=D-1;(O!==0||R<S)&&C!==-1;C--,R++)O+=a*E[C]>>>0,E[C]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=R,g++}if(p[g]!==" "){for(var U=D-S;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(w+(D-U)),$=w;U!==D;)N[$++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var WE=HE,GE=WE;const Rf=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")},ZE=t=>new TextEncoder().encode(t),YE=t=>new TextDecoder().decode(t);class XE{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class JE{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 Cf(this,e)}}class QE{constructor(e){this.decoders=e}or(e){return Cf(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Cf=(t,e)=>new QE({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class e3{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new XE(e,r,n),this.decoder=new JE(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Cs=({name:t,prefix:e,encode:r,decode:n})=>new e3(t,e,r,n),yi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=GE(r,e);return Cs({prefix:t,name:e,encode:n,decode:s=>Rf(i(s))})},t3=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},r3=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},De=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>Cs({prefix:e,name:t,encode(i){return r3(i,n,r)},decode(i){return t3(i,n,r,t)}}),n3=Cs({prefix:"\0",name:"identity",encode:t=>YE(t),decode:t=>ZE(t)});var i3=Object.freeze({__proto__:null,identity:n3});const s3=De({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var o3=Object.freeze({__proto__:null,base2:s3});const a3=De({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var c3=Object.freeze({__proto__:null,base8:a3});const u3=yi({prefix:"9",name:"base10",alphabet:"0123456789"});var l3=Object.freeze({__proto__:null,base10:u3});const h3=De({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),f3=De({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var d3=Object.freeze({__proto__:null,base16:h3,base16upper:f3});const p3=De({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),g3=De({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),y3=De({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),w3=De({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),b3=De({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),m3=De({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),v3=De({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),E3=De({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),x3=De({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var _3=Object.freeze({__proto__:null,base32:p3,base32upper:g3,base32pad:y3,base32padupper:w3,base32hex:b3,base32hexupper:m3,base32hexpad:v3,base32hexpadupper:E3,base32z:x3});const S3=yi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),I3=yi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var D3=Object.freeze({__proto__:null,base36:S3,base36upper:I3});const A3=yi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),$3=yi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var O3=Object.freeze({__proto__:null,base58btc:A3,base58flickr:$3});const B3=De({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),T3=De({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),P3=De({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),R3=De({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var C3=Object.freeze({__proto__:null,base64:B3,base64pad:T3,base64url:P3,base64urlpad:R3});const Uf=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),U3=Uf.reduce((t,e,r)=>(t[r]=e,t),[]),N3=Uf.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function F3(t){return t.reduce((e,r)=>(e+=U3[r],e),"")}function k3(t){const e=[];for(const r of t){const n=N3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const L3=Cs({prefix:"\u{1F680}",name:"base256emoji",encode:F3,decode:k3});var M3=Object.freeze({__proto__:null,base256emoji:L3}),q3=Ff,Nf=128,j3=127,z3=~j3,K3=Math.pow(2,31);function Ff(t,e,r){e=e||[],r=r||0;for(var n=r;t>=K3;)e[r++]=t&255|Nf,t/=128;for(;t&z3;)e[r++]=t&255|Nf,t>>>=7;return e[r]=t|0,Ff.bytes=r-n+1,e}var V3=Wa,H3=128,kf=127;function Wa(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Wa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&kf)<<i:(o&kf)*Math.pow(2,i),i+=7}while(o>=H3);return Wa.bytes=s-n,r}var W3=Math.pow(2,7),G3=Math.pow(2,14),Z3=Math.pow(2,21),Y3=Math.pow(2,28),X3=Math.pow(2,35),J3=Math.pow(2,42),Q3=Math.pow(2,49),ex=Math.pow(2,56),tx=Math.pow(2,63),rx=function(t){return t<W3?1:t<G3?2:t<Z3?3:t<Y3?4:t<X3?5:t<J3?6:t<Q3?7:t<ex?8:t<tx?9:10},nx={encode:q3,decode:V3,encodingLength:rx},Lf=nx;const Mf=(t,e,r=0)=>(Lf.encode(t,e,r),e),qf=t=>Lf.encodingLength(t),Ga=(t,e)=>{const r=e.byteLength,n=qf(t),i=n+qf(r),s=new Uint8Array(i+r);return Mf(t,s,0),Mf(r,s,n),s.set(e,i),new ix(t,r,e,s)};class ix{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const jf=({name:t,code:e,encode:r})=>new sx(t,e,r);class sx{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Ga(this.code,r):r.then(n=>Ga(this.code,n))}else throw Error("Unknown type, must be binary type")}}const zf=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ox=jf({name:"sha2-256",code:18,encode:zf("SHA-256")}),ax=jf({name:"sha2-512",code:19,encode:zf("SHA-512")});var cx=Object.freeze({__proto__:null,sha256:ox,sha512:ax});const Kf=0,ux="identity",Vf=Rf;var lx=Object.freeze({__proto__:null,identity:{code:Kf,name:ux,encode:Vf,digest:t=>Ga(Kf,Vf(t))}});new TextEncoder,new TextDecoder;const Hf={...i3,...o3,...c3,...l3,...d3,..._3,...D3,...O3,...C3,...M3};({...cx,...lx});function Wf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Gf=Wf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Za=Wf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Pf(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Zf={utf8:Gf,"utf-8":Gf,hex:Hf.base16,latin1:Za,ascii:Za,binary:Za,...Hf};function vt(t,e="utf8"){const r=Zf[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ha(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function tt(t,e="utf8"){const r=Zf[e];if(!r)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"):r.encoder.encode(t).substring(1)}const hx={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"}},fx="Input must be an string, Buffer or Uint8Array";function dx(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(fx);return e}function px(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Us(t){return(4294967296+t).toString(16).substring(1)}function gx(t,e,r){let n=`
18
+ `+t+" = ";for(let i=0;i<e.length;i+=2){if(r===32)n+=Us(e[i]).toUpperCase(),n+=" ",n+=Us(e[i+1]).toUpperCase();else if(r===64)n+=Us(e[i+1]).toUpperCase(),n+=Us(e[i]).toUpperCase();else throw new Error("Invalid size "+r);i%6===4?n+=`
19
+ `+new Array(t.length+4).join(" "):i<e.length-2&&(n+=" ")}console.log(n)}function yx(t,e,r){let n=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-n)+"ms"),n=s;for(let o=0;o<r;o++){const a=t(i),c=new Date().getTime(),u=c-n;n=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 Yf={normalizeInput:dx,toHex:px,debugPrint:gx,testSpeed:yx};const Ns=Yf;function Fs(t,e,r){const n=t[e]+t[r];let i=t[e+1]+t[r+1];n>=4294967296&&i++,t[e]=n,t[e+1]=i}function Xf(t,e,r,n){let i=t[e]+r;r<0&&(i+=4294967296);let s=t[e+1]+n;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function Jf(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function br(t,e,r,n,i,s){const o=wi[i],a=wi[i+1],c=wi[s],u=wi[s+1];Fs(X,t,e),Xf(X,t,o,a);let l=X[n]^X[t],f=X[n+1]^X[t+1];X[n]=f,X[n+1]=l,Fs(X,r,n),l=X[e]^X[r],f=X[e+1]^X[r+1],X[e]=l>>>24^f<<8,X[e+1]=f>>>24^l<<8,Fs(X,t,e),Xf(X,t,c,u),l=X[n]^X[t],f=X[n+1]^X[t+1],X[n]=l>>>16^f<<16,X[n+1]=f>>>16^l<<16,Fs(X,r,n),l=X[e]^X[r],f=X[e+1]^X[r+1],X[e]=f>>>31^l<<1,X[e+1]=l>>>31^f<<1}const Qf=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),wx=[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],Fe=new Uint8Array(wx.map(function(t){return t*2})),X=new Uint32Array(32),wi=new Uint32Array(32);function ed(t,e){let r=0;for(r=0;r<16;r++)X[r]=t.h[r],X[r+16]=Qf[r];for(X[24]=X[24]^t.t,X[25]=X[25]^t.t/4294967296,e&&(X[28]=~X[28],X[29]=~X[29]),r=0;r<32;r++)wi[r]=Jf(t.b,4*r);for(r=0;r<12;r++)br(0,8,16,24,Fe[r*16+0],Fe[r*16+1]),br(2,10,18,26,Fe[r*16+2],Fe[r*16+3]),br(4,12,20,28,Fe[r*16+4],Fe[r*16+5]),br(6,14,22,30,Fe[r*16+6],Fe[r*16+7]),br(0,10,20,30,Fe[r*16+8],Fe[r*16+9]),br(2,12,22,24,Fe[r*16+10],Fe[r*16+11]),br(4,14,16,26,Fe[r*16+12],Fe[r*16+13]),br(6,8,18,28,Fe[r*16+14],Fe[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^X[r]^X[r+16]}const mr=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 td(t,e,r,n){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(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(n&&n.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};mr.fill(0),mr[0]=t,e&&(mr[1]=e.length),mr[2]=1,mr[3]=1,r&&mr.set(r,32),n&&mr.set(n,48);for(let s=0;s<16;s++)i.h[s]=Qf[s]^Jf(mr,s*4);return e&&(Ya(i,e),i.c=128),i}function Ya(t,e){for(let r=0;r<e.length;r++)t.c===128&&(t.t+=t.c,ed(t,!1),t.c=0),t.b[t.c++]=e[r]}function rd(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;ed(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3);return e}function nd(t,e,r,n,i){r=r||64,t=Ns.normalizeInput(t),n&&(n=Ns.normalizeInput(n)),i&&(i=Ns.normalizeInput(i));const s=td(r,e,n,i);return Ya(s,t),rd(s)}function bx(t,e,r,n,i){const s=nd(t,e,r,n,i);return Ns.toHex(s)}var mx={blake2b:nd,blake2bHex:bx,blake2bInit:td,blake2bUpdate:Ya,blake2bFinal:rd};const id=Yf;function vx(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vr(t,e,r,n,i,s){te[t]=te[t]+te[e]+i,te[n]=ks(te[n]^te[t],16),te[r]=te[r]+te[n],te[e]=ks(te[e]^te[r],12),te[t]=te[t]+te[e]+s,te[n]=ks(te[n]^te[t],8),te[r]=te[r]+te[n],te[e]=ks(te[e]^te[r],7)}function ks(t,e){return t>>>e^t<<32-e}const sd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=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),Ae=new Uint32Array(16);function od(t,e){let r=0;for(r=0;r<8;r++)te[r]=t.h[r],te[r+8]=sd[r];for(te[12]^=t.t,te[13]^=t.t/4294967296,e&&(te[14]=~te[14]),r=0;r<16;r++)Ae[r]=vx(t.b,4*r);for(r=0;r<10;r++)vr(0,4,8,12,Ae[ke[r*16+0]],Ae[ke[r*16+1]]),vr(1,5,9,13,Ae[ke[r*16+2]],Ae[ke[r*16+3]]),vr(2,6,10,14,Ae[ke[r*16+4]],Ae[ke[r*16+5]]),vr(3,7,11,15,Ae[ke[r*16+6]],Ae[ke[r*16+7]]),vr(0,5,10,15,Ae[ke[r*16+8]],Ae[ke[r*16+9]]),vr(1,6,11,12,Ae[ke[r*16+10]],Ae[ke[r*16+11]]),vr(2,7,8,13,Ae[ke[r*16+12]],Ae[ke[r*16+13]]),vr(3,4,9,14,Ae[ke[r*16+14]],Ae[ke[r*16+15]]);for(r=0;r<8;r++)t.h[r]^=te[r]^te[r+8]}function ad(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const r=e?e.length:0;if(e&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");const n={h:new Uint32Array(sd),b:new Uint8Array(64),c:0,t:0,outlen:t};return n.h[0]^=16842752^r<<8^t,r>0&&(Xa(n,e),n.c=64),n}function Xa(t,e){for(let r=0;r<e.length;r++)t.c===64&&(t.t+=t.c,od(t,!1),t.c=0),t.b[t.c++]=e[r]}function cd(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;od(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3)&255;return e}function ud(t,e,r){r=r||32,t=id.normalizeInput(t);const n=ad(r,e);return Xa(n,t),cd(n)}function Ex(t,e,r){const n=ud(t,e,r);return id.toHex(n)}var xx={blake2s:ud,blake2sHex:Ex,blake2sInit:ad,blake2sUpdate:Xa,blake2sFinal:cd};const bi=mx,mi=xx;var _x={blake2b:bi.blake2b,blake2bHex:bi.blake2bHex,blake2bInit:bi.blake2bInit,blake2bUpdate:bi.blake2bUpdate,blake2bFinal:bi.blake2bFinal,blake2s:mi.blake2s,blake2sHex:mi.blake2sHex,blake2sInit:mi.blake2sInit,blake2sUpdate:mi.blake2sUpdate,blake2sFinal:mi.blake2sFinal};const Sx=":";function Ls(t){const[e,r]=t.split(Sx);return{namespace:e,reference:r}}function ld(t,e){return t.includes(":")?[t]:e.chains||[]}var Ix=Object.defineProperty,Dx=Object.defineProperties,Ax=Object.getOwnPropertyDescriptors,hd=Object.getOwnPropertySymbols,$x=Object.prototype.hasOwnProperty,Ox=Object.prototype.propertyIsEnumerable,Ja=(t,e,r)=>e in t?Ix(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fd=(t,e)=>{for(var r in e||(e={}))$x.call(e,r)&&Ja(t,r,e[r]);if(hd)for(var r of hd(e))Ox.call(e,r)&&Ja(t,r,e[r]);return t},Bx=(t,e)=>Dx(t,Ax(e)),dd=(t,e,r)=>Ja(t,typeof e!="symbol"?e+"":e,r);const Tx="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},Px="js";function Ms(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Er(){return!Wr()&&!!ta()&&navigator.product===Tx}function Rx(){return Er()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function Cx(){return Er()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Pn(){return!Ms()&&!!ta()&&!!Wr()}function vi(){return Er()?ft.reactNative:Ms()?ft.node:Pn()?ft.browser:ft.unknown}function pd(){var t;try{return Er()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Ux(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([n],[i])=>n.localeCompare(i)).forEach(([n,i])=>{i!=null&&r.set(n,String(i))}),r.toString()}function Nx(t){var e,r;const n=gd();try{return t!=null&&t.url&&n.url&&new URL(t.url).host!==new URL(n.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${n.url}. This is probably unintended and can lead to issues.`),t.url=n.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),Bx(fd(fd({},n),t),{url:t?.url||n.url,name:t?.name||n.name,description:t?.description||n.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:n.icons})}catch(i){return console.warn("Error populating app metadata",i),t||n}}function gd(){return Ql()||{name:"",description:"",url:"",icons:[""]}}function Fx(){if(vi()===ft.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:r,Version:n}=global.Platform;return[r,n].join("-")}const t=Cm();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 kx(){var t;const e=vi();return e===ft.browser?[e,((t=Jl())==null?void 0:t.host)||"unknown"].join(":"):e}function yd(t,e,r){const n=Fx(),i=kx();return[[t,e].join("-"),[Px,r].join("-"),n,i].join("/")}function Lx({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=yd(t,e,n),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=Ux(u[1]||"",f);return u[0]+"?"+h}function en(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Qa(t){return Object.fromEntries(t.entries())}function ec(t){return new Map(Object.entries(t))}function tn(t=M.FIVE_MINUTES,e){const r=M.toMiliseconds(t||M.FIVE_MINUTES);let n,i,s,o;return{resolve:a=>{s&&n&&(clearTimeout(s),n(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},r),n=a,i=c})}}function Lt(t,e,r){return new Promise(async(n,i)=>{const s=setTimeout(()=>i(new Error(r)),e);try{const o=await t;n(o)}catch(o){i(o)}clearTimeout(s)})}function wd(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 Mx(t){return wd("topic",t)}function qx(t){return wd("id",t)}function bd(t){const[e,r]=t.split(":"),n={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")n.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))n.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return n}function me(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function xr(t){return Date.now()>=M.toMiliseconds(t)}function ie(t,e){return`${t}${e?`:${e}`:""}`}function rn(t=[],e=[]){return[...new Set([...t,...e])]}async function jx({id:t,topic:e,wcDeepLink:r}){var n;try{if(!r)return;const i=typeof r=="string"?JSON.parse(r):r,s=i?.href;if(typeof s!="string")return;const o=zx(s,t,e),a=vi();if(a===ft.browser){if(!((n=Wr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Kx(o)}else a===ft.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function zx(t,e,r){const n=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${Gx(n,!0)}`}else i=`${i}/wc?${n}`;return i}function Kx(t){let e="_self";Wx()?e="_top":(Hx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Vx(t,e){let r="";try{if(Pn()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function md(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function vd(){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 tc(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Hx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Wx(){try{return window.self!==window.top}catch{return!1}}function Gx(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Ed(t){return Buffer.from(t,"base64").toString("utf-8")}function Zx(t){return new Promise(e=>setTimeout(e,t))}class Yx{constructor({limit:e}){dd(this,"limit"),dd(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}}const qs=BigInt(2**32-1),xd=BigInt(32);function _d(t,e=!1){return e?{h:Number(t&qs),l:Number(t>>xd&qs)}:{h:Number(t>>xd&qs)|0,l:Number(t&qs)|0}}function Sd(t,e=!1){const r=t.length;let n=new Uint32Array(r),i=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=_d(t[s],e);[n[s],i[s]]=[o,a]}return[n,i]}const Id=(t,e,r)=>t>>>r,Dd=(t,e,r)=>t<<32-r|e>>>r,_r=(t,e,r)=>t>>>r|e<<32-r,Sr=(t,e,r)=>t<<32-r|e>>>r,Ei=(t,e,r)=>t<<64-r|e>>>r-32,xi=(t,e,r)=>t>>>r-32|e<<64-r,Xx=(t,e)=>e,Jx=(t,e)=>t,Qx=(t,e,r)=>t<<r|e>>>32-r,e_=(t,e,r)=>e<<r|t>>>32-r,t_=(t,e,r)=>e<<r-32|t>>>64-r,r_=(t,e,r)=>t<<r-32|e>>>64-r;function Ot(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const rc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),nc=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,n_=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),i_=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,s_=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),o_=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,Rn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function js(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Bt(t,...e){if(!js(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 zs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");tr(t.outputLen),tr(t.blockLen)}function Ir(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 ic(t,e){Bt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function _i(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function sc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mt(t,e){return t<<32-e|t>>>e}const Ad=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function $d(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const rr=Ad?t=>t:t=>$d(t);function a_(t){for(let e=0;e<t.length;e++)t[e]=$d(t[e]);return t}const Dr=Ad?t=>t:a_,Od=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",c_=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cn(t){if(Bt(t),Od)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=c_[t[r]];return e}const nr={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bd(t){if(t>=nr._0&&t<=nr._9)return t-nr._0;if(t>=nr.A&&t<=nr.F)return t-(nr.A-10);if(t>=nr.a&&t<=nr.f)return t-(nr.a-10)}function Ks(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Od)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const n=new Uint8Array(r);for(let i=0,s=0;i<r;i++,s+=2){const o=Bd(t.charCodeAt(s)),a=Bd(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}n[i]=o*16+a}return n}function Td(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Tt(t){return typeof t=="string"&&(t=Td(t)),Bt(t),t}function Ar(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Bt(i),e+=i.length}const r=new Uint8Array(e);for(let n=0,i=0;n<t.length;n++){const s=t[n];r.set(s,i),i+=s.length}return r}class Vs{}function Si(t){const e=n=>t().update(Tt(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function u_(t){const e=(n,i)=>t(i).update(Tt(n)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}function nn(t=32){if(Rn&&typeof Rn.getRandomValues=="function")return Rn.getRandomValues(new Uint8Array(t));if(Rn&&typeof Rn.randomBytes=="function")return Uint8Array.from(Rn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const l_=BigInt(0),Ii=BigInt(1),h_=BigInt(2),f_=BigInt(7),d_=BigInt(256),p_=BigInt(113),Pd=[],Rd=[],Cd=[];for(let t=0,e=Ii,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Pd.push(2*(5*n+r)),Rd.push((t+1)*(t+2)/2%64);let i=l_;for(let s=0;s<7;s++)e=(e<<Ii^(e>>f_)*p_)%d_,e&h_&&(i^=Ii<<(Ii<<BigInt(s))-Ii);Cd.push(i)}const Ud=Sd(Cd,!0),g_=Ud[0],y_=Ud[1],Nd=(t,e,r)=>r>32?t_(t,e,r):Qx(t,e,r),Fd=(t,e,r)=>r>32?r_(t,e,r):e_(t,e,r);function w_(t,e=24){const r=new Uint32Array(10);for(let n=24-e;n<24;n++){for(let o=0;o<10;o++)r[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=r[c],l=r[c+1],f=Nd(u,l,1)^r[a],h=Fd(u,l,1)^r[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Rd[o],c=Nd(i,s,a),u=Fd(i,s,a),l=Pd[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=g_[n],t[1]^=y_[n]}Et(r)}class oc extends Vs{constructor(e,r,n,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,tr(n),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=_i(this.state)}clone(){return this._cloneInto()}keccak(){Dr(this.state32),w_(this.state32,this.rounds),Dr(this.state32),this.posOut=0,this.pos=0}update(e){Ir(this),e=Tt(e),Bt(e);const{blockLen:r,state:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);for(let a=0;a<o;a++)n[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:n,blockLen:i}=this;e[n]^=r,r&128&&n===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Ir(this,!1),Bt(e),this.finish();const r=this.state,{blockLen:n}=this;for(let i=0,s=e.length;i<s;){this.posOut>=n&&this.keccak();const o=Math.min(n-this.posOut,s-i);e.set(r.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=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 tr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ic(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,Et(this.state)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new oc(r,n,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=n,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const b_=(t,e,r)=>Si(()=>new oc(e,t,r)),m_=b_(1,136,256/8);function v_(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function E_(t,e,r){return t&e^~t&r}function x_(t,e,r){return t&e^t&r^e&r}class kd extends Vs{constructor(e,r,n,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.buffer=new Uint8Array(e),this.view=sc(this.buffer)}update(e){Ir(this),e=Tt(e),Bt(e);const{view:r,buffer:n,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=sc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ir(this),ic(e,this),this.finished=!0;const{buffer:r,view:n,blockLen:i,isLE:s}=this;let{pos:o}=this;r[o++]=128,Et(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(n,0),o=0);for(let f=o;f<i;f++)r[f]=0;v_(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=sc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:n,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%r&&e.buffer.set(n),e}clone(){return this._cloneInto()}}const $r=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),__=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]),Or=new Uint32Array(64);class S_ extends kd{constructor(e=32){super(64,e,8,!1),this.A=$r[0]|0,this.B=$r[1]|0,this.C=$r[2]|0,this.D=$r[3]|0,this.E=$r[4]|0,this.F=$r[5]|0,this.G=$r[6]|0,this.H=$r[7]|0}get(){const{A:e,B:r,C:n,D:i,E:s,F:o,G:a,H:c}=this;return[e,r,n,i,s,o,a,c]}set(e,r,n,i,s,o,a,c){this.A=e|0,this.B=r|0,this.C=n|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Or[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const h=Or[f-15],d=Or[f-2],p=Mt(h,7)^Mt(h,18)^h>>>3,g=Mt(d,17)^Mt(d,19)^d>>>10;Or[f]=g+Or[f-7]+p+Or[f-16]|0}let{A:n,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=Mt(a,6)^Mt(a,11)^Mt(a,25),d=l+h+E_(a,c,u)+__[f]+Or[f]|0,p=(Mt(n,2)^Mt(n,13)^Mt(n,22))+x_(n,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=n,n=d+p|0}n=n+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(n,i,s,o,a,c,u,l)}roundClean(){Et(Or)}destroy(){this.set(0,0,0,0,0,0,0,0),Et(this.buffer)}}const Ld=Sd(["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))),I_=Ld[0],D_=Ld[1],Br=new Uint32Array(80),Tr=new Uint32Array(80);class ac extends kd{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:r,Bh:n,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w]}set(e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=n|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,r){for(let E=0;E<16;E++,r+=4)Br[E]=e.getUint32(r),Tr[E]=e.getUint32(r+=4);for(let E=16;E<80;E++){const O=Br[E-15]|0,R=Tr[E-15]|0,C=_r(O,R,1)^_r(O,R,8)^Id(O,R,7),U=Sr(O,R,1)^Sr(O,R,8)^Dd(O,R,7),N=Br[E-2]|0,$=Tr[E-2]|0,G=_r(N,$,19)^Ei(N,$,61)^Id(N,$,6),W=Sr(N,$,19)^xi(N,$,61)^Dd(N,$,6),P=n_(U,W,Tr[E-7],Tr[E-16]),v=i_(P,C,G,Br[E-7],Br[E-16]);Br[E]=v|0,Tr[E]=P|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:w,Hh:S,Hl:D}=this;for(let E=0;E<80;E++){const O=_r(f,h,14)^_r(f,h,18)^Ei(f,h,41),R=Sr(f,h,14)^Sr(f,h,18)^xi(f,h,41),C=f&d^~f&g,U=h&p^~h&w,N=s_(D,R,U,D_[E],Tr[E]),$=o_(N,S,O,C,I_[E],Br[E]),G=N|0,W=_r(n,i,28)^Ei(n,i,34)^Ei(n,i,39),P=Sr(n,i,28)^xi(n,i,34)^xi(n,i,39),v=n&s^n&a^s&a,m=i&o^i&c^o&c;S=g|0,D=w|0,g=d|0,w=p|0,d=f|0,p=h|0,{h:f,l:h}=Ot(u|0,l|0,$|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const y=rc(G,P,m);n=nc(y,$,W,v),i=y|0}({h:n,l:i}=Ot(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=Ot(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Ot(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Ot(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=Ot(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=Ot(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=Ot(this.Gh|0,this.Gl|0,g|0,w|0),{h:S,l:D}=Ot(this.Hh|0,this.Hl|0,S|0,D|0),this.set(n,i,s,o,a,c,u,l,f,h,d,p,g,w,S,D)}roundClean(){Et(Br,Tr)}destroy(){Et(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class A_ extends ac{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const qe=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class $_ extends ac{constructor(){super(32),this.Ah=qe[0]|0,this.Al=qe[1]|0,this.Bh=qe[2]|0,this.Bl=qe[3]|0,this.Ch=qe[4]|0,this.Cl=qe[5]|0,this.Dh=qe[6]|0,this.Dl=qe[7]|0,this.Eh=qe[8]|0,this.El=qe[9]|0,this.Fh=qe[10]|0,this.Fl=qe[11]|0,this.Gh=qe[12]|0,this.Gl=qe[13]|0,this.Hh=qe[14]|0,this.Hl=qe[15]|0}}const Hs=Si(()=>new S_),O_=Si(()=>new ac),B_=Si(()=>new A_),T_=Si(()=>new $_),P_=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]),ve=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),K=new Uint32Array(32);function Pr(t,e,r,n,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*r],d=K[2*r+1],p=K[2*n],g=K[2*n+1],w=rc(c,l,o);u=nc(w,u,f,a),c=w|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:Xx(g,p),Dl:Jx(g)},{h:d,l:h}=Ot(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:_r(f,l,24),Bl:Sr(f,l,24)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*r]=h,K[2*r+1]=d,K[2*n]=p,K[2*n+1]=g}function Rr(t,e,r,n,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*r],d=K[2*r+1],p=K[2*n],g=K[2*n+1],w=rc(c,l,o);u=nc(w,u,f,a),c=w|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:_r(g,p,16),Dl:Sr(g,p,16)},{h:d,l:h}=Ot(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:Ei(f,l,63),Bl:xi(f,l,63)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*r]=h,K[2*r+1]=d,K[2*n]=p,K[2*n+1]=g}function R_(t,e={},r,n,i){if(tr(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==n)throw new Error("salt must be undefined or "+n);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class C_ extends Vs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,tr(e),tr(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=_i(this.buffer)}update(e){Ir(this),e=Tt(e),Bt(e);const{blockLen:r,buffer:n,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===r&&(Dr(i),this.compress(i,0,!1),Dr(i),this.pos=0);const u=Math.min(r-this.pos,s-c),l=o+c;if(u===r&&!(l%4)&&c+u<s){const f=new Uint32Array(a,l,Math.floor((s-c)/4));Dr(f);for(let h=0;c+r<s;h+=i.length,c+=r)this.length+=r,this.compress(f,h,!1);Dr(f);continue}n.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){Ir(this),ic(e,this);const{pos:r,buffer32:n}=this;this.finished=!0,Et(this.buffer.subarray(r)),Dr(n),this.compress(n,0,!0),Dr(n);const i=_i(e);this.get().forEach((s,o)=>i[o]=rr(s))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}_cloneInto(e){const{buffer:r,length:n,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=s,e.finished=i,e.length=n,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class U_ extends C_{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=ve[0]|0,this.v0h=ve[1]|0,this.v1l=ve[2]|0,this.v1h=ve[3]|0,this.v2l=ve[4]|0,this.v2h=ve[5]|0,this.v3l=ve[6]|0,this.v3h=ve[7]|0,this.v4l=ve[8]|0,this.v4h=ve[9]|0,this.v5l=ve[10]|0,this.v5h=ve[11]|0,this.v6l=ve[12]|0,this.v6h=ve[13]|0,this.v7l=ve[14]|0,this.v7h=ve[15]|0,R_(r,e,64,16,16);let{key:n,personalization:i,salt:s}=e,o=0;if(n!==void 0&&(n=Tt(n),o=n.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Tt(s);const a=_i(s);this.v4l^=rr(a[0]),this.v4h^=rr(a[1]),this.v5l^=rr(a[2]),this.v5h^=rr(a[3])}if(i!==void 0){i=Tt(i);const a=_i(i);this.v6l^=rr(a[0]),this.v6h^=rr(a[1]),this.v7l^=rr(a[2]),this.v7h^=rr(a[3])}if(n!==void 0){const a=new Uint8Array(this.blockLen);a.set(n),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:n,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:f,v5h:h,v6l:d,v6h:p,v7l:g,v7h:w}=this;return[e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w]}set(e,r,n,i,s,o,a,c,u,l,f,h,d,p,g,w){this.v0l=e|0,this.v0h=r|0,this.v1l=n|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=h|0,this.v6l=d|0,this.v6h=p|0,this.v7l=g|0,this.v7h=w|0}compress(e,r,n){this.get().forEach((c,u)=>K[u]=c),K.set(ve,16);let{h:i,l:s}=_d(BigInt(this.length));K[24]=ve[8]^s,K[25]=ve[9]^i,n&&(K[28]=~K[28],K[29]=~K[29]);let o=0;const a=P_;for(let c=0;c<12;c++)Pr(0,4,8,12,e,r+2*a[o++]),Rr(0,4,8,12,e,r+2*a[o++]),Pr(1,5,9,13,e,r+2*a[o++]),Rr(1,5,9,13,e,r+2*a[o++]),Pr(2,6,10,14,e,r+2*a[o++]),Rr(2,6,10,14,e,r+2*a[o++]),Pr(3,7,11,15,e,r+2*a[o++]),Rr(3,7,11,15,e,r+2*a[o++]),Pr(0,5,10,15,e,r+2*a[o++]),Rr(0,5,10,15,e,r+2*a[o++]),Pr(1,6,11,12,e,r+2*a[o++]),Rr(1,6,11,12,e,r+2*a[o++]),Pr(2,7,8,13,e,r+2*a[o++]),Rr(2,7,8,13,e,r+2*a[o++]),Pr(3,4,9,14,e,r+2*a[o++]),Rr(3,4,9,14,e,r+2*a[o++]);this.v0l^=K[0]^K[16],this.v0h^=K[1]^K[17],this.v1l^=K[2]^K[18],this.v1h^=K[3]^K[19],this.v2l^=K[4]^K[20],this.v2h^=K[5]^K[21],this.v3l^=K[6]^K[22],this.v3h^=K[7]^K[23],this.v4l^=K[8]^K[24],this.v4h^=K[9]^K[25],this.v5l^=K[10]^K[26],this.v5h^=K[11]^K[27],this.v6l^=K[12]^K[28],this.v6h^=K[13]^K[29],this.v7l^=K[14]^K[30],this.v7h^=K[15]^K[31],Et(K)}destroy(){this.destroyed=!0,Et(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const N_=u_(t=>new U_(t)),F_="https://rpc.walletconnect.org/v1";function Md(t){const e=`Ethereum Signed Message:
20
+ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(m_(r)).toString("hex")}async function k_(t,e,r,n,i,s){switch(r.t){case"eip191":return await L_(t,e,r.s);case"eip1271":return await M_(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function L_(t,e,r){return(await P2({hash:Md(e),signature:r})).toLowerCase()===t.toLowerCase()}async function M_(t,e,r,n,i,s){const o=Ls(n);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${n}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),f=(e.startsWith("0x")?e:Md(e)).substring(2),h=a+f+c+l+u,d=await fetch(`${s||F_}/?chainId=${n}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:q_(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:p}=await d.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function q_(){return Date.now()+Math.floor(Math.random()*1e3)}function j_(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const n=r[0];if(n===0)throw new Error("No signatures found");const i=1+n*64;if(r.length<i)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return ui.encode(s)}function z_(t){const e=new Uint8Array(Buffer.from(t,"base64")),r=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),n=new Uint8Array(r.length+e.length);n.set(r),n.set(e,r.length);const i=N_(n,{dkLen:32});return ui.encode(i)}function qd(t){const e=new Uint8Array(Hs(K_(t)));return ui.encode(e)}function K_(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 jd(t){const e=Buffer.from(t,"base64"),r=qE(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const n=RE(r),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(n)]),o=T_(s);return zE.encode(o).replace(/=+$/,"")}function cc(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),Buffer.from(e)}function V_(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),r=Buffer.from(t.signed.authInfoBytes,"base64"),n=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(cc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(cc(r.length)),i.push(r),i.push(Buffer.from([26])),i.push(cc(n.length)),i.push(n);const s=Buffer.concat(i),o=Hs(s);return Buffer.from(o).toString("hex").toUpperCase()}function H_(t){var e,r;const n=[];try{if(typeof t=="string")return n.push(t),n;if(typeof t!="object")return n;t!=null&&t.id&&n.push(t.id);const i=(r=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:r.transactionHashes;i&&n.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return n}var W_=Object.defineProperty,G_=Object.defineProperties,Z_=Object.getOwnPropertyDescriptors,zd=Object.getOwnPropertySymbols,Y_=Object.prototype.hasOwnProperty,X_=Object.prototype.propertyIsEnumerable,Kd=(t,e,r)=>e in t?W_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J_=(t,e)=>{for(var r in e||(e={}))Y_.call(e,r)&&Kd(t,r,e[r]);if(zd)for(var r of zd(e))X_.call(e,r)&&Kd(t,r,e[r]);return t},Q_=(t,e)=>G_(t,Z_(e));const e8="did:pkh:",uc=t=>t?.split(":"),t8=t=>{const e=t&&uc(t);if(e)return t.includes(e8)?e[3]:e[1]},lc=t=>{const e=t&&uc(t);if(e)return e[2]+":"+e[3]},Ws=t=>{const e=t&&uc(t);if(e)return e.pop()};async function Vd(t){const{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=Hd(i,i.iss),o=Ws(i.iss);return await k_(o,s,n,lc(i.iss),r)}const Hd=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,n=Ws(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${t8(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(g=>`
21
+ - ${g}`).join("")}`:void 0,p=Gs(t.resources);if(p){const g=Di(p);i=l8(i,g)}return[r,n,"",i,"",s,o,a,c,u,l,f,h,d].filter(g=>g!=null).join(`
22
+ `)};function r8(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function n8(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function sn(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(r=>{const n=t.att[r];if(Array.isArray(n))throw new Error(`Resource must be an object: ${r}`);if(typeof n!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(n).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(n).forEach(i=>{const s=n[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function i8(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:s8(e,r,n)}}}function s8(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function Wd(t){return sn(t),`urn:recap:${r8(t).replace(/=/g,"")}`}function Di(t){const e=n8(t.replace("urn:recap:",""));return sn(e),e}function o8(t,e,r){const n=i8(t,e,r);return Wd(n)}function a8(t){return t&&t.includes("urn:recap:")}function c8(t,e){const r=Di(t),n=Di(e),i=u8(r,n);return Wd(i)}function u8(t,e){sn(t),sn(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),n={att:{}};return r.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;n.att[i]=Q_(J_({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function l8(t="",e){sn(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const n=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,h)=>f.action.localeCompare(h.action));const u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});const l=Object.keys(u).map(f=>(i++,`(${i}) '${f}': '${u[f].join("', '")}' for '${a}'.`));n.push(l.join(", ").replace(".,","."))});const s=n.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function Gd(t){var e;const r=Di(t);sn(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Zd(t){const e=Di(t);sn(e);const r=[];return Object.values(e.att).forEach(n=>{Object.values(n).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&r.push(i[0].chains)})}),[...new Set(r.flat())]}function Gs(t){if(!t)return;const e=t?.[t.length-1];return a8(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Yd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function hc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function fc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function rt(t,...e){if(!Yd(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 Xd(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 h8(t,e){rt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Cr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Un(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function f8(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const d8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function p8(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function dc(t){if(typeof t=="string")t=p8(t);else if(Yd(t))t=pc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function g8(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function y8(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return r===0}const w8=(t,e)=>{function r(n,...i){if(rt(n),!d8)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?rt(u):rt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&rt(i[1]);const o=e(n,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");rt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,rt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(rt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function Jd(t,e,r=!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(r&&!m8(e))throw new Error("invalid output, must be aligned");return e}function Qd(t,e,r,n){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,n);const i=BigInt(32),s=BigInt(4294967295),o=Number(r>>i&s),a=Number(r&s),c=n?4:0,u=n?0:4;t.setUint32(e+c,o,n),t.setUint32(e+u,a,n)}function b8(t,e,r){hc(r);const n=new Uint8Array(16),i=f8(n);return Qd(i,0,BigInt(e),r),Qd(i,8,BigInt(t),r),n}function m8(t){return t.byteOffset%4===0}function pc(t){return Uint8Array.from(t)}const ep=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),v8=ep("expand 16-byte k"),E8=ep("expand 32-byte k"),x8=Cr(v8),_8=Cr(E8);function re(t,e){return t<<e|t>>>32-e}function gc(t){return t.byteOffset%4===0}const Zs=64,S8=16,tp=2**32-1,rp=new Uint32Array;function I8(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(Zs),l=Cr(u),f=gc(i)&&gc(s),h=f?Cr(i):rp,d=f?Cr(s):rp;for(let p=0;p<c;o++){if(t(e,r,n,l,o,a),o>=tp)throw new Error("arx: counter overflow");const g=Math.min(Zs,c-p);if(f&&g===Zs){const w=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let S=0,D;S<S8;S++)D=w+S,d[D]=h[D]^l[S];p+=Zs;continue}for(let w=0,S;w<g;w++)S=p+w,s[S]=i[S]^u[w];p+=g}}function D8(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=g8({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return fc(i),fc(o),hc(s),hc(r),(a,c,u,l,f=0)=>{rt(a),rt(c),rt(u);const h=u.length;if(l===void 0&&(l=new Uint8Array(h)),rt(l),fc(f),f<0||f>=tp)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p=a.length,g,w;if(p===32)d.push(g=pc(a)),w=_8;else if(p===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),w=x8,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);gc(c)||d.push(c=pc(c));const S=Cr(g);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(w,S,Cr(c.subarray(0,16)),S),c=c.subarray(16)}const D=16-i;if(D!==c.length)throw new Error(`arx: nonce must be ${D} or 16 bytes`);if(D!==12){const O=new Uint8Array(12);O.set(c,s?0:12-c.length),c=O,d.push(c)}const E=Cr(c);return I8(t,w,S,E,u,l,f,o),Un(...d),l}}const $e=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class A8{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=dc(e),rt(e,32);const r=$e(e,0),n=$e(e,2),i=$e(e,4),s=$e(e,6),o=$e(e,8),a=$e(e,10),c=$e(e,12),u=$e(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|n<<3)&8191,this.r[2]=(n>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>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 l=0;l<8;l++)this.pad[l]=$e(e,16+2*l)}process(e,r,n=!1){const i=n?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],f=o[4],h=o[5],d=o[6],p=o[7],g=o[8],w=o[9],S=$e(e,r+0),D=$e(e,r+2),E=$e(e,r+4),O=$e(e,r+6),R=$e(e,r+8),C=$e(e,r+10),U=$e(e,r+12),N=$e(e,r+14);let $=s[0]+(S&8191),G=s[1]+((S>>>13|D<<3)&8191),W=s[2]+((D>>>10|E<<6)&8191),P=s[3]+((E>>>7|O<<9)&8191),v=s[4]+((O>>>4|R<<12)&8191),m=s[5]+(R>>>1&8191),y=s[6]+((R>>>14|C<<2)&8191),b=s[7]+((C>>>11|U<<5)&8191),_=s[8]+((U>>>8|N<<8)&8191),A=s[9]+(N>>>5|i),x=0,I=x+$*a+G*(5*w)+W*(5*g)+P*(5*p)+v*(5*d);x=I>>>13,I&=8191,I+=m*(5*h)+y*(5*f)+b*(5*l)+_*(5*u)+A*(5*c),x+=I>>>13,I&=8191;let B=x+$*c+G*a+W*(5*w)+P*(5*g)+v*(5*p);x=B>>>13,B&=8191,B+=m*(5*d)+y*(5*h)+b*(5*f)+_*(5*l)+A*(5*u),x+=B>>>13,B&=8191;let T=x+$*u+G*c+W*a+P*(5*w)+v*(5*g);x=T>>>13,T&=8191,T+=m*(5*p)+y*(5*d)+b*(5*h)+_*(5*f)+A*(5*l),x+=T>>>13,T&=8191;let j=x+$*l+G*u+W*c+P*a+v*(5*w);x=j>>>13,j&=8191,j+=m*(5*g)+y*(5*p)+b*(5*d)+_*(5*h)+A*(5*f),x+=j>>>13,j&=8191;let L=x+$*f+G*l+W*u+P*c+v*a;x=L>>>13,L&=8191,L+=m*(5*w)+y*(5*g)+b*(5*p)+_*(5*d)+A*(5*h),x+=L>>>13,L&=8191;let k=x+$*h+G*f+W*l+P*u+v*c;x=k>>>13,k&=8191,k+=m*a+y*(5*w)+b*(5*g)+_*(5*p)+A*(5*d),x+=k>>>13,k&=8191;let z=x+$*d+G*h+W*f+P*l+v*u;x=z>>>13,z&=8191,z+=m*c+y*a+b*(5*w)+_*(5*g)+A*(5*p),x+=z>>>13,z&=8191;let H=x+$*p+G*d+W*h+P*f+v*l;x=H>>>13,H&=8191,H+=m*u+y*c+b*a+_*(5*w)+A*(5*g),x+=H>>>13,H&=8191;let Z=x+$*g+G*p+W*d+P*h+v*f;x=Z>>>13,Z&=8191,Z+=m*l+y*u+b*c+_*a+A*(5*w),x+=Z>>>13,Z&=8191;let V=x+$*w+G*g+W*p+P*d+v*h;x=V>>>13,V&=8191,V+=m*f+y*l+b*u+_*c+A*a,x+=V>>>13,V&=8191,x=(x<<2)+x|0,x=x+I|0,I=x&8191,x=x>>>13,B+=x,s[0]=I,s[1]=B,s[2]=T,s[3]=j,s[4]=L,s[5]=k,s[6]=z,s[7]=H,s[8]=Z,s[9]=V}finalize(){const{h:e,pad:r}=this,n=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,n[0]=e[0]+5,i=n[0]>>>13,n[0]&=8191;for(let a=1;a<10;a++)n[a]=e[a]+i,i=n[a]>>>13,n[a]&=8191;n[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)n[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|n[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]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Un(n)}update(e){Xd(this),e=dc(e),rt(e);const{buffer:r,blockLen:n}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);if(o===n){for(;n<=i-s;s+=n)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===n&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Un(this.h,this.r,this.buffer,this.pad)}digestInto(e){Xd(this),h8(e,this),this.finished=!0;const{buffer:r,h:n}=this;let{pos:i}=this;if(i){for(r[i++]=1;i<16;i++)r[i]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=n[o]>>>0,e[s++]=n[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const n=e.slice(0,r);return this.destroy(),n}}function $8(t){const e=(n,i)=>t(i).update(dc(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const O8=$8(t=>new A8(t));function B8(t,e,r,n,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],h=e[2],d=e[3],p=e[4],g=e[5],w=e[6],S=e[7],D=i,E=r[0],O=r[1],R=r[2],C=o,U=a,N=c,$=u,G=l,W=f,P=h,v=d,m=p,y=g,b=w,_=S,A=D,x=E,I=O,B=R;for(let j=0;j<s;j+=2)C=C+G|0,A=re(A^C,16),m=m+A|0,G=re(G^m,12),C=C+G|0,A=re(A^C,8),m=m+A|0,G=re(G^m,7),U=U+W|0,x=re(x^U,16),y=y+x|0,W=re(W^y,12),U=U+W|0,x=re(x^U,8),y=y+x|0,W=re(W^y,7),N=N+P|0,I=re(I^N,16),b=b+I|0,P=re(P^b,12),N=N+P|0,I=re(I^N,8),b=b+I|0,P=re(P^b,7),$=$+v|0,B=re(B^$,16),_=_+B|0,v=re(v^_,12),$=$+v|0,B=re(B^$,8),_=_+B|0,v=re(v^_,7),C=C+W|0,B=re(B^C,16),b=b+B|0,W=re(W^b,12),C=C+W|0,B=re(B^C,8),b=b+B|0,W=re(W^b,7),U=U+P|0,A=re(A^U,16),_=_+A|0,P=re(P^_,12),U=U+P|0,A=re(A^U,8),_=_+A|0,P=re(P^_,7),N=N+v|0,x=re(x^N,16),m=m+x|0,v=re(v^m,12),N=N+v|0,x=re(x^N,8),m=m+x|0,v=re(v^m,7),$=$+G|0,I=re(I^$,16),y=y+I|0,G=re(G^y,12),$=$+G|0,I=re(I^$,8),y=y+I|0,G=re(G^y,7);let T=0;n[T++]=o+C|0,n[T++]=a+U|0,n[T++]=c+N|0,n[T++]=u+$|0,n[T++]=l+G|0,n[T++]=f+W|0,n[T++]=h+P|0,n[T++]=d+v|0,n[T++]=p+m|0,n[T++]=g+y|0,n[T++]=w+b|0,n[T++]=S+_|0,n[T++]=D+A|0,n[T++]=E+x|0,n[T++]=O+I|0,n[T++]=R+B|0}const T8=D8(B8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),P8=new Uint8Array(16),np=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(P8.subarray(r))},R8=new Uint8Array(32);function ip(t,e,r,n,i){const s=t(e,r,R8),o=O8.create(s);i&&np(o,i),np(o,n);const a=b8(n.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Un(s,a),c}const C8=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=Jd(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=ip(t,e,r,a,n);return s.set(c,o),Un(c),s},decrypt(i,s){s=Jd(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=ip(t,e,r,o,n);if(!y8(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),Un(c),s}}),sp=w8({blockSize:64,nonceLength:12,tagLength:16},C8(T8));class op extends Vs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,zs(e);const n=Tt(r);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 i=this.blockLen,s=new Uint8Array(i);s.set(n.length>i?e.create().update(n).digest():n);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Et(s)}update(e){return Ir(this),this.iHash.update(e),this}digestInto(e){Ir(this),Bt(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:r,iHash:n,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=n._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ys=(t,e,r)=>new op(t,e).update(r).digest();Ys.create=(t,e)=>new op(t,e);function U8(t,e,r){return zs(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Ys(t,Tt(r),Tt(e))}const yc=Uint8Array.from([0]),ap=Uint8Array.of();function N8(t,e,r,n=32){zs(t),tr(n);const i=t.outputLen;if(n>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(n/i);r===void 0&&(r=ap);const o=new Uint8Array(s*i),a=Ys.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)yc[0]=l+1,c.update(l===0?ap:u).update(r).update(yc).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),Et(u,yc),o.slice(0,n)}const F8=(t,e,r,n,i)=>N8(t,U8(t,e,r),n,i),Xs=Hs,wc=BigInt(0),bc=BigInt(1);function Js(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function on(t,e,r=""){const n=js(t),i=t?.length,s=e!==void 0;if(!n||s&&i!==e){const o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=n?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function cp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?wc:BigInt("0x"+t)}function eo(t){return cp(Cn(t))}function to(t){return Bt(t),cp(Cn(Uint8Array.from(t).reverse()))}function mc(t,e){return Ks(t.toString(16).padStart(e*2,"0"))}function vc(t,e){return mc(t,e).reverse()}function je(t,e,r){let n;if(typeof e=="string")try{n=Ks(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(js(e))n=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=n.length;if(typeof r=="number"&&i!==r)throw new Error(t+" of length "+r+" expected, got "+i);return n}const Ec=t=>typeof t=="bigint"&&wc<=t;function k8(t,e,r){return Ec(t)&&Ec(e)&&Ec(r)&&e<=t&&t<r}function xc(t,e,r,n){if(!k8(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function up(t){let e;for(e=0;t>wc;t>>=bc,e+=1);return e}const Ai=t=>(bc<<BigInt(t))-bc;function L8(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const n=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=n(t),o=n(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...h)=>r(o,s,...h),l=(h=n(0))=>{o=u(i(0),h),s=u(),h.length!==0&&(o=u(i(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const d=[];for(;h<e;){s=u();const p=s.slice();d.push(p),h+=s.length}return Ar(...d)};return(h,d)=>{c(),l(h);let p;for(;!(p=d(f()));)l();return c(),p}}function ro(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function n(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>n(i,s,!1)),Object.entries(r).forEach(([i,s])=>n(i,s,!0))}function lp(t){const e=new WeakMap;return(r,...n)=>{const i=e.get(r);if(i!==void 0)return i;const s=t(r,...n);return e.set(r,s),s}}const nt=BigInt(0),Ze=BigInt(1),an=BigInt(2),hp=BigInt(3),fp=BigInt(4),dp=BigInt(5),M8=BigInt(7),pp=BigInt(8),q8=BigInt(9),gp=BigInt(16);function dt(t,e){const r=t%e;return r>=nt?r:e+r}function Pt(t,e,r){let n=t;for(;e-- >nt;)n*=n,n%=r;return n}function yp(t,e){if(t===nt)throw new Error("invert: expected non-zero number");if(e<=nt)throw new Error("invert: expected positive modulus, got "+e);let r=dt(t,e),n=e,i=nt,s=Ze;for(;r!==nt;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==Ze)throw new Error("invert: does not exist");return dt(i,e)}function _c(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function wp(t,e){const r=(t.ORDER+Ze)/fp,n=t.pow(e,r);return _c(t,n,e),n}function j8(t,e){const r=(t.ORDER-dp)/pp,n=t.mul(e,an),i=t.pow(n,r),s=t.mul(e,i),o=t.mul(t.mul(s,an),i),a=t.mul(s,t.sub(o,t.ONE));return _c(t,a,e),a}function z8(t){const e=Ur(t),r=bp(t),n=r(e,e.neg(e.ONE)),i=r(e,n),s=r(e,e.neg(n)),o=(t+M8)/gp;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,n);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),w=a.cmov(u,l,g);return _c(a,w,c),w}}function bp(t){if(t<hp)throw new Error("sqrt is not defined for small field");let e=t-Ze,r=0;for(;e%an===nt;)e/=an,r++;let n=an;const i=Ur(t);for(;vp(i,n)===1;)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return wp;let s=i.pow(n,e);const o=(e+Ze)/an;return function(a,c){if(a.is0(c))return c;if(vp(a,c)!==1)throw new Error("Cannot find square root");let u=r,l=a.mul(a.ONE,s),f=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let d=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(d++,p=a.sqr(p),d===u)throw new Error("Cannot find square root");const g=Ze<<BigInt(u-d-1),w=a.pow(l,g);u=d,l=a.sqr(w),f=a.mul(f,l),h=a.mul(h,w)}return h}}function K8(t){return t%fp===hp?wp:t%pp===dp?j8:t%gp===q8?z8(t):bp(t)}const V8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function H8(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=V8.reduce((n,i)=>(n[i]="function",n),e);return ro(t,r),t}function W8(t,e,r){if(r<nt)throw new Error("invalid exponent, negatives unsupported");if(r===nt)return t.ONE;if(r===Ze)return e;let n=t.ONE,i=e;for(;r>nt;)r&Ze&&(n=t.mul(n,i)),i=t.sqr(i),r>>=Ze;return n}function mp(t,e,r=!1){const n=new Array(e.length).fill(r?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(n[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(n[c]=t.mul(o,n[c]),t.mul(o,a)),s),n}function vp(t,e){const r=(t.ORDER-Ze)/an,n=t.pow(e,r),i=t.eql(n,t.ONE),s=t.eql(n,t.ZERO),o=t.eql(n,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Ep(t,e){e!==void 0&&tr(e);const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Ur(t,e,r=!1,n={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(n.sqrt||r)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(r=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),n.sqrt&&(s=n.sqrt);const{nBitLength:c,nByteLength:u}=Ep(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:Ai(c),ZERO:nt,ONE:Ze,allowedLengths:a,create:h=>dt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return nt<=h&&h<t},is0:h=>h===nt,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ze)===Ze,neg:h=>dt(-h,t),eql:(h,d)=>h===d,sqr:h=>dt(h*h,t),add:(h,d)=>dt(h+d,t),sub:(h,d)=>dt(h-d,t),mul:(h,d)=>dt(h*d,t),pow:(h,d)=>W8(f,h,d),div:(h,d)=>dt(h*yp(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>yp(h,t),sqrt:s||(h=>(l||(l=K8(t)),l(f,h))),toBytes:h=>r?vc(h,u):mc(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,r?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=r?to(h):eo(h);if(o&&(p=dt(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>mp(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function xp(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 _p(t){const e=xp(t);return e+Math.ceil(e/2)}function G8(t,e,r=!1){const n=t.length,i=xp(e),s=_p(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?to(t):eo(t),a=dt(o,e-Ze)+Ze;return r?vc(a,i):mc(a,i)}const Nn=BigInt(0),cn=BigInt(1);function no(t,e){const r=e.negate();return t?r:e}function Sc(t,e){const r=mp(t.Fp,e.map(n=>n.Z));return e.map((n,i)=>t.fromAffine(n.toAffine(r[i])))}function Sp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ic(t,e){Sp(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1),i=2**t,s=Ai(t),o=BigInt(t);return{windows:r,windowSize:n,mask:s,maxNumber:i,shiftBy:o}}function Ip(t,e,r){const{windowSize:n,mask:i,maxNumber:s,shiftBy:o}=r;let a=Number(t&i),c=t>>o;a>n&&(a-=s,c+=cn);const u=e*n,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function Z8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,n)=>{if(!(r instanceof e))throw new Error("invalid point at index "+n)})}function Y8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,n)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+n)})}const Dc=new WeakMap,Dp=new WeakMap;function Ac(t){return Dp.get(t)||1}function Ap(t){if(t!==Nn)throw new Error("invalid wNAF")}class X8{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,n=this.ZERO){let i=e;for(;r>Nn;)r&cn&&(n=n.add(i)),i=i.double(),r>>=cn;return n}precomputeWindow(e,r){const{windows:n,windowSize:i}=Ic(r,this.bits),s=[];let o=e,a=o;for(let c=0;c<n;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,r,n){if(!this.Fn.isValid(n))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=Ic(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=Ip(n,a,o);n=c,l?s=s.add(no(h,r[d])):i=i.add(no(f,r[u]))}return Ap(n),{p:i,f:s}}wNAFUnsafe(e,r,n,i=this.ZERO){const s=Ic(e,this.bits);for(let o=0;o<s.windows&&n!==Nn;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Ip(n,o,s);if(n=a,!u){const f=r[c];i=i.add(l?f.negate():f)}}return Ap(n),i}getPrecomputes(e,r,n){let i=Dc.get(r);return i||(i=this.precomputeWindow(r,e),e!==1&&(typeof n=="function"&&(i=n(i)),Dc.set(r,i))),i}cached(e,r,n){const i=Ac(e);return this.wNAF(i,this.getPrecomputes(i,e,n),r)}unsafe(e,r,n,i){const s=Ac(e);return s===1?this._unsafeLadder(e,r,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,n),r,i)}createCache(e,r){Sp(r,this.bits),Dp.set(e,r),Dc.delete(e)}hasCache(e){return Ac(e)!==1}}function J8(t,e,r,n){let i=e,s=t.ZERO,o=t.ZERO;for(;r>Nn||n>Nn;)r&cn&&(s=s.add(i)),n&cn&&(o=o.add(i)),i=i.double(),r>>=cn,n>>=cn;return{p1:s,p2:o}}function Q8(t,e,r,n){Z8(r,t),Y8(n,e);const i=r.length,s=n.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=up(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Ai(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const w=n[g],S=Number(w>>BigInt(d)&u);l[S]=l[S].add(r[g])}let p=o;for(let g=l.length-1,w=o;g>0;g--)w=w.add(l[g]),p=p.add(w);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function $p(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return H8(e),e}else return Ur(t,{isLE:r})}function eS(t,e,r={},n){if(n===void 0&&(n=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>Nn))throw new Error(`CURVE.${a} must be positive bigint`)}const i=$p(e.p,r.Fp,n),s=$p(e.n,r.Fn,n),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Td("HashToScalar-");const $i=BigInt(0),Fn=BigInt(1),io=BigInt(2);function tS(t){return ro(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function rS(t){const e=tS(t),{P:r,type:n,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=n==="x25519";if(!a&&n!=="x448")throw new Error("invalid type");const c=o||nn,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),h=BigInt(a?121665:39081),d=a?io**BigInt(254):io**BigInt(447),p=a?BigInt(8)*io**BigInt(251)-Fn:BigInt(4)*io**BigInt(445)-Fn,g=d+p+Fn,w=P=>dt(P,r),S=D(f);function D(P){return vc(w(P),l)}function E(P){const v=je("u coordinate",P,l);return a&&(v[31]&=127),w(to(v))}function O(P){return to(i(je("scalar",P,l)))}function R(P,v){const m=N(E(v),O(P));if(m===$i)throw new Error("invalid private or public key received");return D(m)}function C(P){return R(P,S)}function U(P,v,m){const y=w(P*(v-m));return v=w(v-y),m=w(m+y),{x_2:v,x_3:m}}function N(P,v){xc("u",P,$i,r),xc("scalar",v,d,g);const m=v,y=P;let b=Fn,_=$i,A=P,x=Fn,I=$i;for(let T=BigInt(u-1);T>=$i;T--){const j=m>>T&Fn;I^=j,{x_2:b,x_3:A}=U(I,b,A),{x_2:_,x_3:x}=U(I,_,x),I=j;const L=b+_,k=w(L*L),z=b-_,H=w(z*z),Z=k-H,V=A+x,Y=A-x,he=w(Y*L),Ve=w(V*z),yt=he+Ve,hr=he-Ve;A=w(yt*yt),x=w(y*w(hr*hr)),b=w(k*H),_=w(Z*(k+w(h*Z)))}({x_2:b,x_3:A}=U(I,b,A)),{x_2:_,x_3:x}=U(I,_,x);const B=s(_);return w(b*B)}const $={secretKey:l,publicKey:l,seed:l},G=(P=c(l))=>(Bt(P,$.seed),P);function W(P){const v=G(P);return{secretKey:v,publicKey:C(v)}}return{keygen:W,getSharedSecret:(P,v)=>R(P,v),getPublicKey:P=>C(P),scalarMult:R,scalarMultBase:C,utils:{randomSecretKey:G,randomPrivateKey:G},GuBytes:S.slice(),lengths:$}}const nS=BigInt(1),Op=BigInt(2),iS=BigInt(3),sS=BigInt(5),oS=BigInt(8),Bp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),aS={p:Bp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:oS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function cS(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=Bp,o=t*t%s*t%s,a=Pt(o,Op,s)*o%s,c=Pt(a,nS,s)*t%s,u=Pt(c,sS,s)*c%s,l=Pt(u,e,s)*u%s,f=Pt(l,r,s)*l%s,h=Pt(f,n,s)*f%s,d=Pt(h,i,s)*h%s,p=Pt(d,i,s)*h%s,g=Pt(p,e,s)*u%s;return{pow_p_5_8:Pt(g,Op,s)*t%s,b2:o}}function uS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const lS=Ur(aS.p,{isLE:!0}),$c=(()=>{const t=lS.ORDER;return rS({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:n}=cS(e);return dt(Pt(r,iS,t)*n,t)},adjustScalarBytes:uS})})(),Tp=(t,e)=>(t+(t>=0?e:-e)/Pp)/e;function hS(t,e,r){const[[n,i],[s,o]]=e,a=Tp(o*t,r),c=Tp(-i*t,r);let u=t-a*n-c*s,l=-a*i-c*o;const f=u<sr,h=l<sr;f&&(u=-u),h&&(l=-l);const d=Ai(Math.ceil(up(r)/2))+kn;if(u<sr||u>=d||l<sr||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Oc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Bc(t,e){const r={};for(let n of Object.keys(e))r[n]=t[n]===void 0?e[n]:t[n];return Js(r.lowS,"lowS"),Js(r.prehash,"prehash"),r.format!==void 0&&Oc(r.format),r}class fS extends Error{constructor(e=""){super(e)}}const ir={Err:fS,_tlv:{encode:(t,e)=>{const{Err:r}=ir;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const n=e.length/2,i=Qs(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Qs(i.length/2|128):"";return Qs(t)+s+i+e},decode(t,e){const{Err:r}=ir;let n=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[n++]!==t)throw new r("tlv.decode: wrong tlv");const i=e[n++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(n,n+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(n+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(n,n+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(n+o)}}},_int:{encode(t){const{Err:e}=ir;if(t<sr)throw new e("integer: negative integers are not allowed");let r=Qs(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=ir;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 eo(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=ir,i=je("signature",t),{v:s,l:o}=n.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=n.decode(2,s),{v:u,l}=n.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=ir,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},sr=BigInt(0),kn=BigInt(1),Pp=BigInt(2),so=BigInt(3),dS=BigInt(4);function Ln(t,e){const{BYTES:r}=t;let n;if(typeof e=="bigint")n=e;else{let i=je("private key",e);try{n=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(n))throw new Error("invalid private key: out of range [1..N-1]");return n}function pS(t,e={}){const r=eS("weierstrass",t,e),{Fp:n,Fn:i}=r;let s=r.CURVE;const{h:o,n:a}=s;ro(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!n.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Cp(n,i);function l(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:y,y:b}=v.toAffine(),_=n.toBytes(y);if(Js(m,"isCompressed"),m){l();const A=!n.isOdd(b);return Ar(Rp(A),_)}else return Ar(Uint8Array.of(4),_,n.toBytes(b))}function h(P){on(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,y=P.length,b=P[0],_=P.subarray(1);if(y===v&&(b===2||b===3)){const A=n.fromBytes(_);if(!n.isValid(A))throw new Error("bad point: is not on curve, wrong x");const x=g(A);let I;try{I=n.sqrt(x)}catch(T){const j=T instanceof Error?": "+T.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}l();const B=n.isOdd(I);return(b&1)===1!==B&&(I=n.neg(I)),{x:A,y:I}}else if(y===m&&b===4){const A=n.BYTES,x=n.fromBytes(_.subarray(0,A)),I=n.fromBytes(_.subarray(A,A*2));if(!w(x,I))throw new Error("bad point: is not on curve");return{x,y:I}}else throw new Error(`bad point: got length ${y}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=n.sqr(P),m=n.mul(v,P);return n.add(n.add(m,n.mul(P,s.a)),s.b)}function w(P,v){const m=n.sqr(v),y=g(P);return n.eql(m,y)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const S=n.mul(n.pow(s.a,so),dS),D=n.mul(n.sqr(s.b),BigInt(27));if(n.is0(n.add(S,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!n.isValid(v)||m&&n.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function O(P){if(!(P instanceof $))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return hS(P,c.basises,i.ORDER)}const C=lp((P,v)=>{const{X:m,Y:y,Z:b}=P;if(n.eql(b,n.ONE))return{x:m,y};const _=P.is0();v==null&&(v=_?n.ONE:n.inv(b));const A=n.mul(m,v),x=n.mul(y,v),I=n.mul(b,v);if(_)return{x:n.ZERO,y:n.ZERO};if(!n.eql(I,n.ONE))throw new Error("invZ was invalid");return{x:A,y:x}}),U=lp(P=>{if(P.is0()){if(e.allowInfinityPoint&&!n.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!n.isValid(v)||!n.isValid(m))throw new Error("bad point: x or y not field elements");if(!w(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,y,b){return m=new $(n.mul(m.X,P),m.Y,m.Z),v=no(y,v),m=no(b,m),v.add(m)}class ${constructor(v,m,y){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y}=v||{};if(!v||!n.isValid(m)||!n.isValid(y))throw new Error("invalid affine point");if(v instanceof $)throw new Error("projective point not allowed");return n.is0(m)&&n.is0(y)?$.ZERO:new $(m,y,n.ONE)}static fromBytes(v){const m=$.fromAffine(p(on(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return $.fromBytes(je("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(so),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(v)}equals(v){O(v);const{X:m,Y:y,Z:b}=this,{X:_,Y:A,Z:x}=v,I=n.eql(n.mul(m,x),n.mul(_,b)),B=n.eql(n.mul(y,x),n.mul(A,b));return I&&B}negate(){return new $(this.X,n.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,y=n.mul(m,so),{X:b,Y:_,Z:A}=this;let x=n.ZERO,I=n.ZERO,B=n.ZERO,T=n.mul(b,b),j=n.mul(_,_),L=n.mul(A,A),k=n.mul(b,_);return k=n.add(k,k),B=n.mul(b,A),B=n.add(B,B),x=n.mul(v,B),I=n.mul(y,L),I=n.add(x,I),x=n.sub(j,I),I=n.add(j,I),I=n.mul(x,I),x=n.mul(k,x),B=n.mul(y,B),L=n.mul(v,L),k=n.sub(T,L),k=n.mul(v,k),k=n.add(k,B),B=n.add(T,T),T=n.add(B,T),T=n.add(T,L),T=n.mul(T,k),I=n.add(I,T),L=n.mul(_,A),L=n.add(L,L),T=n.mul(L,k),x=n.sub(x,T),B=n.mul(L,j),B=n.add(B,B),B=n.add(B,B),new $(x,I,B)}add(v){O(v);const{X:m,Y:y,Z:b}=this,{X:_,Y:A,Z:x}=v;let I=n.ZERO,B=n.ZERO,T=n.ZERO;const j=s.a,L=n.mul(s.b,so);let k=n.mul(m,_),z=n.mul(y,A),H=n.mul(b,x),Z=n.add(m,y),V=n.add(_,A);Z=n.mul(Z,V),V=n.add(k,z),Z=n.sub(Z,V),V=n.add(m,b);let Y=n.add(_,x);return V=n.mul(V,Y),Y=n.add(k,H),V=n.sub(V,Y),Y=n.add(y,b),I=n.add(A,x),Y=n.mul(Y,I),I=n.add(z,H),Y=n.sub(Y,I),T=n.mul(j,V),I=n.mul(L,H),T=n.add(I,T),I=n.sub(z,T),T=n.add(z,T),B=n.mul(I,T),z=n.add(k,k),z=n.add(z,k),H=n.mul(j,H),V=n.mul(L,V),z=n.add(z,H),H=n.sub(k,H),H=n.mul(j,H),V=n.add(V,H),k=n.mul(z,V),B=n.add(B,k),k=n.mul(Y,V),I=n.mul(Z,I),I=n.sub(I,k),k=n.mul(Z,z),T=n.mul(Y,T),T=n.add(T,k),new $(I,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals($.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let y,b;const _=A=>W.cached(this,A,x=>Sc($,x));if(m){const{k1neg:A,k1:x,k2neg:I,k2:B}=R(v),{p:T,f:j}=_(x),{p:L,f:k}=_(B);b=j.add(k),y=N(m.beta,T,L,A,I)}else{const{p:A,f:x}=_(v);y=A,b=x}return Sc($,[y,b])[0]}multiplyUnsafe(v){const{endo:m}=e,y=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===sr||y.is0())return $.ZERO;if(v===kn)return y;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:_,k2neg:A,k2:x}=R(v),{p1:I,p2:B}=J8($,y,_,x);return N(m.beta,I,B,b,A)}else return W.unsafe(y,v)}multiplyAndAddUnsafe(v,m,y){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(y));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===kn?!0:v?v($,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===kn?this:v?v($,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return Js(v,"isCompressed"),this.assertValidity(),d($,this,v)}toHex(v=!0){return Cn(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return Sc($,v)}static msm(v,m){return Q8($,i,v,m)}static fromPrivateKey(v){return $.BASE.multiply(Ln(i,v))}}$.BASE=new $(s.Gx,s.Gy,n.ONE),$.ZERO=new $(n.ZERO,n.ONE,n.ZERO),$.Fp=n,$.Fn=i;const G=i.BITS,W=new X8($,e.endo?Math.ceil(G/2):G);return $.BASE.precompute(8),$}function Rp(t){return Uint8Array.of(t?2:3)}function Cp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function gS(t,e={}){const{Fn:r}=t,n=e.randomBytes||nn,i=Object.assign(Cp(t.Fp,r),{seed:_p(r.ORDER)});function s(h){try{return!!Ln(r,h)}catch{return!1}}function o(h,d){const{publicKey:p,publicKeyUncompressed:g}=i;try{const w=h.length;return d===!0&&w!==p||d===!1&&w!==g?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=n(i.seed)){return G8(on(h,i.seed,"seed"),r.ORDER)}function c(h,d=!0){return t.BASE.multiply(Ln(r,h)).toBytes(d)}function u(h){const d=a(h);return{secretKey:d,publicKey:c(d)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:d,publicKey:p,publicKeyUncompressed:g}=i;if(r.allowedLengths||d===p)return;const w=je("key",h).length;return w===p||w===g}function f(h,d,p=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");const g=Ln(r,h);return t.fromHex(d).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>Ln(r,h),precompute(h=8,d=t.BASE){return d.precompute(h,!1)}},lengths:i})}function yS(t,e,r={}){zs(e),ro(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const n=r.randomBytes||nn,i=r.hmac||((m,...y)=>Ys(e,m,Ar(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=gS(t,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(m){const y=a>>kn;return m>y}function S(m,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return y}function D(m,y){Oc(y);const b=d.signature,_=y==="compact"?b:y==="recovered"?b+1:void 0;return on(m,_,`${y} signature`)}class E{constructor(y,b,_){this.r=S("r",y),this.s=S("s",b),_!=null&&(this.recovery=_),Object.freeze(this)}static fromBytes(y,b=g){D(y,b);let _;if(b==="der"){const{r:B,s:T}=ir.toSig(on(y));return new E(B,T)}b==="recovered"&&(_=y[0],b="compact",y=y.subarray(1));const A=o.BYTES,x=y.subarray(0,A),I=y.subarray(A,A*2);return new E(o.fromBytes(x),o.fromBytes(I),_)}static fromHex(y,b){return this.fromBytes(Ks(y),b)}addRecoveryBit(y){return new E(this.r,this.s,y)}recoverPublicKey(y){const b=s.ORDER,{r:_,s:A,recovery:x}=this;if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");if(a*Pp<b&&x>1)throw new Error("recovery id is ambiguous for h>1 curve");const I=x===2||x===3?_+a:_;if(!s.isValid(I))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(I),T=t.fromBytes(Ar(Rp((x&1)===0),B)),j=o.inv(I),L=R(je("msgHash",y)),k=o.create(-L*j),z=o.create(A*j),H=t.BASE.multiplyUnsafe(k).add(T.multiplyUnsafe(z));if(H.is0())throw new Error("point at infinify");return H.assertValidity(),H}hasHighS(){return w(this.s)}toBytes(y=g){if(Oc(y),y==="der")return Ks(ir.hexFromSig(this));const b=o.toBytes(this.r),_=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ar(Uint8Array.of(this.recovery),b,_)}return Ar(b,_)}toHex(y){return Cn(this.toBytes(y))}assertValidity(){}static fromCompact(y){return E.fromBytes(je("sig",y),"compact")}static fromDER(y){return E.fromBytes(je("sig",y),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Cn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Cn(this.toBytes("compact"))}}const O=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const y=eo(m),b=m.length*8-c;return b>0?y>>BigInt(b):y},R=r.bits2int_modN||function(m){return o.create(O(m))},C=Ai(c);function U(m){return xc("num < 2^"+c,m,sr,C),o.toBytes(m)}function N(m,y){return on(m,void 0,"message"),y?on(e(m),void 0,"prehashed message"):m}function $(m,y,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:_,prehash:A,extraEntropy:x}=Bc(b,p);m=N(m,A);const I=R(m),B=Ln(o,y),T=[U(B),U(I)];if(x!=null&&x!==!1){const z=x===!0?n(d.secretKey):x;T.push(je("extraEntropy",z))}const j=Ar(...T),L=I;function k(z){const H=O(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===sr)return;const he=o.create(Z*o.create(L+Y*B));if(he===sr)return;let Ve=(V.x===Y?0:2)|Number(V.y&kn),yt=he;return _&&w(he)&&(yt=o.neg(he),Ve^=1),new E(Y,yt,Ve)}return{seed:j,k2sig:k}}function G(m,y,b={}){m=je("message",m);const{seed:_,k2sig:A}=$(m,y,b);return L8(e.outputLen,o.BYTES,i)(_,A)}function W(m){let y;const b=typeof m=="string"||js(m),_=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!_)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(_)y=new E(m.r,m.s);else if(b){try{y=E.fromBytes(je("sig",m),"der")}catch(A){if(!(A instanceof ir.Err))throw A}if(!y)try{y=E.fromBytes(je("sig",m),"compact")}catch{return!1}}return y||!1}function P(m,y,b,_={}){const{lowS:A,prehash:x,format:I}=Bc(_,p);if(b=je("publicKey",b),y=N(je("message",y),x),"strict"in _)throw new Error("options.strict was renamed to lowS");const B=I===void 0?W(m):E.fromBytes(je("sig",m),I);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:j,s:L}=B,k=R(y),z=o.inv(L),H=o.create(k*z),Z=o.create(j*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===j}catch{return!1}}function v(m,y,b={}){const{prehash:_}=Bc(b,p);return y=N(y,_),E.fromBytes(m,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function wS(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},r=t.Fp;let n=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=Ur(e.n,{BITS:t.nBitLength,allowedLengths:n,modFromBytes:t.wrapPrivateKey}),s={Fp:r,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function bS(t){const{CURVE:e,curveOpts:r}=wS(t),n={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:n}}function mS(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,Ep(r.Fn.ORDER,r.Fn.BITS))})}function vS(t){const{CURVE:e,curveOpts:r,hash:n,ecdsaOpts:i}=bS(t),s=pS(e,r),o=yS(s,n,i);return mS(t,o)}function Tc(t,e){const r=n=>vS({...t,hash:n});return{...r(e),create:r}}const Up={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Np={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Fp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},ES=Ur(Up.p),xS=Ur(Np.p),_S=Ur(Fp.p),SS=Tc({...Up,Fp:ES,lowS:!1},Hs);Tc({...Np,Fp:xS,lowS:!1},B_),Tc({...Fp,Fp:_S,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},O_);const IS=SS,kp="base10",Ye="base16",it="base64pad",Nr="base64url",Oi="utf8",Lp=0,or=1,Bi=2,DS=0,Mp=1,Ti=12,Pc=32;function AS(){const t=$c.utils.randomPrivateKey(),e=$c.getPublicKey(t);return{privateKey:tt(t,Ye),publicKey:tt(e,Ye)}}function Rc(){const t=nn(Pc);return tt(t,Ye)}function $S(t,e){const r=$c.getSharedSecret(vt(t,Ye),vt(e,Ye)),n=F8(Xs,r,void 0,void 0,Pc);return tt(n,Ye)}function oo(t){const e=Xs(vt(t,Ye));return tt(e,Ye)}function xt(t){const e=Xs(vt(t,Oi));return tt(e,Ye)}function qp(t){return vt(`${t}`,kp)}function un(t){return Number(tt(t,kp))}function jp(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function zp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function OS(t){const e=qp(typeof t.type<"u"?t.type:Lp);if(un(e)===or&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?vt(t.senderPublicKey,Ye):void 0,n=typeof t.iv<"u"?vt(t.iv,Ye):nn(Ti),i=vt(t.symKey,Ye),s=sp(i,n).encrypt(vt(t.message,Oi)),o=Kp({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===Nr?jp(o):o}function BS(t){const e=vt(t.symKey,Ye),{sealed:r,iv:n}=Pi({encoded:t.encoded,encoding:t.encoding}),i=sp(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return tt(i,Oi)}function TS(t,e){const r=qp(Bi),n=nn(Ti),i=vt(t,Oi),s=Kp({type:r,sealed:i,iv:n});return e===Nr?jp(s):s}function PS(t,e){const{sealed:r}=Pi({encoded:t,encoding:e});return tt(r,Oi)}function Kp(t){if(un(t.type)===Bi)return tt(gi([t.type,t.sealed]),it);if(un(t.type)===or){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return tt(gi([t.type,t.senderPublicKey,t.iv,t.sealed]),it)}return tt(gi([t.type,t.iv,t.sealed]),it)}function Pi(t){const e=(t.encoding||it)===Nr?zp(t.encoded):t.encoded,r=vt(e,it),n=r.slice(DS,Mp),i=Mp;if(un(n)===or){const c=i+Pc,u=c+Ti,l=r.slice(i,c),f=r.slice(c,u),h=r.slice(u);return{type:n,sealed:h,iv:f,senderPublicKey:l}}if(un(n)===Bi){const c=r.slice(i),u=nn(Ti);return{type:n,sealed:c,iv:u}}const s=i+Ti,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function RS(t,e){const r=Pi({encoded:t,encoding:e?.encoding});return Vp({type:un(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?tt(r.senderPublicKey,Ye):void 0,receiverPublicKey:e?.receiverPublicKey})}function Vp(t){const e=t?.type||Lp;if(e===or){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 Hp(t){return t.type===or&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Wp(t){return t.type===Bi}function CS(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return gi([new Uint8Array([4]),e,r])}function US(t,e){const[r,n,i]=t.split("."),s=Buffer.from(zp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${r}.${n}`,u=Xs(c),l=CS(e);if(!IS.verify(gi([o,a]),u,l))throw new Error("Invalid signature");return ea(t).payload}const NS="irn";function ao(t){return t?.relay||{protocol:NS}}function Mn(t){const e=hx[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var FS=Object.defineProperty,kS=Object.defineProperties,LS=Object.getOwnPropertyDescriptors,Gp=Object.getOwnPropertySymbols,MS=Object.prototype.hasOwnProperty,qS=Object.prototype.propertyIsEnumerable,Zp=(t,e,r)=>e in t?FS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Cc=(t,e)=>{for(var r in e||(e={}))MS.call(e,r)&&Zp(t,r,e[r]);if(Gp)for(var r of Gp(e))qS.call(e,r)&&Zp(t,r,e[r]);return t},jS=(t,e)=>kS(t,LS(e));function zS(t,e="-"){const r={},n="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(n)){const s=i.replace(n,""),o=t[i];r[s]=o}}),r}function Yp(t){if(!t.includes("wc:")){const u=Ed(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(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,n=t.substring(0,e),i=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:n,topic:KS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:zS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function KS(t){return t.startsWith("//")?t.substring(2):t}function VS(t,e="-"){const r="relay",n={};return Object.keys(t).forEach(i=>{const s=i,o=r+e+s;t[s]&&(n[o]=t[s])}),n}function Xp(t){const e=new URLSearchParams,r=Cc(Cc(jS(Cc({},VS(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(r).sort(([n],[i])=>n.localeCompare(i)).forEach(([n,i])=>{i!==void 0&&e.append(n,String(i))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function co(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var HS=Object.defineProperty,WS=Object.defineProperties,GS=Object.getOwnPropertyDescriptors,Jp=Object.getOwnPropertySymbols,ZS=Object.prototype.hasOwnProperty,YS=Object.prototype.propertyIsEnumerable,Qp=(t,e,r)=>e in t?HS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,XS=(t,e)=>{for(var r in e||(e={}))ZS.call(e,r)&&Qp(t,r,e[r]);if(Jp)for(var r of Jp(e))YS.call(e,r)&&Qp(t,r,e[r]);return t},JS=(t,e)=>WS(t,GS(e));function qn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function QS(t){const e=[];return Object.values(t).forEach(r=>{e.push(...qn(r.accounts))}),e}function e6(t,e){const r=[];return Object.values(t).forEach(n=>{qn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function t6(t,e){const r=[];return Object.values(t).forEach(n=>{qn(n.accounts).includes(e)&&r.push(...n.events)}),r}function eg(t){return t.includes(":")}function r6(t){return eg(t)?t.split(":")[0]:t}function tg(t){var e,r,n;const i={};if(!Ri(t))return i;for(const[s,o]of Object.entries(t)){const a=eg(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=r6(s);i[l]=JS(XS({},i[l]),{chains:rn(a,(e=i[l])==null?void 0:e.chains),methods:rn(c,(r=i[l])==null?void 0:r.methods),events:rn(u,(n=i[l])==null?void 0:n.events)})}return i}function n6(t){const e={};return t?.forEach(r=>{var n;const[i,s]=r.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(r),(n=e[i].chains)==null||n.push(`${i}:${s}`)}),e}function rg(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=n6(e);for(const[n,i]of Object.entries(r))i.methods?i.methods=rn(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}function i6(t,e){var r,n,i,s,o,a;const c=tg(t),u=tg(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const h of f)l[h]={chains:rn((r=c[h])==null?void 0:r.chains,(n=u[h])==null?void 0:n.chains),methods:rn((i=c[h])==null?void 0:i.methods,(s=u[h])==null?void 0:s.methods),events:rn((o=c[h])==null?void 0:o.events,(a=u[h])==null?void 0:a.events)};return l}const s6={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}},o6={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 q(t,e){const{message:r,code:n}=o6[t];return{message:e?`${r} ${e}`:r,code:n}}function fe(t,e){const{message:r,code:n}=s6[t];return{message:e?`${r} ${e}`:r,code:n}}function jn(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ri(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ee(t){return typeof t>"u"}function ge(t,e){return e&&Ee(t)?!0:typeof t=="string"&&!!t.trim().length}function Uc(t,e){return e&&Ee(t)?!0:typeof t=="number"&&!isNaN(t)}function a6(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return en(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=qn(a),f=r[o];(!en(ld(o,f),l)||!en(f.methods,c)||!en(f.events,u))&&(s=!1)}),s):!1}function uo(t){return ge(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function c6(t){if(ge(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&uo(r)}}return!1}function u6(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(ge(t,!1)){if(e(t))return!0;const r=Ed(t);return e(r)}}catch{}return!1}function l6(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function h6(t){return t?.topic}function f6(t,e){let r=null;return ge(t?.publicKey,!1)||(r=q("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function ng(t){let e=!0;return jn(t)?t.length&&(e=t.every(r=>ge(r,!1))):e=!1,e}function d6(t,e,r){let n=null;return jn(e)&&e.length?e.forEach(i=>{n||uo(i)||(n=fe("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):uo(t)||(n=fe("UNSUPPORTED_CHAINS",`${r}, 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"] }`)),n}function p6(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=d6(i,ld(i,s),`${e} ${r}`);o&&(n=o)}),n}function g6(t,e){let r=null;return jn(t)?t.forEach(n=>{r||c6(n)||(r=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function y6(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=g6(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function w6(t,e){let r=null;return ng(t?.methods)?ng(t?.events)||(r=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function ig(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=w6(n,`${e}, namespace`);i&&(r=i)}),r}function b6(t,e,r){let n=null;if(t&&Ri(t)){const i=ig(t,e);i&&(n=i);const s=p6(t,e,r);s&&(n=s)}else n=q("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function Nc(t,e){let r=null;if(t&&Ri(t)){const n=ig(t,e);n&&(r=n);const i=y6(t,e);i&&(r=i)}else r=q("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function sg(t){return ge(t.protocol,!0)}function m6(t,e){let r=!1;return e&&!t?r=!0:t&&jn(t)&&t.length&&t.forEach(n=>{r=sg(n)}),r}function v6(t){return typeof t=="number"}function st(t){return typeof t<"u"&&typeof t!==null}function E6(t){return!(!t||typeof t!="object"||!t.code||!Uc(t.code,!1)||!t.message||!ge(t.message,!1))}function x6(t){return!(Ee(t)||!ge(t.method,!1))}function _6(t){return!(Ee(t)||Ee(t.result)&&Ee(t.error)||!Uc(t.id,!1)||!ge(t.jsonrpc,!1))}function S6(t){return!(Ee(t)||!ge(t.name,!1))}function og(t,e){return!(!uo(e)||!QS(t).includes(e))}function I6(t,e,r){return ge(r,!1)?e6(t,e).includes(r):!1}function D6(t,e,r){return ge(r,!1)?t6(t,e).includes(r):!1}function ag(t,e,r){let n=null;const i=A6(t),s=$6(e),o=Object.keys(i),a=Object.keys(s),c=cg(Object.keys(t)),u=cg(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(n=q("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
23
23
  Required: ${l.toString()}
24
- Received: ${Object.keys(e).toString()}`)),Xr(o,a)||(n=z("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
24
+ Received: ${Object.keys(e).toString()}`)),en(o,a)||(n=q("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
25
25
  Required: ${o.toString()}
26
- Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||n)return;const f=Pn(e[h].accounts);f.includes(h)||(n=z("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
27
- Required: ${h}
28
- Approved: ${f.toString()}`))}),o.forEach(h=>{n||(Xr(i[h].methods,s[h].methods)?Xr(i[h].events,s[h].events)||(n=z("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=z("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function JS(t){const e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function zp(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function XS(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:Pn(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function QS(t,e){return Tc(t,!1)&&t<=e.max&&t>=e.min}function qp(){const t=wi();return new Promise(e=>{switch(t){case lt.browser:e(e6());break;case lt.reactNative:e(t6());break;case lt.node:e(r6());break;default:e(!0)}})}function e6(){return Sn()&&navigator?.onLine}async function t6(){return xr()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function r6(){return!0}function n6(t){switch(wi()){case lt.browser:i6(t);break;case lt.reactNative:s6(t);break}}function i6(t){!xr()&&Sn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function s6(t){xr()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function o6(){var t;return Sn()&&Hr()?((t=Hr())==null?void 0:t.visibilityState)==="visible":!0}const Cc={};class Ri{static get(e){return Cc[e]}static set(e,r){Cc[e]=r}static delete(e){delete Cc[e]}}function a6(t){const e=oi.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function c6({publicKey:t,signature:e,payload:r}){var n;const i=Rc(r.method),s=128|parseInt(((n=r.version)==null?void 0:n.toString())||"4"),o=h6(r.address),a=r.era==="00"?new Uint8Array([0]):Rc(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${l6(r.tip)}`),h=d6(l),f=new Uint8Array([0,...t,o,...e,...a,...u,...h,...i]),p=f6(f.length+1);return new Uint8Array([...p,s,...f])}function u6(t){const e=Rc(t),r=Q3.blake2b(e,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function Rc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function l6(t){return t.startsWith("0x")?t.slice(2):t}function h6(t){const e=oi.decode(t)[0];return e===42?0:e===60?2:1}function f6(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 d6(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 p6(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),r=a6(t.transaction.address),n=c6({publicKey:r,signature:e,payload:t.transaction}),i=Buffer.from(n).toString("hex");return u6(i)}const g6="PARSE_ERROR",y6="INVALID_REQUEST",w6="METHOD_NOT_FOUND",b6="INVALID_PARAMS",jp="INTERNAL_ERROR",Nc="SERVER_ERROR",m6=[-32700,-32600,-32601,-32602,-32603],Ni={[g6]:{code:-32700,message:"Parse error"},[y6]:{code:-32600,message:"Invalid Request"},[w6]:{code:-32601,message:"Method not found"},[b6]:{code:-32602,message:"Invalid params"},[jp]:{code:-32603,message:"Internal error"},[Nc]:{code:-32e3,message:"Server error"}},Vp=Nc;function v6(t){return m6.includes(t)}function Kp(t){return Object.keys(Ni).includes(t)?Ni[t]:Ni[Vp]}function E6(t){const e=Object.values(Ni).find(r=>r.code===t);return e||Ni[Vp]}function x6(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Hp={};/*! *****************************************************************************
26
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||n)return;const h=qn(e[f].accounts);h.includes(f)||(n=q("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${f}
27
+ Required: ${f}
28
+ Approved: ${h.toString()}`))}),o.forEach(f=>{n||(en(i[f].methods,s[f].methods)?en(i[f].events,s[f].events)||(n=q("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${f}`)):n=q("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${f}`))}),n}function A6(t){const e={};return Object.keys(t).forEach(r=>{var n;r.includes(":")?e[r]=t[r]:(n=t[r].chains)==null||n.forEach(i=>{e[i]={methods:t[r].methods,events:t[r].events}})}),e}function cg(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function $6(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:qn(t[r].accounts)?.forEach(i=>{e[i]={accounts:t[r].accounts.filter(s=>s.includes(`${i}:`)),methods:t[r].methods,events:t[r].events}})}),e}function O6(t,e){return Uc(t,!1)&&t<=e.max&&t>=e.min}function ug(){const t=vi();return new Promise(e=>{switch(t){case ft.browser:e(B6());break;case ft.reactNative:e(T6());break;case ft.node:e(P6());break;default:e(!0)}})}function B6(){return Pn()&&navigator?.onLine}async function T6(){return Er()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function P6(){return!0}function R6(t){switch(vi()){case ft.browser:C6(t);break;case ft.reactNative:U6(t);break}}function C6(t){!Er()&&Pn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function U6(t){Er()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function N6(){var t;return Pn()&&Wr()?((t=Wr())==null?void 0:t.visibilityState)==="visible":!0}const Fc={};class Ci{static get(e){return Fc[e]}static set(e,r){Fc[e]=r}static delete(e){delete Fc[e]}}function F6(t){const e=ui.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function k6({publicKey:t,signature:e,payload:r}){var n;const i=kc(r.method),s=128|parseInt(((n=r.version)==null?void 0:n.toString())||"4"),o=q6(r.address),a=r.era==="00"?new Uint8Array([0]):kc(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${M6(r.tip)}`),f=z6(l),h=new Uint8Array([0,...t,o,...e,...a,...u,...f,...i]),d=j6(h.length+1);return new Uint8Array([...d,s,...h])}function L6(t){const e=kc(t),r=_x.blake2b(e,void 0,32);return"0x"+Buffer.from(r).toString("hex")}function kc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function M6(t){return t.startsWith("0x")?t.slice(2):t}function q6(t){const e=ui.decode(t)[0];return e===42?0:e===60?2:1}function j6(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 z6(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 K6(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),r=F6(t.transaction.address),n=k6({publicKey:r,signature:e,payload:t.transaction}),i=Buffer.from(n).toString("hex");return L6(i)}const V6="PARSE_ERROR",H6="INVALID_REQUEST",W6="METHOD_NOT_FOUND",G6="INVALID_PARAMS",lg="INTERNAL_ERROR",Lc="SERVER_ERROR",Z6=[-32700,-32600,-32601,-32602,-32603],Ui={[V6]:{code:-32700,message:"Parse error"},[H6]:{code:-32600,message:"Invalid Request"},[W6]:{code:-32601,message:"Method not found"},[G6]:{code:-32602,message:"Invalid params"},[lg]:{code:-32603,message:"Internal error"},[Lc]:{code:-32e3,message:"Server error"}},hg=Lc;function Y6(t){return Z6.includes(t)}function fg(t){return Object.keys(Ui).includes(t)?Ui[t]:Ui[hg]}function X6(t){const e=Object.values(Ui).find(r=>r.code===t);return e||Ui[hg]}function J6(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var dg={};/*! *****************************************************************************
29
29
  Copyright (c) Microsoft Corporation.
30
30
 
31
31
  Permission to use, copy, modify, and/or distribute this software for any
@@ -38,5 +38,5 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Zx(r)).toStr
38
38
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
39
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
40
  PERFORMANCE OF THIS SOFTWARE.
41
- ***************************************************************************** */var Uc=function(t,e){return Uc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Uc(t,e)};function _6(t,e){Uc(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Fc=function(){return Fc=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Fc.apply(this,arguments)};function S6(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function I6(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function A6(t,e){return function(r,n){e(r,n,t)}}function D6(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function $6(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(h){o(h)}}function c(l){try{u(n.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function O6(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function B6(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function T6(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function kc(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Wp(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function P6(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Wp(arguments[e]));return t}function C6(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Ui(t){return this instanceof Ui?(this.v=t,this):new Ui(t)}function R6(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){n[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(n[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Ui?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function N6(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Ui(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function U6(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof kc=="function"?kc(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function F6(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function k6(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function L6(t){return t&&t.__esModule?t:{default:t}}function M6(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function z6(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var q6=Object.freeze({__proto__:null,__extends:_6,get __assign(){return Fc},__rest:S6,__decorate:I6,__param:A6,__metadata:D6,__awaiter:$6,__generator:O6,__createBinding:B6,__exportStar:T6,__values:kc,__read:Wp,__spread:P6,__spreadArrays:C6,__await:Ui,__asyncGenerator:R6,__asyncDelegator:N6,__asyncValues:U6,__makeTemplateObject:F6,__importStar:k6,__importDefault:L6,__classPrivateFieldGet:M6,__classPrivateFieldSet:z6}),j6=lu(q6),or={},Gp;function V6(){if(Gp)return or;Gp=1,Object.defineProperty(or,"__esModule",{value:!0}),or.isBrowserCryptoAvailable=or.getSubtleCrypto=or.getBrowerCrypto=void 0;function t(){return Rt?.crypto||Rt?.msCrypto||{}}or.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}or.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return or.isBrowserCryptoAvailable=r,or}var ar={},Yp;function K6(){if(Yp)return ar;Yp=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.isBrowser=ar.isNode=ar.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ar.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}ar.isNode=e;function r(){return!t()&&!e()}return ar.isBrowser=r,ar}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=j6;e.__exportStar(V6(),t),e.__exportStar(K6(),t)})(Hp);function zt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ur(t=6){return BigInt(zt(t))}function cr(t,e,r){return{id:r||zt(),jsonrpc:"2.0",method:t,params:e}}function io(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Lc(t,e,r){return{id:t,jsonrpc:"2.0",error:H6(e,r)}}function H6(t,e){return typeof t>"u"?Kp(jp):(typeof t=="string"&&(t=Object.assign(Object.assign({},Kp(Nc)),{message:t})),typeof e<"u"&&(t.data=e),v6(t.code)&&(t=E6(t.code)),t)}class W6{}class G6 extends W6{constructor(){super()}}class Y6 extends G6{constructor(e){super()}}const Z6="^wss?:";function J6(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function X6(t,e){const r=J6(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Zp(t){return X6(t,Z6)}function Q6(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Jp(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Mc(t){return Jp(t)&&"method"in t}function so(t){return Jp(t)&&(qt(t)||xt(t))}function qt(t){return"result"in t}function xt(t){return"error"in t}class eI extends Y6{constructor(e){super(e),this.events=new Ue.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(cr(e.method,e.params||[],e.id||Ur().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{xt(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),so(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 tI=()=>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"),rI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Xp=t=>t.split("?")[0],Qp=10,nI=tI();class iI{constructor(e){if(this.url=e,this.events=new Ue.exports.EventEmitter,this.registering=!1,!Zp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(jr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Zp(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=Hp.isReactNative()?void 0:{rejectUnauthorized:!Q6(e)},s=new nI(e,[],i);rI()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?fn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=Lc(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return x6(e,Xp(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Qp&&this.events.setMaxListeners(Qp)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Xp(this.url)}`));return this.events.emit("register_error",r),r}}const eg="wc",tg=2,oo="core",jt=`${eg}@2:${oo}:`,sI={name:oo,logger:"error"},oI={database:":memory:"},aI="crypto",rg="client_ed25519_seed",cI=M.ONE_DAY,uI="keychain",lI="0.3",hI="messages",fI="0.3",dI=M.SIX_HOURS,pI="publisher",ng="irn",gI="error",ig="wss://relay.walletconnect.org",yI="relayer",pe={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"},wI="_subscription",_t={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},bI=.1,zc="2.21.7",he={link_mode:"link_mode",relay:"relay"},ao={inbound:"inbound",outbound:"outbound"},mI="0.3",vI="WALLETCONNECT_CLIENT_ID",sg="WALLETCONNECT_LINK_MODE_APPS",ht={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},EI="subscription",xI="0.3",_I="pairing",SI="0.3",Fi={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},an={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ct={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},II="history",AI="0.3",DI="expirer",St={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},$I="0.3",OI="verify-api",BI="https://verify.walletconnect.com",og="https://verify.walletconnect.org",ki=og,TI=`${ki}/v3`,PI=[BI,og],CI="echo",RI="https://echo.walletconnect.com",Vt={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"},ur={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"},Fr={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"},Li={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"},cn={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"},Mi={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"},NI=.1,UI="event-client",FI=86400,kI="https://pulse.walletconnect.org/batch";function LI(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(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,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var m=(A-_)*l+1>>>0,v=new Uint8Array(m);_!==A;){for(var x=d[_],B=0,R=m-1;(x!==0||B<y)&&R!==-1;R--,B++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=B,_++}for(var C=m-y;C!==m&&v[C]===0;)C++;for(var b=c.repeat(g);C<m;++C)b+=t.charAt(v[C]);return b}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,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,m=new Uint8Array(A);d[g];){var v=r[d.charCodeAt(g)];if(v===255)return;for(var x=0,B=A-1;(v!==0||x<_)&&B!==-1;B--,x++)v+=a*m[B]>>>0,m[B]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&m[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),b=y;R!==A;)C[b++]=m[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var MI=LI,zI=MI;const ag=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")},qI=t=>new TextEncoder().encode(t),jI=t=>new TextDecoder().decode(t);class VI{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class KI{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 cg(this,e)}}class HI{constructor(e){this.decoders=e}or(e){return cg(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const cg=(t,e)=>new HI({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class WI{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new VI(e,r,n),this.decoder=new KI(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:r,decode:n})=>new WI(t,e,r,n),zi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=zI(r,e);return co({prefix:t,name:e,encode:n,decode:s=>ag(i(s))})},GI=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},YI=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Te=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>co({prefix:e,name:t,encode(i){return YI(i,n,r)},decode(i){return GI(i,n,r,t)}}),ZI=co({prefix:"\0",name:"identity",encode:t=>jI(t),decode:t=>qI(t)});var JI=Object.freeze({__proto__:null,identity:ZI});const XI=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var QI=Object.freeze({__proto__:null,base2:XI});const e4=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var t4=Object.freeze({__proto__:null,base8:e4});const r4=zi({prefix:"9",name:"base10",alphabet:"0123456789"});var n4=Object.freeze({__proto__:null,base10:r4});const i4=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),s4=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var o4=Object.freeze({__proto__:null,base16:i4,base16upper:s4});const a4=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),c4=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),u4=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),l4=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),h4=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),f4=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),d4=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),p4=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),g4=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var y4=Object.freeze({__proto__:null,base32:a4,base32upper:c4,base32pad:u4,base32padupper:l4,base32hex:h4,base32hexupper:f4,base32hexpad:d4,base32hexpadupper:p4,base32z:g4});const w4=zi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),b4=zi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var m4=Object.freeze({__proto__:null,base36:w4,base36upper:b4});const v4=zi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),E4=zi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var x4=Object.freeze({__proto__:null,base58btc:v4,base58flickr:E4});const _4=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),S4=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),I4=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),A4=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var D4=Object.freeze({__proto__:null,base64:_4,base64pad:S4,base64url:I4,base64urlpad:A4});const ug=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$4=ug.reduce((t,e,r)=>(t[r]=e,t),[]),O4=ug.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function B4(t){return t.reduce((e,r)=>(e+=$4[r],e),"")}function T4(t){const e=[];for(const r of t){const n=O4[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const P4=co({prefix:"\u{1F680}",name:"base256emoji",encode:B4,decode:T4});var C4=Object.freeze({__proto__:null,base256emoji:P4}),R4=hg,lg=128,N4=127,U4=~N4,F4=Math.pow(2,31);function hg(t,e,r){e=e||[],r=r||0;for(var n=r;t>=F4;)e[r++]=t&255|lg,t/=128;for(;t&U4;)e[r++]=t&255|lg,t>>>=7;return e[r]=t|0,hg.bytes=r-n+1,e}var k4=qc,L4=128,fg=127;function qc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw qc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&fg)<<i:(o&fg)*Math.pow(2,i),i+=7}while(o>=L4);return qc.bytes=s-n,r}var M4=Math.pow(2,7),z4=Math.pow(2,14),q4=Math.pow(2,21),j4=Math.pow(2,28),V4=Math.pow(2,35),K4=Math.pow(2,42),H4=Math.pow(2,49),W4=Math.pow(2,56),G4=Math.pow(2,63),Y4=function(t){return t<M4?1:t<z4?2:t<q4?3:t<j4?4:t<V4?5:t<K4?6:t<H4?7:t<W4?8:t<G4?9:10},Z4={encode:R4,decode:k4,encodingLength:Y4},dg=Z4;const pg=(t,e,r=0)=>(dg.encode(t,e,r),e),gg=t=>dg.encodingLength(t),jc=(t,e)=>{const r=e.byteLength,n=gg(t),i=n+gg(r),s=new Uint8Array(i+r);return pg(t,s,0),pg(r,s,n),s.set(e,i),new J4(t,r,e,s)};class J4{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const yg=({name:t,code:e,encode:r})=>new X4(t,e,r);class X4{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?jc(this.code,r):r.then(n=>jc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const wg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Q4=yg({name:"sha2-256",code:18,encode:wg("SHA-256")}),eA=yg({name:"sha2-512",code:19,encode:wg("SHA-512")});var tA=Object.freeze({__proto__:null,sha256:Q4,sha512:eA});const bg=0,rA="identity",mg=ag;var nA=Object.freeze({__proto__:null,identity:{code:bg,name:rA,encode:mg,digest:t=>jc(bg,mg(t))}});new TextEncoder,new TextDecoder;const vg={...JI,...QI,...t4,...n4,...o4,...y4,...m4,...x4,...D4,...C4};({...tA,...nA});function Eg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function iA(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Eg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function xg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const _g=xg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Vc=xg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=iA(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),sA={utf8:_g,"utf-8":_g,hex:vg.base16,latin1:Vc,ascii:Vc,binary:Vc,...vg};function oA(t,e="utf8"){const r=sA[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Eg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var aA=Object.defineProperty,cA=(t,e,r)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kt=(t,e,r)=>cA(t,typeof e!="symbol"?e+"":e,r);class uA{constructor(e,r){this.core=e,this.logger=r,Kt(this,"keychain",new Map),Kt(this,"name",uI),Kt(this,"version",lI),Kt(this,"initialized",!1),Kt(this,"storagePrefix",jt),Kt(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Kt(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Kt(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),Kt(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=z("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),Kt(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=Ve(r,this.name)}get context(){return Ze(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ja(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Xa(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lA=Object.defineProperty,hA=(t,e,r)=>e in t?lA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pe=(t,e,r)=>hA(t,typeof e!="symbol"?e+"":e,r);class fA{constructor(e,r,n){this.core=e,this.logger=r,Pe(this,"name",aI),Pe(this,"keychain"),Pe(this,"randomSessionIdentifier",Bc()),Pe(this,"initialized",!1),Pe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Pe(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Pe(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=ql(i);return zl(s.publicKey)}),Pe(this,"generateKeyPair",()=>{this.isInitialized();const i=nS();return this.setPrivateKey(i.publicKey,i.privateKey)}),Pe(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=ql(s),a=this.randomSessionIdentifier;return await im(a,i,cI,o)}),Pe(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=iS(a,s);return this.setSymKey(c,o)}),Pe(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||eo(i);return await this.keychain.set(o,i),o}),Pe(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Pe(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Pe(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Ap(o),c=jr(s);if($p(a))return aS(c,o?.encoding);if(Dp(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(f,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return sS({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Pe(this,"decode",async(i,s,o)=>{this.isInitialized();const a=uS(s,o);if($p(a)){const c=cS(s,o?.encoding);return fn(c)}if(Dp(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=oS({symKey:c,encoded:s,encoding:o?.encoding});return fn(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Pe(this,"getPayloadType",(i,s=nt)=>{const o=Pi({encoded:i,encoding:s});return on(o.type)}),Pe(this,"getPayloadSenderPublicKey",(i,s=nt)=>{const o=Pi({encoded:i,encoding:s});return o.senderPublicKey?Qe(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=Ve(r,this.name),this.keychain=n||new uA(this.core,this.logger)}get context(){return Ze(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(rg)}catch{e=Bc(),await this.keychain.set(rg,e)}return oA(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var dA=Object.defineProperty,pA=Object.defineProperties,gA=Object.getOwnPropertyDescriptors,Sg=Object.getOwnPropertySymbols,yA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,Kc=(t,e,r)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,bA=(t,e)=>{for(var r in e||(e={}))yA.call(e,r)&&Kc(t,r,e[r]);if(Sg)for(var r of Sg(e))wA.call(e,r)&&Kc(t,r,e[r]);return t},mA=(t,e)=>pA(t,gA(e)),ft=(t,e,r)=>Kc(t,typeof e!="symbol"?e+"":e,r);class vA extends n1{constructor(e,r){super(e,r),this.logger=e,this.core=r,ft(this,"messages",new Map),ft(this,"messagesWithoutClientAck",new Map),ft(this,"name",hI),ft(this,"version",fI),ft(this,"initialized",!1),ft(this,"storagePrefix",jt),ft(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),ft(this,"set",async(n,i,s)=>{this.isInitialized();const o=Et(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===ao.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,mA(bA({},c),{[o]:i}))}return await this.persist(),o}),ft(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),ft(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),ft(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=Et(i);return typeof s[o]<"u"}),ft(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=Et(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),ft(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=Ve(e,this.name),this.core=r}get context(){return Ze(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,Ja(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ja(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Xa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Xa(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EA=Object.defineProperty,xA=Object.defineProperties,_A=Object.getOwnPropertyDescriptors,Ig=Object.getOwnPropertySymbols,SA=Object.prototype.hasOwnProperty,IA=Object.prototype.propertyIsEnumerable,Hc=(t,e,r)=>e in t?EA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Rn=(t,e)=>{for(var r in e||(e={}))SA.call(e,r)&&Hc(t,r,e[r]);if(Ig)for(var r of Ig(e))IA.call(e,r)&&Hc(t,r,e[r]);return t},Ag=(t,e)=>xA(t,_A(e)),It=(t,e,r)=>Hc(t,typeof e!="symbol"?e+"":e,r);class AA extends i1{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,It(this,"events",new Ue.exports.EventEmitter),It(this,"name",pI),It(this,"queue",new Map),It(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),It(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),It(this,"needsTransportRestart",!1),It(this,"publish",async(n,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const h=s?.ttl||dI,f=s?.prompt||!1,p=s?.tag||0,d=s?.id||Ur().toString(),g=Tn(to().protocol),y={id:d,method:s?.publishMethod||g.publish,params:Rn({topic:n,message:i,ttl:h,prompt:f,tag:p,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},_=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{Ee((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),Ee((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const A=new Promise(async m=>{const v=({id:B})=>{var R;((R=y.id)==null?void 0:R.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(pe.publish,v),m())};this.relayer.events.on(pe.publish,v);const x=Lt(new Promise((B,R)=>{this.rpcPublish(y,s).then(B).catch(C=>{this.logger.warn(C,C?.message),R(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await x,this.events.removeListener(pe.publish,v)}catch(B){this.queue.set(d,{request:y,opts:s,attempt:1}),this.logger.warn(B,B?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:n,message:i,opts:s}}),await Lt(A,this.publishTimeout,_)}catch(A){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(A),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw A}finally{this.queue.delete(d)}}),It(this,"publishCustom",async n=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:u,opts:l={}}=n,{attestation:h,tvf:f,publishMethod:p,prompt:d,tag:g,ttl:y=M.FIVE_MINUTES}=l,_=l.id||Ur().toString(),A=Tn(to().protocol),m=p||A.publish,v={id:_,method:m,params:Rn(Ag(Rn({},u),{ttl:y,prompt:d,tag:g,attestation:h}),f)},x=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{Ee((i=v.params)==null?void 0:i.prompt)&&((s=v.params)==null||delete s.prompt),Ee((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const B=new Promise(async R=>{const C=({id:T})=>{var I;((I=v.id)==null?void 0:I.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(pe.publish,C),R())};this.relayer.events.on(pe.publish,C);const b=Lt(new Promise((T,I)=>{this.rpcPublish(v,l).then(T).catch($=>{this.logger.warn($,$?.message),I($)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${m} id:${_} tag:${g}`);try{await b,this.events.removeListener(pe.publish,C)}catch(T){this.queue.set(_,{request:v,opts:l,attempt:1}),this.logger.warn(T,T?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:u,opts:l}}),await Lt(B,this.publishTimeout,x)}catch(B){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(B),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw B}finally{this.queue.delete(_)}}),It(this,"on",(n,i)=>{this.events.on(n,i)}),It(this,"once",(n,i)=>{this.events.once(n,i)}),It(this,"off",(n,i)=>{this.events.off(n,i)}),It(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=Ve(r,this.name),this.registerEventListeners()}get context(){return Ze(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(pe.publish,Rn(Rn({},e),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var n;const i=e.attempt+1;this.queue.set(r,Ag(Rn({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(zr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pe.connection_stalled);return}this.checkQueue()}),this.relayer.on(pe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var DA=Object.defineProperty,$A=(t,e,r)=>e in t?DA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Nn=(t,e,r)=>$A(t,typeof e!="symbol"?e+"":e,r);class OA{constructor(){Nn(this,"map",new Map),Nn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Nn(this,"get",e=>this.map.get(e)||[]),Nn(this,"exists",(e,r)=>this.get(e).includes(r)),Nn(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Nn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var BA=Object.defineProperty,TA=Object.defineProperties,PA=Object.getOwnPropertyDescriptors,Dg=Object.getOwnPropertySymbols,CA=Object.prototype.hasOwnProperty,RA=Object.prototype.propertyIsEnumerable,Wc=(t,e,r)=>e in t?BA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qi=(t,e)=>{for(var r in e||(e={}))CA.call(e,r)&&Wc(t,r,e[r]);if(Dg)for(var r of Dg(e))RA.call(e,r)&&Wc(t,r,e[r]);return t},Gc=(t,e)=>TA(t,PA(e)),ce=(t,e,r)=>Wc(t,typeof e!="symbol"?e+"":e,r);class NA extends a1{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new OA),ce(this,"events",new Ue.exports.EventEmitter),ce(this,"name",EI),ce(this,"version",xI),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",jt),ce(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(n,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=to(i),a={topic:n,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ce(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ce(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ce(this,"on",(n,i)=>{this.events.on(n,i)}),ce(this,"once",(n,i)=>{this.events.once(n,i)}),ce(this,"off",(n,i)=>{this.events.off(n,i)}),ce(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(zr.pulse,async()=>{await this.checkPending()}),this.events.on(ht.created,async n=>{const i=ht.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(ht.deleted,async n=>{const i=ht.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=Ve(r,this.name),this.clientId=""}get context(){return Ze(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=to(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i,s;const o=await this.getSubscriptionId(e);if((i=n?.internal)!=null&&i.skipSubscribe)return o;(!n||n?.transportType===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:Tn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async h=>{const f=p=>{p.topic===e&&(this.events.removeListener(ht.created,f),h(p.id))};this.events.on(ht.created,f);try{const p=await Lt(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(ht.created,f),h(p)}catch{}}),l=await Lt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pe.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Tn(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Lt(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Tn(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await Lt(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Tn(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Gc(qi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,qi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,qi({},r)),this.topicMap.set(r.topic,e),this.events.emit(ht.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(ht.deleted,Gc(qi({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(ht.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(ht.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Gc(qi({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Ix(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=z("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 Et(e+await this.getClientId())}}var UA=Object.defineProperty,$g=Object.getOwnPropertySymbols,FA=Object.prototype.hasOwnProperty,kA=Object.prototype.propertyIsEnumerable,Yc=(t,e,r)=>e in t?UA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Og=(t,e)=>{for(var r in e||(e={}))FA.call(e,r)&&Yc(t,r,e[r]);if($g)for(var r of $g(e))kA.call(e,r)&&Yc(t,r,e[r]);return t},re=(t,e,r)=>Yc(t,typeof e!="symbol"?e+"":e,r);class LA extends s1{constructor(e){super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new Ue.exports.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",yI),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),re(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Ur().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),re(this,"resetPingTimeout",()=>{Fs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),re(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(pe.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(pe.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),re(this,"registerProviderListeners",()=>{this.provider.on(_t.payload,this.onPayloadHandler),this.provider.on(_t.connect,this.onConnectHandler),this.provider.on(_t.disconnect,this.onDisconnectHandler),this.provider.on(_t.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ve(e.logger,this.name):Gt($o({level:e.logger||gI})),this.messages=new vA(this.logger,e.core),this.subscriber=new NA(this,this.logger),this.publisher=new AA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ig,ux()?this.packageName=rd():lx()&&(this.bundleId=rd()),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 Ze(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:he.relay},ao.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(ht.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(ht.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Og({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Lt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).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 qp())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 r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=me(M.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(pe.message,e),await this.recordMessageEvent(e,ao.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(_t.disconnect,s),await Lt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(_t.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(_t.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(_t.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,M.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(Fs())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.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 eI(new iI(gx({sdkVersion:zc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Mc(e)){if(!e.method.endsWith(wI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Og({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else so(e)&&this.events.emit(pe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ao.inbound),this.events.emit(pe.message,e))}async acknowledgePayload(e){const r=io(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(_t.payload,this.onPayloadHandler),this.provider.off(_t.connect,this.onConnectHandler),this.provider.off(_t.disconnect,this.onDisconnectHandler),this.provider.off(_t.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await qp();n6(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(zr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&o6())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(pe.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},M.toMiliseconds(bI)))))}isInitialized(){if(!this.initialized){const{message:e}=z("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 MA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Bg(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Tg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const zA="[object RegExp]",qA="[object String]",jA="[object Number]",VA="[object Boolean]",Pg="[object Arguments]",KA="[object Symbol]",HA="[object Date]",WA="[object Map]",GA="[object Set]",YA="[object Array]",ZA="[object Function]",JA="[object ArrayBuffer]",Zc="[object Object]",XA="[object Error]",QA="[object DataView]",eD="[object Uint8Array]",tD="[object Uint8ClampedArray]",rD="[object Uint16Array]",nD="[object Uint32Array]",iD="[object BigUint64Array]",sD="[object Int8Array]",oD="[object Int16Array]",aD="[object Int32Array]",cD="[object BigInt64Array]",uD="[object Float32Array]",lD="[object Float64Array]";function hD(){}function Cg(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 fD(t,e,r){return ji(t,e,void 0,void 0,void 0,void 0,r)}function ji(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Vi(t,e,s,o)}return Vi(t,e,s,o)}function Vi(t,e,r,n){if(Object.is(t,e))return!0;let i=Tg(t),s=Tg(e);if(i===Pg&&(i=Zc),s===Pg&&(s=Zc),i!==s)return!1;switch(i){case qA:return t.toString()===e.toString();case jA:{const c=t.valueOf(),u=e.valueOf();return MA(c,u)}case VA:case HA:case KA:return Object.is(t.valueOf(),e.valueOf());case zA:return t.source===e.source&&t.flags===e.flags;case ZA:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case WA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ji(u,e.get(c),c,t,e,r,n))return!1;return!0}case GA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>ji(h,p,void 0,t,e,r,n));if(f===-1)return!1;u.splice(f,1)}return!0}case YA:case eD:case tD:case rD:case nD:case iD:case sD:case oD:case aD:case cD:case uD:case lD:{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(!ji(t[c],e[c],c,t,e,r,n))return!1;return!0}case JA:return t.byteLength!==e.byteLength?!1:Vi(new Uint8Array(t),new Uint8Array(e),r,n);case QA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Vi(new Uint8Array(t),new Uint8Array(e),r,n);case XA:return t.name===e.name&&t.message===e.message;case Zc:{if(!(Vi(t.constructor,e.constructor,r,n)||Cg(t)&&Cg(e)))return!1;const c=[...Object.keys(t),...Bg(t)],u=[...Object.keys(e),...Bg(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!ji(f,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function dD(t,e){return fD(t,e,hD)}var pD=Object.defineProperty,Rg=Object.getOwnPropertySymbols,gD=Object.prototype.hasOwnProperty,yD=Object.prototype.propertyIsEnumerable,Jc=(t,e,r)=>e in t?pD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ng=(t,e)=>{for(var r in e||(e={}))gD.call(e,r)&&Jc(t,r,e[r]);if(Rg)for(var r of Rg(e))yD.call(e,r)&&Jc(t,r,e[r]);return t},st=(t,e,r)=>Jc(t,typeof e!="symbol"?e+"":e,r);class un extends o1{constructor(e,r,n,i=jt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,st(this,"map",new Map),st(this,"version",mI),st(this,"cached",[]),st(this,"initialized",!1),st(this,"getKey"),st(this,"storagePrefix",jt),st(this,"recentlyDeleted",[]),st(this,"recentlyDeletedLimit",200),st(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ee(o)?this.map.set(this.getKey(o),o):RS(o)?this.map.set(o.id,o):NS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),st(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())}),st(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),st(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>dD(a[c],o[c]))):this.values)),st(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=Ng(Ng({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),st(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=Ve(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Ze(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var wD=Object.defineProperty,bD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,J=(t,e,r)=>bD(t,typeof e!="symbol"?e+"":e,r);class mD{constructor(e,r){this.core=e,this.logger=r,J(this,"name",_I),J(this,"version",SI),J(this,"events",new Ue.exports),J(this,"pairings"),J(this,"initialized",!1),J(this,"storagePrefix",jt),J(this,"ignoredPayloadTypes",[sr]),J(this,"registeredMethods",[]),J(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),J(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),J(this,"create",async n=>{this.isInitialized();const i=Bc(),s=await this.core.crypto.setSymKey(i),o=me(M.FIVE_MINUTES),a={protocol:ng},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=Bp({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(an.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}}),J(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Vt.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Op(n.uri);i.props.properties.topic=s,i.addTrace(Vt.pairing_uri_validation_success),i.addTrace(Vt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Vt.existing_pairing),l.active)throw i.setError(ur.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Vt.pairing_not_expired)}const h=c||me(M.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),i.addTrace(Vt.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(an.create,f),i.addTrace(Vt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Vt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(ur.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(ur.subscribe_pairing_topic_failure),p}return i.addTrace(Vt.subscribe_pairing_topic_success),f}),J(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(M.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),J(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Qr();this.events.once(ne("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),J(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),J(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),J(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),J(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),J(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return Bp({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),J(this,"sendRequest",async(n,i,s)=>{const o=cr(i,s),a=await this.core.crypto.encode(n,o),c=Fi[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),J(this,"sendResult",async(n,i,s)=>{const o=io(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Fi[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"sendError",async(n,i,s)=>{const o=Lc(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Fi[c]?Fi[c].res:Fi.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),J(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>_r(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),J(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),J(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),J(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(an.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),J(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{qt(i)?this.events.emit(ne("pairing_ping",s),{}):xt(i)&&this.events.emit(ne("pairing_ping",s),{error:i.error})},500)}),J(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(an.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),J(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),J(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",n))}),J(this,"isValidPair",(n,i)=>{var s;if(!it(n)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(ur.malformed_pairing_uri),new Error(a)}if(!CS(n.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(ur.malformed_pairing_uri),new Error(a)}const o=Op(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(ur.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(ur.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(ur.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),J(this,"isValidPing",async n=>{if(!it(n)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),J(this,"isValidDisconnect",async n=>{if(!it(n)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),J(this,"isValidPairingTopic",async n=>{if(!ye(n,!1)){const{message:i}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(_r(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=z("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=Ve(r,this.name),this.pairings=new un(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Ze(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pe.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Mc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):so(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(St.expired,async e=>{const{topic:r}=od(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(an.expire,{topic:r}))})}}var vD=Object.defineProperty,ED=(t,e,r)=>e in t?vD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ce=(t,e,r)=>ED(t,typeof e!="symbol"?e+"":e,r);class xD extends r1{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ce(this,"records",new Map),Ce(this,"events",new Ue.exports.EventEmitter),Ce(this,"name",II),Ce(this,"version",AI),Ce(this,"cached",[]),Ce(this,"initialized",!1),Ce(this,"storagePrefix",jt),Ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ce(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:me(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ct.created,o)}),Ce(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=xt(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Ct.updated,i))}),Ce(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Ce(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Ct.deleted,s)}}),this.persist()}),Ce(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Ce(this,"on",(n,i)=>{this.events.on(n,i)}),Ce(this,"once",(n,i)=>{this.events.once(n,i)}),Ce(this,"off",(n,i)=>{this.events.off(n,i)}),Ce(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ve(r,this.name)}get context(){return Ze(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:cr(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ct.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Ct.created,e=>{const r=Ct.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ct.updated,e=>{const r=Ct.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ct.deleted,e=>{const r=Ct.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(zr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{M.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ct.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _D=Object.defineProperty,SD=(t,e,r)=>e in t?_D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qe=(t,e,r)=>SD(t,typeof e!="symbol"?e+"":e,r);class ID extends c1{constructor(e,r){super(e,r),this.core=e,this.logger=r,qe(this,"expirations",new Map),qe(this,"events",new Ue.exports.EventEmitter),qe(this,"name",DI),qe(this,"version",$I),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"storagePrefix",jt),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),qe(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),qe(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(St.created,{target:s,expiration:o})}),qe(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),qe(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(St.deleted,{target:i,expiration:s})}}),qe(this,"on",(n,i)=>{this.events.on(n,i)}),qe(this,"once",(n,i)=>{this.events.once(n,i)}),qe(this,"off",(n,i)=>{this.events.off(n,i)}),qe(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=Ve(r,this.name)}get context(){return Ze(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 yx(e);if(typeof e=="number")return wx(e);const{message:r}=z("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(St.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;M.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(St.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(zr.pulse,()=>this.checkExpirations()),this.events.on(St.created,e=>{const r=St.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(St.expired,e=>{const r=St.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(St.deleted,e=>{const r=St.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AD=Object.defineProperty,DD=(t,e,r)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,we=(t,e,r)=>DD(t,typeof e!="symbol"?e+"":e,r);class $D extends u1{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,we(this,"name",OI),we(this,"abortController"),we(this,"isDevEnv"),we(this,"verifyUrlV3",TI),we(this,"storagePrefix",jt),we(this,"version",tg),we(this,"publicKey"),we(this,"fetchPromise"),we(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),we(this,"register",async i=>{if(!Sn()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=Hr(),l=this.startAbortTimer(M.ONE_SECOND*5),h=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=_=>{if(_.data&&typeof _.data=="string")try{const A=JSON.parse(_.data);if(A.type==="verify_attestation"){if(Yo(A.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",y),f(A.attestation===null?"":A.attestation)}}catch(A){this.logger.warn(A)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),we(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Yo(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);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(i?.verifyUrl);return this.fetchAttestation(o,c)}),we(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),we(this,"getVerifyUrl",i=>{let s=i||ki;return PI.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${ki}`),s=ki),s}),we(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),we(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),we(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),we(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),we(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),we(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),we(this,"validateAttestation",(i,s)=>{const o=hS(i,s.publicKey),a={hasExpired:M.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=Ve(r,this.name),this.abortController=new AbortController,this.isDevEnv=Qa(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Ze(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var OD=Object.defineProperty,BD=(t,e,r)=>e in t?OD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ug=(t,e,r)=>BD(t,typeof e!="symbol"?e+"":e,r);class TD extends l1{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Ug(this,"context",CI),Ug(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${RI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=Ve(r,this.context)}}var PD=Object.defineProperty,Fg=Object.getOwnPropertySymbols,CD=Object.prototype.hasOwnProperty,RD=Object.prototype.propertyIsEnumerable,Xc=(t,e,r)=>e in t?PD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ki=(t,e)=>{for(var r in e||(e={}))CD.call(e,r)&&Xc(t,r,e[r]);if(Fg)for(var r of Fg(e))RD.call(e,r)&&Xc(t,r,e[r]);return t},Ie=(t,e,r)=>Xc(t,typeof e!="symbol"?e+"":e,r);class ND extends h1{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Ie(this,"context",UI),Ie(this,"storagePrefix",jt),Ie(this,"storageVersion",NI),Ie(this,"events",new Map),Ie(this,"shouldPersist",!1),Ie(this,"init",async()=>{if(!Qa())try{const i={eventId:cd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:id(this.core.relayer.protocol,this.core.relayer.version,zc)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Ie(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=cd(),l=this.core.projectId||"",h=Date.now(),f=Ki({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),Ie(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ki(Ki({},a),this.setMethods(a.eventId))}),Ie(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Ie(this,"setEventListeners",()=>{this.core.heartbeat.on(zr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>FI&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Ie(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Ie(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Ie(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Ie(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ie(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ki(Ki({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Ie(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Ie(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${kI}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${zc}${s}`,{method:"POST",body:JSON.stringify(i)})}),Ie(this,"getAppDomain",()=>nd().url),this.logger=Ve(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var UD=Object.defineProperty,kg=Object.getOwnPropertySymbols,FD=Object.prototype.hasOwnProperty,kD=Object.prototype.propertyIsEnumerable,Qc=(t,e,r)=>e in t?UD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lg=(t,e)=>{for(var r in e||(e={}))FD.call(e,r)&&Qc(t,r,e[r]);if(kg)for(var r of kg(e))kD.call(e,r)&&Qc(t,r,e[r]);return t},le=(t,e,r)=>Qc(t,typeof e!="symbol"?e+"":e,r);class eu extends Xy{constructor(e){var r;super(e),le(this,"protocol",eg),le(this,"version",tg),le(this,"name",oo),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new Ue.exports.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||ig,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=$o({level:typeof e?.logger=="string"&&e.logger?e.logger:sI.logger,name:oo}),{logger:s,chunkLoggerController:o}=Yy({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ve(s,this.name),this.heartbeat=new Eo,this.crypto=new fA(this,this.logger,e?.keychain),this.history=new xD(this,this.logger),this.expirer=new ID(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Ey(Lg(Lg({},oI),e?.storageOptions)),this.relayer=new LA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new mD(this,this.logger),this.verify=new $D(this,this.logger,this.storage),this.echoClient=new TD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new ND(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new eu(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(vI,n),r}get context(){return Ze(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(sg,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(sg)||[],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 r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const tu=eu,Mg="wc",zg=2,qg="client",ru=`${Mg}@${zg}:${qg}:`,nu={name:qg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},jg="WALLETCONNECT_DEEPLINK_CHOICE",LD="proposal",Vg="Proposal expired",MD="session",Un=M.SEVEN_DAYS,zD="engine",Re={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},iu={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Ht={idle:"IDLE",active:"ACTIVE"},qD={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:""}},jD="request",VD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],KD="wc",HD="auth",WD="authKeys",GD="pairingTopics",YD="requests",uo=`${KD}@${1.5}:${HD}:`,lo=`${uo}:PUB_KEY`;var ZD=Object.defineProperty,JD=Object.defineProperties,XD=Object.getOwnPropertyDescriptors,Kg=Object.getOwnPropertySymbols,QD=Object.prototype.hasOwnProperty,e5=Object.prototype.propertyIsEnumerable,su=(t,e,r)=>e in t?ZD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))QD.call(e,r)&&su(t,r,e[r]);if(Kg)for(var r of Kg(e))e5.call(e,r)&&su(t,r,e[r]);return t},je=(t,e)=>JD(t,XD(e)),k=(t,e,r)=>su(t,typeof e!="symbol"?e+"":e,r);class t5 extends g1{constructor(e){super(e),k(this,"name",zD),k(this,"events",new Ue.exports),k(this,"initialized",!1),k(this,"requestQueue",{state:Ht.idle,queue:[]}),k(this,"sessionRequestQueue",{state:Ht.idle,queue:[]}),k(this,"emittedSessionRequests",new Ax({limit:500})),k(this,"requestQueueDelay",M.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Re)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=je(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=$S(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,f=!1;try{if(l){const B=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=B.active}}catch(B){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),B}if(!l||!f){const{topic:B,uri:R}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=B,h=R}if(!l){const{message:B}=z("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(B)}const p=await this.client.core.crypto.generateKeyPair(),d=Re.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=me(d),y=je(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:ng}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:zt()}),_=ne("session_connect",y.id),{reject:A,resolve:m,done:v}=Qr(d,Vg),x=({id:B})=>{B===y.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(y.id),this.events.emit(_,{error:{message:Vg,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(_,({error:B,session:R})=>{this.client.events.off("proposal_expire",x),B?A(B):R&&m(R)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:h,approval:v}}),k(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),k(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[Fr.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(b){throw o.setError(Li.no_internet_connection),b}try{await this.isValidProposalId(r?.id)}catch(b){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Li.proposal_not_found),b}try{await this.isValidApprove(r)}catch(b){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Li.session_approve_namespace_validation_failure),b}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:g,requiredNamespaces:y,optionalNamespaces:_}=p;let A=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});A||(A=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Fr.session_approve_started,properties:{topic:d,trace:[Fr.session_approve_started,Fr.session_namespaces_validation_success]}}));const m=await this.client.core.crypto.generateKeyPair(),v=g.publicKey,x=await this.client.core.crypto.generateSharedKey(m,v),B=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:m,metadata:this.client.metadata},expiry:me(Un)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),R=he.relay;A.addTrace(Fr.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:R,internal:{skipSubscribe:!0}})}catch(b){throw A.setError(Li.subscribe_session_topic_failure),b}A.addTrace(Fr.subscribe_session_topic_success);const C=je(ie({},B),{topic:x,requiredNamespaces:y,optionalNamespaces:_,pairingTopic:d,acknowledged:!1,self:B.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:m,transportType:he.relay});await this.client.session.set(x,C),A.addTrace(Fr.store_session);try{await this.sendApproveSession({sessionTopic:x,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:m},sessionSettleRequest:B,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),A.addTrace(Fr.session_approve_publish_success)}catch(b){throw this.client.logger.error(b),this.client.session.delete(x,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),b}return this.client.core.eventClient.deleteEvent({eventId:A.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(x,me(Un)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&await this.sendError({id:n,topic:s,error:i,rpcOpts:Re.wc_sessionPropose.reject}),await this.deleteProposal(n)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=Qr(),c=zt(),u=Ur().toString(),l=this.client.session.get(n).namespaces;return this.events.once(ne("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(n,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=zt(),{done:s,resolve:o,reject:a}=Qr();return this.events.once(ne("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(Un)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:n,request:i,topic:s,expiry:o=Re.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const c=zt(),u=Ur().toString(),{done:l,resolve:h,reject:f}=Qr(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:y,result:_})=>{y?f(y):h(_)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:je(ie({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(y=>f(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const g={request:je(ie({},i),{expiryTimestamp:me(o)}),chainId:n};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),y()}),new Promise(async y=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const A=await Ex(this.client.core.storage,jg);await bx({id:c,topic:s,wcDeepLink:A})}y()}),l()]).then(y=>y[2])}),k(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);qt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):xt(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=zt(),s=Ur().toString(),{done:o,resolve:a,reject:c}=Qr();this.events.once(ne("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Ur().toString(),a=zt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>TS(n,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:g=[],expiry:y}=r,_=[...r.resources||[]],{topic:A,uri:m}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:m}});const v=await this.client.core.crypto.generateKeyPair(),x=eo(v);if(await Promise.all([this.client.auth.authKeys.set(lo,{responseTopic:x,publicKey:v}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:A})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${A}`),g.length>0){const{namespace:D}=Us(a[0]);let N=U_(D,"request",g);qs(_)&&(N=k_(N,_.pop())),_.push(N)}const B=y&&y>Re.wc_sessionAuthenticate.req.ttl?y:Re.wc_sessionAuthenticate.req.ttl,R={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:me(B)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},b={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:A,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:me(Re.wc_sessionPropose.req.ttl),id:zt()},{done:T,resolve:I,reject:$}=Qr(B,"Request expired"),P=zt(),F=ne("session_connect",b.id),E=ne("session_request",P),w=async({error:D,session:N})=>{this.events.off(E,S),D?$(D):N&&I({session:N})},S=async D=>{var N,U,L;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),D.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===W.code?void 0:(this.events.off(F,w),$(D.error.message))}await this.deleteProposal(b.id),this.events.off(F,w);const{cacaos:j,responder:V}=D.result,K=[],H=[];for(const W of j){await Pd({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),$(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ae}=W,ge=qs(ae.resources),dt=[hc(ae.iss)],At=zs(ae.iss);if(ge){const Dt=Nd(ge),Wt=Ud(ge);K.push(...Dt),dt.push(...Wt)}for(const Dt of dt)H.push(`${Dt}:${At}`)}const Z=await this.client.core.crypto.generateSharedKey(v,V.publicKey);let Q;K.length>0&&(Q={topic:Z,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:me(Un),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:Np([...new Set(K)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(Z,{transportType:o}),await this.client.session.set(Z,Q),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:V.metadata}),Q=this.client.session.get(Z)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(L=V.metadata.redirect)!=null&&L.universal&&n&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(Z,{transportType:he.link_mode})),I({auths:j,session:Q})};this.events.once(F,w),this.events.once(E,S);let O;try{if(s){const D=cr("wc_sessionAuthenticate",R,P);this.client.core.history.set(A,D);const N=await this.client.core.crypto.encode("",D,{type:Bi,encoding:Nr});O=ro(n,A,N)}else await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:R,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:b,expiry:Re.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:b.id})])}catch(D){throw this.events.off(F,w),this.events.off(E,S),D}return await this.setProposal(b.id,b),await this.setAuthRequest(P,{request:je(ie({},R),{verifyContext:{}}),pairingTopic:A,transportType:o}),{uri:O??m,response:T}}),k(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[cn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Mi.no_internet_connection),y}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Mi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=eo(c),h={type:sr,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const y of i){if(!await Pd({cacao:y,projectId:this.client.core.projectId})){s.setError(Mi.invalid_cacao);const x=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:x,encodeOpts:h}),new Error(x.message)}s.addTrace(cn.cacaos_verified);const{p:_}=y,A=qs(_.resources),m=[hc(_.iss)],v=zs(_.iss);if(A){const x=Nd(A),B=Ud(A);f.push(...x),m.push(...B)}for(const x of m)p.push(`${x}:${v}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(cn.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(Un),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:Np([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(cn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw s.setError(Mi.subscribe_authenticated_session_topic_failure),y}s.addTrace(cn.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),s.addTrace(cn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(cn.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Mi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=eo(o),u={type:sr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Re.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return Cd(n,i)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),k(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(jg).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Ht.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),k(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Li.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Ht.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),k(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),k(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Re.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),k(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=he.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Re.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=r,p=cr(i,s,c);let d;const g=!!l;try{const A=g?Nr:nt;d=await this.client.core.crypto.encode(n,p,{encoding:A})}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),A}let y;if(VD.includes(i)){const A=Et(JSON.stringify(p)),m=Et(d);y=await this.client.core.verify.register({id:m,decryptedId:A})}const _=ie(ie({},Re[i].req),f);if(_.attestation=y,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(n,p),g){const A=ro(l,n,d);await global.Linking.openURL(A,this.client.name)}else _.tvf=je(ie({},h),{correlationId:p.id}),u?(_.internal=je(ie({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,d,_)):this.client.core.relayer.publish(n,d,_).catch(A=>this.client.logger.error(A));return p.id}),k(this,"sendProposeSession",async r=>{const{proposal:n,publishOpts:i}=r,s=cr("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);const o=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:nt}),a=Et(JSON.stringify(s)),c=Et(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:je(ie({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:n,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=io(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:nt}),l=cr("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(n,l,{encoding:nt});this.client.core.history.set(n,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:je(ie({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=io(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?Nr:nt;l=await this.client.core.crypto.encode(i,u,je(ie({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),d}let f,p;try{f=await this.client.core.history.get(i,n);const d=f.request;try{p=this.getTVFParams(n,d.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),d}if(h){const d=ro(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=Re[d].res;g.tvf=je(ie({},p),{correlationId:n}),o?(g.internal=je(ie({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),k(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=Lc(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?Nr:nt;l=await this.client.core.crypto.encode(i,u,je(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let f;try{f=await this.client.core.history.get(i,n)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),p}if(h){const p=ro(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Re[p].res;this.client.core.relayer.publish(i,l,d)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;_r(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{_r(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ht.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=Ht.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Ht.idle}),k(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=z("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(ur.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||me(Re.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:n,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:Et(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Vt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Re.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(qt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(xt(n)){await this.deleteProposal(s);const o=ne("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),k(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=n.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const d=this.client.proposal.get(p.proposalId),g=je(ie(ie(ie({topic:r,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}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),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(ne("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:n.id,topic:r,result:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;qt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ne("session_approve",i),{})):xt(n)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ne("session_approve",i),{error:n.error}))}),k(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Ri.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},i));try{Ri.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Ri.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ne("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qt(n)?this.events.emit(ne("session_update",i),{}):xt(n)&&this.events.emit(ne("session_update",i),{error:n.error})}),k(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(Un)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ne("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qt(n)?this.events.emit(ne("session_extend",i),{}):xt(n)&&this.events.emit(ne("session_extend",i),{error:n.error})}),k(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ne("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);qt(n)?this.events.emit(ne("session_ping",i),{}):xt(n)&&this.events.emit(ne("session_ping",i),{error:n.error})},500)}),k(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(pe.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(ie({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:Et(JSON.stringify(cr("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(g),l===he.link_mode&&(n=p.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),k(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ne("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);qt(n)?this.events.emit(ne("session_request",i),{result:n.result}):xt(n)&&this.events.emit(ne("session_request",i),{error:n.error})}),k(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Ri.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ie({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Ri.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),qt(n)?this.events.emit(ne("session_request",i),{result:n.result}):xt(n)&&this.events.emit(ne("session_request",i),{error:n.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:Et(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===he.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:sr,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Re.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ht.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ne("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ne("session_request",s.request.id),{error:n})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ht.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),k(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Ht.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:cr("wc_sessionPropose",je(ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),k(this,"isValidConnect",async r=>{if(!it(r)){const{message:u}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Ee(n)||await this.isValidPairingTopic(n),!jS(c,!0)){const{message:u}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Ee(i)&&Ci(i)!==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(i,"requiredNamespaces")}if(!Ee(s)&&Ci(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ee(o)||this.validateSessionProps(o,"sessionProperties"),!Ee(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.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)}`)}}),k(this,"validateNamespaces",(r,n)=>{const i=qS(r,"connect()",n);if(i)throw new Error(i.message)}),k(this,"isValidApprove",async r=>{if(!it(r))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=Pc(i,"approve()");if(u)throw new Error(u.message);const l=Mp(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ye(s,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Ee(o)||this.validateSessionProps(o,"sessionProperties"),!Ee(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async r=>{if(!it(r)){const{message:s}=z("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!KS(i)){const{message:s}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!it(r)){const{message:u}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!kp(n)){const{message:u}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=US(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Pc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(_r(o)){const{message:u}=z("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async r=>{if(!it(r)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=Pc(i,"update()");if(o)throw new Error(o.message);const a=Mp(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!it(r)){const{message:i}=z("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),k(this,"isValidRequest",async r=>{if(!it(r)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!Lp(a,s)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!HS(i)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!YS(a,s,i.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!QS(o,iu)){const{message:c}=z("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${iu.min} and ${iu.max}`);throw new Error(c)}}),k(this,"isValidRespond",async r=>{var n;if(!it(r)){const{message:o}=z("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!WS(s)){const{message:o}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),k(this,"isValidPing",async r=>{if(!it(r)){const{message:i}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),k(this,"isValidEmit",async r=>{if(!it(r)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!Lp(o,s)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!GS(i)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!ZS(o,s,i.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!it(r)){const{message:i}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),k(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!ye(i,!1))throw new Error("uri is required parameter");if(!ye(s,!1))throw new Error("domain is required parameter");if(!ye(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Us(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Us(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,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}),k(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=z("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),k(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),k(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,f;return!r||n!==he.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.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)!==""&&((l=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((f=r?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=ad(r,"topic")||"",i=decodeURIComponent(ad(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(Qa()||xr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),k(this,"getTVFParams",(r,n,i)=>{var s,o,a;if(!((s=n.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{const u=this.extractTxHashesFromResult(n.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.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}),k(this,"isValidContractData",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(r,n)=>{var i;try{if(!n)return[];const s=r.method,o=qD[s];if(s==="sui_signTransaction")return[v_(n.transactionBytes)];if(s==="near_signTransaction")return[$d(n)];if(s==="near_signTransactions")return n.map(c=>$d(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=n.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[p6({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return Cn(n)?n.map(c=>Od(c)):[Od(n)];if(s==="cosmos_signDirect")return[x_(n)];if(typeof n=="string")return[n];const a=n[o.key];if(Cn(a))return s==="solana_signAllTransactions"?a.map(c=>m_(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(lo)?this.client.auth.authKeys.get(lo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===he.link_mode?Nr:nt});Mc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:Et(n)})):so(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(St.expired,async e=>{const{topic:r,id:n}=od(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,z("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,z("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(an.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(an.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ye(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(_r(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ye(e,!1)){const{message:r}=z("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(_r(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=z("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=z("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ye(e,!1)){const{message:r}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!VS(e)){const{message:r}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(_r(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=z("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class r5 extends un{constructor(e,r){super(e,r,LD,ru),this.core=e,this.logger=r}}class Hg extends un{constructor(e,r){super(e,r,MD,ru),this.core=e,this.logger=r}}class n5 extends un{constructor(e,r){super(e,r,jD,ru,n=>n.id),this.core=e,this.logger=r}}class i5 extends un{constructor(e,r){super(e,r,WD,uo,()=>lo),this.core=e,this.logger=r}}class s5 extends un{constructor(e,r){super(e,r,GD,uo),this.core=e,this.logger=r}}class o5 extends un{constructor(e,r){super(e,r,YD,uo,n=>n.id),this.core=e,this.logger=r}}var a5=Object.defineProperty,c5=(t,e,r)=>e in t?a5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ou=(t,e,r)=>c5(t,typeof e!="symbol"?e+"":e,r);class u5{constructor(e,r){this.core=e,this.logger=r,ou(this,"authKeys"),ou(this,"pairingTopics"),ou(this,"requests"),this.authKeys=new i5(this.core,this.logger),this.pairingTopics=new s5(this.core,this.logger),this.requests=new o5(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var l5=Object.defineProperty,h5=(t,e,r)=>e in t?l5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,X=(t,e,r)=>h5(t,typeof e!="symbol"?e+"":e,r);class au extends p1{constructor(e){super(e),X(this,"protocol",Mg),X(this,"version",zg),X(this,"name",nu.name),X(this,"metadata"),X(this,"core"),X(this,"logger"),X(this,"events",new Ue.exports.EventEmitter),X(this,"engine"),X(this,"session"),X(this,"proposal"),X(this,"pendingRequest"),X(this,"auth"),X(this,"signConfig"),X(this,"on",(n,i)=>this.events.on(n,i)),X(this,"once",(n,i)=>this.events.once(n,i)),X(this,"off",(n,i)=>this.events.off(n,i)),X(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),X(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),X(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),X(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),X(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),X(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||nu.name,this.metadata=fx(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Gt($o({level:e?.logger||nu.logger}));this.core=e?.core||new tu(e),this.logger=Ve(r,this.name),this.session=new Hg(this.core,this.logger),this.proposal=new r5(this.core,this.logger),this.pendingRequest=new n5(this.core,this.logger),this.engine=new t5(this),this.auth=new u5(this.core,this.logger)}static async init(e){const r=new au(e);return await r.initialize(),r}get context(){return Ze(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 f5=Hg,d5=au;class p5 extends Ue.exports{constructor(){super()}}class Wg{constructor(e){this.opts=e}}class Gg{constructor(e){this.client=e}}var g5=Object.defineProperty,y5=Object.defineProperties,w5=Object.getOwnPropertyDescriptors,Yg=Object.getOwnPropertySymbols,b5=Object.prototype.hasOwnProperty,m5=Object.prototype.propertyIsEnumerable,Zg=(t,e,r)=>e in t?g5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,v5=(t,e)=>{for(var r in e||(e={}))b5.call(e,r)&&Zg(t,r,e[r]);if(Yg)for(var r of Yg(e))m5.call(e,r)&&Zg(t,r,e[r]);return t},E5=(t,e)=>y5(t,w5(e));class x5 extends Gg{constructor(e){super(e),this.init=async()=>{this.signClient=await d5.init({core:this.client.core,metadata:this.client.metadata,signConfig:this.client.signConfig}),this.signClient.core.eventClient.init().catch(r=>{this.client.logger.warn(r)})},this.pair=async r=>{await this.client.core.pairing.pair(r)},this.approveSession=async r=>{const{topic:n,acknowledged:i}=await this.signClient.approve(E5(v5({},r),{id:r.id,namespaces:r.namespaces,sessionProperties:r.sessionProperties,sessionConfig:r.sessionConfig}));return await i(),this.signClient.session.get(n)},this.rejectSession=async r=>await this.signClient.reject(r),this.updateSession=async r=>await this.signClient.update(r),this.extendSession=async r=>await this.signClient.extend(r),this.respondSessionRequest=async r=>await this.signClient.respond(r),this.disconnectSession=async r=>await this.signClient.disconnect(r),this.emitSessionEvent=async r=>await this.signClient.emit(r),this.getActiveSessions=()=>this.signClient.session.getAll().reduce((r,n)=>(r[n.topic]=n,r),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.approveSessionAuthenticate=async r=>await this.signClient.approveSessionAuthenticate(r),this.rejectSessionAuthenticate=async r=>await this.signClient.rejectSessionAuthenticate(r),this.formatAuthMessage=r=>this.signClient.formatAuthMessage(r),this.registerDeviceToken=r=>this.client.core.echoClient.registerDeviceToken(r),this.on=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"on"),this.client.events.on(r,n)),this.once=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"once"),this.client.events.once(r,n)),this.off=(r,n)=>(this.setEvent(r,"off"),this.client.events.off(r,n)),this.removeListener=(r,n)=>(this.setEvent(r,"removeListener"),this.client.events.removeListener(r,n)),this.onSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onSessionProposal=r=>{this.client.events.emit("session_proposal",r)},this.onSessionDelete=r=>{this.client.events.emit("session_delete",r)},this.onProposalExpire=r=>{this.client.events.emit("proposal_expire",r)},this.onSessionRequestExpire=r=>{this.client.events.emit("session_request_expire",r)},this.onSessionRequestAuthenticate=r=>{this.client.events.emit("session_authenticate",r)},this.setEvent=(r,n)=>{switch(r){case"session_request":this.signClient.events[n]("session_request",this.onSessionRequest);break;case"session_proposal":this.signClient.events[n]("session_proposal",this.onSessionProposal);break;case"session_delete":this.signClient.events[n]("session_delete",this.onSessionDelete);break;case"proposal_expire":this.signClient.events[n]("proposal_expire",this.onProposalExpire);break;case"session_request_expire":this.signClient.events[n]("session_request_expire",this.onSessionRequestExpire);break;case"session_authenticate":this.signClient.events[n]("session_authenticate",this.onSessionRequestAuthenticate);break}},this.signClient={}}}const _5={decryptMessage:async t=>{const e={core:new tu({storageOptions:t.storageOptions,storage:t.storage})};await e.core.crypto.init();const r=e.core.crypto.decode(t.topic,t.encryptedMessage);return e.core=null,r},getMetadata:async t=>{const e={core:new tu({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new f5(e.core,e.core.logger),await e.sessionStore.init();const r=e.sessionStore.get(t.topic),n=r?.peer.metadata;return e.core=null,e.sessionStore=null,n}},Jg=class extends Wg{constructor(t){super(t),this.events=new Ue.exports,this.on=(e,r)=>this.engine.on(e,r),this.once=(e,r)=>this.engine.once(e,r),this.off=(e,r)=>this.engine.off(e,r),this.removeListener=(e,r)=>this.engine.removeListener(e,r),this.pair=async e=>{try{return await this.engine.pair(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(r){throw this.logger.error(r.message),r}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(r){throw this.logger.error(r.message),r}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(r){throw this.logger.error(r.message),r}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(r){throw this.logger.error(r.message),r}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.registerDeviceToken=e=>{try{return this.engine.registerDeviceToken(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSessionAuthenticate=e=>{try{return this.engine.approveSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSessionAuthenticate=e=>{try{return this.engine.rejectSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(r){throw this.logger.error(r.message),r}},this.metadata=t.metadata,this.name=t.name||fo,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new x5(this)}static async init(t){const e=new Jg(t);return await e.initialize(),e}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("WalletKit Initialization Success")}catch(t){throw this.logger.info("WalletKit Initialization Failure"),this.logger.error(t.message),t}}};let cu=Jg;cu.notifications=_5;const S5=cu;Ne.CLIENT_CONTEXT=fo,Ne.CLIENT_STORAGE_OPTIONS=d0,Ne.CLIENT_STORAGE_PREFIX=f0,Ne.IWalletKit=Wg,Ne.IWalletKitEngine=Gg,Ne.IWalletKitEvents=p5,Ne.PROTOCOL=Eu,Ne.PROTOCOL_VERSION=h0,Ne.REQUEST_CONTEXT=p0,Ne.WalletKit=S5,Ne.default=cu,Object.defineProperty(Ne,"__esModule",{value:!0})});
41
+ ***************************************************************************** */var Mc=function(t,e){return Mc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,n){r.__proto__=n}||function(r,n){for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i])},Mc(t,e)};function Q6(t,e){Mc(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var qc=function(){return qc=Object.assign||function(e){for(var r,n=1,i=arguments.length;n<i;n++){r=arguments[n];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},qc.apply(this,arguments)};function eI(t,e){var r={};for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.indexOf(n)<0&&(r[n]=t[n]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(t);i<n.length;i++)e.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(t,n[i])&&(r[n[i]]=t[n[i]]);return r}function tI(t,e,r,n){var i=arguments.length,s=i<3?e:n===null?n=Object.getOwnPropertyDescriptor(e,r):n,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,n);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,r,s):o(e,r))||s);return i>3&&s&&Object.defineProperty(e,r,s),s}function rI(t,e){return function(r,n){e(r,n,t)}}function nI(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function iI(t,e,r,n){function i(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(l){try{u(n.next(l))}catch(f){o(f)}}function c(l){try{u(n.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((n=n.apply(t,e||[])).next())})}function sI(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},n,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(n)throw new TypeError("Generator is already executing.");for(;r;)try{if(n=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,i=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){r.label=u[1];break}if(u[0]===6&&r.label<s[1]){r.label=s[1],s=u;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(u);break}s[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],i=0}finally{n=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function oI(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function aI(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function jc(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],n=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&n>=t.length&&(t=void 0),{value:t&&t[n++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var n=r.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(r=n.return)&&r.call(n)}finally{if(o)throw o.error}}return s}function cI(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(pg(arguments[e]));return t}function uI(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var n=Array(t),i=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)n[i]=s[o];return n}function Ni(t){return this instanceof Ni?(this.v=t,this):new Ni(t)}function lI(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){n[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(n[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof Ni?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function hI(t){var e,r;return e={},n("next"),n("throw",function(i){throw i}),n("return"),e[Symbol.iterator]=function(){return this},e;function n(i,s){e[i]=t[i]?function(o){return(r=!r)?{value:Ni(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function fI(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof jc=="function"?jc(t):t[Symbol.iterator](),r={},n("next"),n("throw"),n("return"),r[Symbol.asyncIterator]=function(){return this},r);function n(s){r[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function dI(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function pI(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function gI(t){return t&&t.__esModule?t:{default:t}}function yI(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function wI(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}var bI=Object.freeze({__proto__:null,__extends:Q6,get __assign(){return qc},__rest:eI,__decorate:tI,__param:rI,__metadata:nI,__awaiter:iI,__generator:sI,__createBinding:oI,__exportStar:aI,__values:jc,__read:pg,__spread:cI,__spreadArrays:uI,__await:Ni,__asyncGenerator:lI,__asyncDelegator:hI,__asyncValues:fI,__makeTemplateObject:dI,__importStar:pI,__importDefault:gI,__classPrivateFieldGet:yI,__classPrivateFieldSet:wI}),mI=gu(bI),ar={},gg;function vI(){if(gg)return ar;gg=1,Object.defineProperty(ar,"__esModule",{value:!0}),ar.isBrowserCryptoAvailable=ar.getSubtleCrypto=ar.getBrowerCrypto=void 0;function t(){return Ct?.crypto||Ct?.msCrypto||{}}ar.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}ar.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return ar.isBrowserCryptoAvailable=r,ar}var cr={},yg;function EI(){if(yg)return cr;yg=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.isBrowser=cr.isNode=cr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}cr.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}cr.isNode=e;function r(){return!t()&&!e()}return cr.isBrowser=r,cr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=mI;e.__exportStar(vI(),t),e.__exportStar(EI(),t)})(dg);function qt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Fr(t=6){return BigInt(qt(t))}function ur(t,e,r){return{id:r||qt(),jsonrpc:"2.0",method:t,params:e}}function lo(t,e){return{id:t,jsonrpc:"2.0",result:e}}function zc(t,e,r){return{id:t,jsonrpc:"2.0",error:xI(e,r)}}function xI(t,e){return typeof t>"u"?fg(lg):(typeof t=="string"&&(t=Object.assign(Object.assign({},fg(Lc)),{message:t})),typeof e<"u"&&(t.data=e),Y6(t.code)&&(t=X6(t.code)),t)}class _I{}class SI extends _I{constructor(){super()}}class II extends SI{constructor(e){super()}}const DI="^wss?:";function AI(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function $I(t,e){const r=AI(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function wg(t){return $I(t,DI)}function OI(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function bg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Kc(t){return bg(t)&&"method"in t}function ho(t){return bg(t)&&(jt(t)||_t(t))}function jt(t){return"result"in t}function _t(t){return"error"in t}class BI extends II{constructor(e){super(e),this.events=new Ce.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(ur(e.method,e.params||[],e.id||Fr().toString()),r)}async requestStrict(e,r){return new Promise(async(n,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{_t(s)?i(s.error):n(s.result)});try{await this.connection.send(e,r)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ho(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 TI=()=>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"),PI=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",mg=t=>t.split("?")[0],vg=10,RI=TI();class CI{constructor(e){if(this.url=e,this.events=new Ce.exports.EventEmitter,this.registering=!1,!wg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=n=>{this.onClose(n),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Kr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!wg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((n,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));n(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,n)=>{const i=dg.isReactNative()?void 0:{rejectUnauthorized:!OI(e)},s=new RI(e,[],i);PI()?s.onerror=o=>{const a=o;n(this.emitError(a.error))}:s.on("error",o=>{n(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?gn(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=zc(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return J6(e,mg(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>vg&&this.events.setMaxListeners(vg)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${mg(this.url)}`));return this.events.emit("register_error",r),r}}const Eg="wc",xg=2,fo="core",zt=`${Eg}@2:${fo}:`,UI={name:fo,logger:"error"},NI={database:":memory:"},FI="crypto",_g="client_ed25519_seed",kI=M.ONE_DAY,LI="keychain",MI="0.3",qI="messages",jI="0.3",zI=M.SIX_HOURS,KI="publisher",Sg="irn",VI="error",Ig="wss://relay.walletconnect.org",HI="relayer",pe={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"},WI="_subscription",St={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},GI=.1,Vc="2.21.9",le={link_mode:"link_mode",relay:"relay"},po={inbound:"inbound",outbound:"outbound"},ZI="0.3",YI="WALLETCONNECT_CLIENT_ID",Dg="WALLETCONNECT_LINK_MODE_APPS",pt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},XI="subscription",JI="0.3",QI="pairing",e4="0.3",Fi={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},ln={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Rt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},t4="history",r4="0.3",n4="expirer",It={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},i4="0.3",s4="verify-api",o4="https://verify.walletconnect.com",Ag="https://verify.walletconnect.org",ki=Ag,a4=`${ki}/v3`,c4=[o4,Ag],u4="echo",l4="https://echo.walletconnect.com",Kt={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"},lr={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"},kr={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"},Li={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"},hn={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"},Mi={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"},h4=.1,f4="event-client",d4=86400,p4="https://pulse.walletconnect.org/batch";function g4(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,S=0,D=p.length;S!==D&&p[S]===0;)S++,g++;for(var E=(D-S)*l+1>>>0,O=new Uint8Array(E);S!==D;){for(var R=p[S],C=0,U=E-1;(R!==0||C<w)&&U!==-1;U--,C++)R+=256*O[U]>>>0,O[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");w=C,S++}for(var N=E-w;N!==E&&O[N]===0;)N++;for(var $=c.repeat(g);N<E;++N)$+=t.charAt(O[N]);return $}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,S=0;p[g]===c;)w++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var O=r[p.charCodeAt(g)];if(O===255)return;for(var R=0,C=D-1;(O!==0||R<S)&&C!==-1;C--,R++)O+=a*E[C]>>>0,E[C]=O%256>>>0,O=O/256>>>0;if(O!==0)throw new Error("Non-zero carry");S=R,g++}if(p[g]!==" "){for(var U=D-S;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(w+(D-U)),$=w;U!==D;)N[$++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var y4=g4,w4=y4;const $g=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")},b4=t=>new TextEncoder().encode(t),m4=t=>new TextDecoder().decode(t);class v4{constructor(e,r,n){this.name=e,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class E4{constructor(e,r,n){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=n}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 Og(this,e)}}class x4{constructor(e){this.decoders=e}or(e){return Og(this,e)}decode(e){const r=e[0],n=this.decoders[r];if(n)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Og=(t,e)=>new x4({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class _4{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new v4(e,r,n),this.decoder=new E4(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const go=({name:t,prefix:e,encode:r,decode:n})=>new _4(t,e,r,n),qi=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=w4(r,e);return go({prefix:t,name:e,encode:n,decode:s=>$g(i(s))})},S4=(t,e,r,n)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*r/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${n} character`);c=c<<r|f,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},I4=(t,e,r)=>{const n=e[e.length-1]==="=",i=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[i&a>>o];if(o&&(s+=e[i&a<<r-o]),n)for(;s.length*r&7;)s+="=";return s},Oe=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>go({prefix:e,name:t,encode(i){return I4(i,n,r)},decode(i){return S4(i,n,r,t)}}),D4=go({prefix:"\0",name:"identity",encode:t=>m4(t),decode:t=>b4(t)});var A4=Object.freeze({__proto__:null,identity:D4});const $4=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var O4=Object.freeze({__proto__:null,base2:$4});const B4=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var T4=Object.freeze({__proto__:null,base8:B4});const P4=qi({prefix:"9",name:"base10",alphabet:"0123456789"});var R4=Object.freeze({__proto__:null,base10:P4});const C4=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),U4=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var N4=Object.freeze({__proto__:null,base16:C4,base16upper:U4});const F4=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),k4=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),L4=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),M4=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q4=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),j4=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),z4=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),K4=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),V4=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var H4=Object.freeze({__proto__:null,base32:F4,base32upper:k4,base32pad:L4,base32padupper:M4,base32hex:q4,base32hexupper:j4,base32hexpad:z4,base32hexpadupper:K4,base32z:V4});const W4=qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),G4=qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Z4=Object.freeze({__proto__:null,base36:W4,base36upper:G4});const Y4=qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),X4=qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var J4=Object.freeze({__proto__:null,base58btc:Y4,base58flickr:X4});const Q4=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),eD=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),tD=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),rD=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var nD=Object.freeze({__proto__:null,base64:Q4,base64pad:eD,base64url:tD,base64urlpad:rD});const Bg=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),iD=Bg.reduce((t,e,r)=>(t[r]=e,t),[]),sD=Bg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function oD(t){return t.reduce((e,r)=>(e+=iD[r],e),"")}function aD(t){const e=[];for(const r of t){const n=sD[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const cD=go({prefix:"\u{1F680}",name:"base256emoji",encode:oD,decode:aD});var uD=Object.freeze({__proto__:null,base256emoji:cD}),lD=Pg,Tg=128,hD=127,fD=~hD,dD=Math.pow(2,31);function Pg(t,e,r){e=e||[],r=r||0;for(var n=r;t>=dD;)e[r++]=t&255|Tg,t/=128;for(;t&fD;)e[r++]=t&255|Tg,t>>>=7;return e[r]=t|0,Pg.bytes=r-n+1,e}var pD=Hc,gD=128,Rg=127;function Hc(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Hc.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Rg)<<i:(o&Rg)*Math.pow(2,i),i+=7}while(o>=gD);return Hc.bytes=s-n,r}var yD=Math.pow(2,7),wD=Math.pow(2,14),bD=Math.pow(2,21),mD=Math.pow(2,28),vD=Math.pow(2,35),ED=Math.pow(2,42),xD=Math.pow(2,49),_D=Math.pow(2,56),SD=Math.pow(2,63),ID=function(t){return t<yD?1:t<wD?2:t<bD?3:t<mD?4:t<vD?5:t<ED?6:t<xD?7:t<_D?8:t<SD?9:10},DD={encode:lD,decode:pD,encodingLength:ID},Cg=DD;const Ug=(t,e,r=0)=>(Cg.encode(t,e,r),e),Ng=t=>Cg.encodingLength(t),Wc=(t,e)=>{const r=e.byteLength,n=Ng(t),i=n+Ng(r),s=new Uint8Array(i+r);return Ug(t,s,0),Ug(r,s,n),s.set(e,i),new AD(t,r,e,s)};class AD{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Fg=({name:t,code:e,encode:r})=>new $D(t,e,r);class $D{constructor(e,r,n){this.name=e,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Wc(this.code,r):r.then(n=>Wc(this.code,n))}else throw Error("Unknown type, must be binary type")}}const kg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),OD=Fg({name:"sha2-256",code:18,encode:kg("SHA-256")}),BD=Fg({name:"sha2-512",code:19,encode:kg("SHA-512")});var TD=Object.freeze({__proto__:null,sha256:OD,sha512:BD});const Lg=0,PD="identity",Mg=$g;var RD=Object.freeze({__proto__:null,identity:{code:Lg,name:PD,encode:Mg,digest:t=>Wc(Lg,Mg(t))}});new TextEncoder,new TextDecoder;const qg={...A4,...O4,...T4,...R4,...N4,...H4,...Z4,...J4,...nD,...uD};({...TD,...RD});function jg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function CD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?jg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function zg(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Kg=zg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Gc=zg("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=CD(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),UD={utf8:Kg,"utf-8":Kg,hex:qg.base16,latin1:Gc,ascii:Gc,binary:Gc,...qg};function ND(t,e="utf8"){const r=UD[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?jg(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var FD=Object.defineProperty,kD=(t,e,r)=>e in t?FD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vt=(t,e,r)=>kD(t,typeof e!="symbol"?e+"":e,r);class LD{constructor(e,r){this.core=e,this.logger=r,Vt(this,"keychain",new Map),Vt(this,"name",LI),Vt(this,"version",MI),Vt(this,"initialized",!1),Vt(this,"storagePrefix",zt),Vt(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),Vt(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),Vt(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),Vt(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=q("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),Vt(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=He(r,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Qa(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ec(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MD=Object.defineProperty,qD=(t,e,r)=>e in t?MD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>qD(t,typeof e!="symbol"?e+"":e,r);class jD{constructor(e,r,n){this.core=e,this.logger=r,Be(this,"name",FI),Be(this,"keychain"),Be(this,"randomSessionIdentifier",Rc()),Be(this,"initialized",!1),Be(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Be(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Be(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Wl(i);return Hl(s.publicKey)}),Be(this,"generateKeyPair",()=>{this.isInitialized();const i=AS();return this.setPrivateKey(i.publicKey,i.privateKey)}),Be(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Wl(s),a=this.randomSessionIdentifier;return await Im(a,i,kI,o)}),Be(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=$S(a,s);return this.setSymKey(c,o)}),Be(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||oo(i);return await this.keychain.set(o,i),o}),Be(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Be(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Be(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Vp(o),c=Kr(s);if(Wp(a))return TS(c,o?.encoding);if(Hp(a)){const h=a.senderPublicKey,d=a.receiverPublicKey;i=await this.generateSharedKey(h,d)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return OS({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Be(this,"decode",async(i,s,o)=>{this.isInitialized();const a=RS(s,o);if(Wp(a)){const c=PS(s,o?.encoding);return gn(c)}if(Hp(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=BS({symKey:c,encoded:s,encoding:o?.encoding});return gn(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Be(this,"getPayloadType",(i,s=it)=>{const o=Pi({encoded:i,encoding:s});return un(o.type)}),Be(this,"getPayloadSenderPublicKey",(i,s=it)=>{const o=Pi({encoded:i,encoding:s});return o.senderPublicKey?tt(o.senderPublicKey,Ye):void 0}),this.core=e,this.logger=He(r,this.name),this.keychain=n||new LD(this.core,this.logger)}get context(){return Je(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(_g)}catch{e=Rc(),await this.keychain.set(_g,e)}return ND(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var zD=Object.defineProperty,KD=Object.defineProperties,VD=Object.getOwnPropertyDescriptors,Vg=Object.getOwnPropertySymbols,HD=Object.prototype.hasOwnProperty,WD=Object.prototype.propertyIsEnumerable,Zc=(t,e,r)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,GD=(t,e)=>{for(var r in e||(e={}))HD.call(e,r)&&Zc(t,r,e[r]);if(Vg)for(var r of Vg(e))WD.call(e,r)&&Zc(t,r,e[r]);return t},ZD=(t,e)=>KD(t,VD(e)),gt=(t,e,r)=>Zc(t,typeof e!="symbol"?e+"":e,r);class YD extends Sw{constructor(e,r){super(e,r),this.logger=e,this.core=r,gt(this,"messages",new Map),gt(this,"messagesWithoutClientAck",new Map),gt(this,"name",qI),gt(this,"version",jI),gt(this,"initialized",!1),gt(this,"storagePrefix",zt),gt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const n=await this.getRelayerMessages();typeof n<"u"&&(this.messages=n);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(n){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(n)}finally{this.initialized=!0}}}),gt(this,"set",async(n,i,s)=>{this.isInitialized();const o=xt(i);let a=this.messages.get(n);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(n,a),s===po.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,ZD(GD({},c),{[o]:i}))}return await this.persist(),o}),gt(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),gt(this,"getWithoutAck",n=>{this.isInitialized();const i={};for(const s of n){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),gt(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=xt(i);return typeof s[o]<"u"}),gt(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=xt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),gt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=He(e,this.name),this.core=r}get context(){return Je(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,Qa(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Qa(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?ec(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?ec(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var XD=Object.defineProperty,JD=Object.defineProperties,QD=Object.getOwnPropertyDescriptors,Hg=Object.getOwnPropertySymbols,eA=Object.prototype.hasOwnProperty,tA=Object.prototype.propertyIsEnumerable,Yc=(t,e,r)=>e in t?XD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zn=(t,e)=>{for(var r in e||(e={}))eA.call(e,r)&&Yc(t,r,e[r]);if(Hg)for(var r of Hg(e))tA.call(e,r)&&Yc(t,r,e[r]);return t},Wg=(t,e)=>JD(t,QD(e)),Dt=(t,e,r)=>Yc(t,typeof e!="symbol"?e+"":e,r);class rA extends Iw{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,Dt(this,"events",new Ce.exports.EventEmitter),Dt(this,"name",KI),Dt(this,"queue",new Map),Dt(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),Dt(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),Dt(this,"needsTransportRestart",!1),Dt(this,"publish",async(n,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const f=s?.ttl||zI,h=s?.prompt||!1,d=s?.tag||0,p=s?.id||Fr().toString(),g=Mn(ao().protocol),w={id:p,method:s?.publishMethod||g.publish,params:zn({topic:n,message:i,ttl:f,prompt:h,tag:d,attestation:s?.attestation},s?.tvf)},S=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{Ee((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),Ee((c=w.params)==null?void 0:c.tag)&&((u=w.params)==null||delete u.tag);const D=new Promise(async E=>{const O=({id:C})=>{var U;((U=w.id)==null?void 0:U.toString())===C.toString()&&(this.removeRequestFromQueue(C),this.relayer.events.removeListener(pe.publish,O),E())};this.relayer.events.on(pe.publish,O);const R=Lt(new Promise((C,U)=>{this.rpcPublish(w,s).then(C).catch(N=>{this.logger.warn(N,N?.message),U(N)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await R,this.events.removeListener(pe.publish,O)}catch(C){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(C,C?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:n,message:i,opts:s}}),await Lt(D,this.publishTimeout,S)}catch(D){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(D),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw D}finally{this.queue.delete(p)}}),Dt(this,"publishCustom",async n=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:n});const{payload:u,opts:l={}}=n,{attestation:f,tvf:h,publishMethod:d,prompt:p,tag:g,ttl:w=M.FIVE_MINUTES}=l,S=l.id||Fr().toString(),D=Mn(ao().protocol),E=d||D.publish,O={id:S,method:E,params:zn(Wg(zn({},u),{ttl:w,prompt:p,tag:g,attestation:f}),h)},R=`Failed to publish custom payload, please try again. id:${S} tag:${g}`;try{Ee((i=O.params)==null?void 0:i.prompt)&&((s=O.params)==null||delete s.prompt),Ee((o=O.params)==null?void 0:o.tag)&&((a=O.params)==null||delete a.tag);const C=new Promise(async U=>{const N=({id:G})=>{var W;((W=O.id)==null?void 0:W.toString())===G.toString()&&(this.removeRequestFromQueue(G),this.relayer.events.removeListener(pe.publish,N),U())};this.relayer.events.on(pe.publish,N);const $=Lt(new Promise((G,W)=>{this.rpcPublish(O,l).then(G).catch(P=>{this.logger.warn(P,P?.message),W(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${S} tag:${g}`);try{await $,this.events.removeListener(pe.publish,N)}catch(G){this.queue.set(S,{request:O,opts:l,attempt:1}),this.logger.warn(G,G?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:S,payload:u,opts:l}}),await Lt(C,this.publishTimeout,R)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw C}finally{this.queue.delete(S)}}),Dt(this,"on",(n,i)=>{this.events.on(n,i)}),Dt(this,"once",(n,i)=>{this.events.once(n,i)}),Dt(this,"off",(n,i)=>{this.events.off(n,i)}),Dt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=He(r,this.name),this.registerEventListeners()}get context(){return Je(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const n=await this.relayer.request(e);return this.relayer.events.emit(pe.publish,zn(zn({},e),r)),this.logger.debug("Successfully Published Payload"),n}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var n;const i=e.attempt+1;this.queue.set(r,Wg(zn({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(n=e.request.params)==null?void 0:n.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(jr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pe.connection_stalled);return}this.checkQueue()}),this.relayer.on(pe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var nA=Object.defineProperty,iA=(t,e,r)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Kn=(t,e,r)=>iA(t,typeof e!="symbol"?e+"":e,r);class sA{constructor(){Kn(this,"map",new Map),Kn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),Kn(this,"get",e=>this.map.get(e)||[]),Kn(this,"exists",(e,r)=>this.get(e).includes(r)),Kn(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const n=this.get(e);if(!this.exists(e,r))return;const i=n.filter(s=>s!==r);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Kn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var oA=Object.defineProperty,aA=Object.defineProperties,cA=Object.getOwnPropertyDescriptors,Gg=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,Xc=(t,e,r)=>e in t?oA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ji=(t,e)=>{for(var r in e||(e={}))uA.call(e,r)&&Xc(t,r,e[r]);if(Gg)for(var r of Gg(e))lA.call(e,r)&&Xc(t,r,e[r]);return t},Jc=(t,e)=>aA(t,cA(e)),ae=(t,e,r)=>Xc(t,typeof e!="symbol"?e+"":e,r);class hA extends $w{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ae(this,"subscriptions",new Map),ae(this,"topicMap",new sA),ae(this,"events",new Ce.exports.EventEmitter),ae(this,"name",XI),ae(this,"version",JI),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",zt),ae(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",M.toMiliseconds(M.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(n,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const o=ao(i),a={topic:n,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(n,a);const c=await this.rpcSubscribe(n,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ae(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ae(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ae(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ae(this,"on",(n,i)=>{this.events.on(n,i)}),ae(this,"once",(n,i)=>{this.events.once(n,i)}),ae(this,"off",(n,i)=>{this.events.off(n,i)}),ae(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),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 n=[];this.pending.forEach(i=>{n.push(i)}),await this.batchSubscribe(n)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(jr.pulse,async()=>{await this.checkPending()}),this.events.on(pt.created,async n=>{const i=pt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(pt.deleted,async n=>{const i=pt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=He(r,this.name),this.clientId=""}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,r){let n=!1;try{n=this.getSubscription(e).topic===r}catch{}return n}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const n=this.topicMap.get(e);await Promise.all(n.map(async i=>await this.unsubscribeById(e,i,r)))}async unsubscribeById(e,r,n){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}});try{const i=ao(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:n}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,r,n){var i,s;const o=await this.getSubscriptionId(e);if((i=n?.internal)!=null&&i.skipSubscribe)return o;(!n||n?.transportType===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:Mn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=n?.internal)==null?void 0:s.throwOnFailedPublish;try{if(n?.transportType===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async f=>{const h=d=>{d.topic===e&&(this.events.removeListener(pt.created,h),f(d.id))};this.events.on(pt.created,h);try{const d=await Lt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w?.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(pt.created,h),f(d)}catch{}}),l=await Lt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pe.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Mn(r.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});try{await await Lt(new Promise(i=>{this.relayer.request(n).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Mn(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n});let i;try{i=await await Lt(new Promise((s,o)=>{this.relayer.request(n).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Mn(n.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,r){this.setSubscription(e,Jc(ji({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ji({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,n){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,n),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,ji({},r)),this.topicMap.set(r.topic,e),this.events.emit(pt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const n=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(n.topic,e),this.events.emit(pt.deleted,Jc(ji({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(pt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let n=0;n<r;n++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(pt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var n;return r.topic===((n=this.subscriptions.get(r.id))==null?void 0:n.topic)})){const{message:r}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>Jc(ji({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await Zx(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=q("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 xt(e+await this.getClientId())}}var fA=Object.defineProperty,Zg=Object.getOwnPropertySymbols,dA=Object.prototype.hasOwnProperty,pA=Object.prototype.propertyIsEnumerable,Qc=(t,e,r)=>e in t?fA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yg=(t,e)=>{for(var r in e||(e={}))dA.call(e,r)&&Qc(t,r,e[r]);if(Zg)for(var r of Zg(e))pA.call(e,r)&&Qc(t,r,e[r]);return t},ne=(t,e,r)=>Qc(t,typeof e!="symbol"?e+"":e,r);class gA extends Dw{constructor(e){super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new Ce.exports.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",HI),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ne(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Fr().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const o=`${s}:${((i=r.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),ne(this,"resetPingTimeout",()=>{Ms()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(pe.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(pe.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(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"?He(e.logger,this.name):Wt(Ro({level:e.logger||VI})),this.messages=new YD(this.logger,e.core),this.subscriber=new hA(this,this.logger),this.publisher=new rA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ig,Rx()?this.packageName=pd():Cx()&&(this.bundleId=pd()),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 Je(this.logger)}get connected(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===1||!1}get connecting(){var e,r,n;return((n=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:n.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,n){this.isInitialized(),await this.publisher.publish(e,r,n),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:le.relay},po.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var n,i,s;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((n=r?.internal)==null?void 0:n.throwOnFailedPublish)>"u"?!0:(i=r?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(pt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(pt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,Yg({internal:{throwOnFailedPublish:o}},r)).catch(h=>{o&&f(h)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Lt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,n)=>{await this.connect(e).then(r).catch(n).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 ug())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 r=e.sort((n,i)=>n.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const n of r)try{await this.onMessageEvent(n)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:n}=e;if(!r.sessionExists){const i=me(M.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(pe.message,e),await this.recordMessageEvent(e,po.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(n,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(St.disconnect,s),await Lt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(St.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(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,n()})}catch(n){await this.subscriber.stop();const i=n;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(n=>setTimeout(n,M.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(Ms())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(i=(n=this.provider)==null?void 0:n.connection)==null?void 0:i.socket)==null||s.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 BI(new CI(Lx({sdkVersion:Vc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:n,message:i}=e;await this.messages.set(n,i,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:n}=e;if(!n||n.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${n}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const i=this.messages.has(r,n);return i&&this.logger.warn(`Ignoring duplicate message: ${n}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Kc(e)){if(!e.method.endsWith(WI))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yg({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ho(e)&&this.events.emit(pe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,po.inbound),this.events.emit(pe.message,e))}async acknowledgePayload(e){const r=lo(e.id,!0);await this.provider.connection.send(r)}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 ug();R6(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(n=>this.logger.error(n,n?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(jr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&N6())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(pe.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},M.toMiliseconds(GI)))))}isInitialized(){if(!this.initialized){const{message:e}=q("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 yA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Xg(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const wA="[object RegExp]",bA="[object String]",mA="[object Number]",vA="[object Boolean]",Qg="[object Arguments]",EA="[object Symbol]",xA="[object Date]",_A="[object Map]",SA="[object Set]",IA="[object Array]",DA="[object Function]",AA="[object ArrayBuffer]",eu="[object Object]",$A="[object Error]",OA="[object DataView]",BA="[object Uint8Array]",TA="[object Uint8ClampedArray]",PA="[object Uint16Array]",RA="[object Uint32Array]",CA="[object BigUint64Array]",UA="[object Int8Array]",NA="[object Int16Array]",FA="[object Int32Array]",kA="[object BigInt64Array]",LA="[object Float32Array]",MA="[object Float64Array]";function qA(){}function e0(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 jA(t,e,r){return zi(t,e,void 0,void 0,void 0,void 0,r)}function zi(t,e,r,n,i,s,o){const a=o(t,e,r,n,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Ki(t,e,s,o)}return Ki(t,e,s,o)}function Ki(t,e,r,n){if(Object.is(t,e))return!0;let i=Jg(t),s=Jg(e);if(i===Qg&&(i=eu),s===Qg&&(s=eu),i!==s)return!1;switch(i){case bA:return t.toString()===e.toString();case mA:{const c=t.valueOf(),u=e.valueOf();return yA(c,u)}case vA:case xA:case EA:return Object.is(t.valueOf(),e.valueOf());case wA:return t.source===e.source&&t.flags===e.flags;case DA:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(i){case _A:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!zi(u,e.get(c),c,t,e,r,n))return!1;return!0}case SA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const f=c[l],h=u.findIndex(d=>zi(f,d,void 0,t,e,r,n));if(h===-1)return!1;u.splice(h,1)}return!0}case IA:case BA:case TA:case PA:case RA:case CA:case UA:case NA:case FA:case kA:case LA:case MA:{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(!zi(t[c],e[c],c,t,e,r,n))return!1;return!0}case AA:return t.byteLength!==e.byteLength?!1:Ki(new Uint8Array(t),new Uint8Array(e),r,n);case OA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ki(new Uint8Array(t),new Uint8Array(e),r,n);case $A:return t.name===e.name&&t.message===e.message;case eu:{if(!(Ki(t.constructor,e.constructor,r,n)||e0(t)&&e0(e)))return!1;const c=[...Object.keys(t),...Xg(t)],u=[...Object.keys(e),...Xg(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],h=t[f];if(!Object.hasOwn(e,f))return!1;const d=e[f];if(!zi(h,d,f,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function zA(t,e){return jA(t,e,qA)}var KA=Object.defineProperty,t0=Object.getOwnPropertySymbols,VA=Object.prototype.hasOwnProperty,HA=Object.prototype.propertyIsEnumerable,tu=(t,e,r)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,r0=(t,e)=>{for(var r in e||(e={}))VA.call(e,r)&&tu(t,r,e[r]);if(t0)for(var r of t0(e))HA.call(e,r)&&tu(t,r,e[r]);return t},ot=(t,e,r)=>tu(t,typeof e!="symbol"?e+"":e,r);class fn extends Aw{constructor(e,r,n,i=zt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,ot(this,"map",new Map),ot(this,"version",ZI),ot(this,"cached",[]),ot(this,"initialized",!1),ot(this,"getKey"),ot(this,"storagePrefix",zt),ot(this,"recentlyDeleted",[]),ot(this,"recentlyDeletedLimit",200),ot(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ee(o)?this.map.set(this.getKey(o),o):l6(o)?this.map.set(o.id,o):h6(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ot(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())}),ot(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ot(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>zA(a[c],o[c]))):this.values)),ot(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=r0(r0({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ot(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=He(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:i}=q("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WA=Object.defineProperty,GA=(t,e,r)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q=(t,e,r)=>GA(t,typeof e!="symbol"?e+"":e,r);class ZA{constructor(e,r){this.core=e,this.logger=r,Q(this,"name",QI),Q(this,"version",e4),Q(this,"events",new Ce.exports),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",zt),Q(this,"ignoredPayloadTypes",[or]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Q(this,"create",async n=>{this.isInitialized();const i=Rc(),s=await this.core.crypto.setSymKey(i),o=me(M.FIVE_MINUTES),a={protocol:Sg},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=Xp({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(ln.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType,internal:n?.internal}),{topic:s,uri:u}}),Q(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Kt.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Yp(n.uri);i.props.properties.topic=s,i.addTrace(Kt.pairing_uri_validation_success),i.addTrace(Kt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Kt.existing_pairing),l.active)throw i.setError(lr.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Kt.pairing_not_expired)}const f=c||me(M.FIVE_MINUTES),h={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,h),i.addTrace(Kt.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(ln.create,h),i.addTrace(Kt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Kt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(lr.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw i.setError(lr.subscribe_pairing_topic_failure),d}return i.addTrace(Kt.subscribe_pairing_topic_success),h}),Q(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(M.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Q(this,"ping",async n=>{this.isInitialized(),await this.isValidPing(n),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=n;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=tn();this.events.once(ie("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Q(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Q(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async n=>{this.isInitialized(),await this.isValidDisconnect(n);const{topic:i}=n;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),Q(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return Xp({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(n,i,s)=>{const o=ur(i,s),a=await this.core.crypto.encode(n,o),c=Fi[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Q(this,"sendResult",async(n,i,s)=>{const o=lo(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Fi[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"sendError",async(n,i,s)=>{const o=zc(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Fi[c]?Fi[c].res:Fi.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Q(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>xr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Q(this,"onRelayEventRequest",async n=>{const{topic:i,payload:s}=n;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Q(this,"onRelayEventResponse",async n=>{const{topic:i,payload:s}=n,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(ln.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{jt(i)?this.events.emit(ie("pairing_ping",s),{}):_t(i)&&this.events.emit(ie("pairing_ping",s),{error:i.error})},500)}),Q(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(ln.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,n,a),this.logger.error(a)}catch(a){await this.sendError(s,n,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",n))}),Q(this,"isValidPair",(n,i)=>{var s;if(!st(n)){const{message:a}=q("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(lr.malformed_pairing_uri),new Error(a)}if(!u6(n.uri)){const{message:a}=q("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(lr.malformed_pairing_uri),new Error(a)}const o=Yp(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(lr.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=q("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(lr.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(lr.pairing_expired);const{message:a}=q("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async n=>{if(!st(n)){const{message:s}=q("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Q(this,"isValidDisconnect",async n=>{if(!st(n)){const{message:s}=q("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Q(this,"isValidPairingTopic",async n=>{if(!ge(n,!1)){const{message:i}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(xr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=q("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=He(r,this.name),this.pairings=new fn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Je(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pe.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);Kc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ho(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,n)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(It.expired,async e=>{const{topic:r}=bd(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(ln.expire,{topic:r}))})}}var YA=Object.defineProperty,XA=(t,e,r)=>e in t?YA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Te=(t,e,r)=>XA(t,typeof e!="symbol"?e+"":e,r);class JA extends _w{constructor(e,r){super(e,r),this.core=e,this.logger=r,Te(this,"records",new Map),Te(this,"events",new Ce.exports.EventEmitter),Te(this,"name",t4),Te(this,"version",r4),Te(this,"cached",[]),Te(this,"initialized",!1),Te(this,"storagePrefix",zt),Te(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.records.set(n.id,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Te(this,"set",(n,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:n,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:n,request:{method:i.method,params:i.params||null},chainId:s,expiry:me(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Rt.created,o)}),Te(this,"resolve",async n=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:n}),!this.records.has(n.id))return;const i=await this.getRecord(n.id);typeof i.response>"u"&&(i.response=_t(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(Rt.updated,i))}),Te(this,"get",async(n,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:n,id:i}),await this.getRecord(i))),Te(this,"delete",(n,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===n){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Rt.deleted,s)}}),this.persist()}),Te(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Te(this,"on",(n,i)=>{this.events.on(n,i)}),Te(this,"once",(n,i)=>{this.events.once(n,i)}),Te(this,"off",(n,i)=>{this.events.off(n,i)}),Te(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=He(r,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(r=>{if(typeof r.response<"u")return;const n={topic:r.topic,request:ur(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(n)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Rt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Rt.created,e=>{const r=Rt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Rt.updated,e=>{const r=Rt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Rt.deleted,e=>{const r=Rt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(jr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{M.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Rt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var QA=Object.defineProperty,e5=(t,e,r)=>e in t?QA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>e5(t,typeof e!="symbol"?e+"":e,r);class t5 extends Ow{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new Ce.exports.EventEmitter),ze(this,"name",n4),ze(this,"version",i4),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",zt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(n=>this.expirations.set(n.target,n)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ze(this,"set",(n,i)=>{this.isInitialized();const s=this.formatTarget(n),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(It.created,{target:s,expiration:o})}),ze(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),ze(this,"del",n=>{if(this.isInitialized(),this.has(n)){const i=this.formatTarget(n),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(It.deleted,{target:i,expiration:s})}}),ze(this,"on",(n,i)=>{this.events.on(n,i)}),ze(this,"once",(n,i)=>{this.events.once(n,i)}),ze(this,"off",(n,i)=>{this.events.off(n,i)}),ze(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=He(r,this.name)}get context(){return Je(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 Mx(e);if(typeof e=="number")return qx(e);const{message:r}=q("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(It.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=q("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:n}=q("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;M.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(It.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(jr.pulse,()=>this.checkExpirations()),this.events.on(It.created,e=>{const r=It.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(It.expired,e=>{const r=It.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(It.deleted,e=>{const r=It.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}}var r5=Object.defineProperty,n5=(t,e,r)=>e in t?r5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>n5(t,typeof e!="symbol"?e+"":e,r);class i5 extends Bw{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,ye(this,"name",s4),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",a4),ye(this,"storagePrefix",zt),ye(this,"version",xg),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async i=>{if(!Pn()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=Wr(),l=this.startAbortTimer(M.ONE_SECOND*5),f=await new Promise((h,d)=>{const p=()=>{window.removeEventListener("message",w),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=S=>{if(S.data&&typeof S.data=="string")try{const D=JSON.parse(S.data);if(D.type==="verify_attestation"){if(ea(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),h(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",f),f}catch(u){this.logger.warn(u)}return""}),ye(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(ea(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);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(i?.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",i=>{let s=i||ki;return c4.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${ki}`),s=ki),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),ye(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),ye(this,"validateAttestation",(i,s)=>{const o=US(i,s.publicKey),a={hasExpired:M.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=He(r,this.name),this.abortController=new AbortController,this.isDevEnv=tc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Je(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var s5=Object.defineProperty,o5=(t,e,r)=>e in t?s5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,n0=(t,e,r)=>o5(t,typeof e!="symbol"?e+"":e,r);class a5 extends Tw{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,n0(this,"context",u4),n0(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${l4}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=He(r,this.context)}}var c5=Object.defineProperty,i0=Object.getOwnPropertySymbols,u5=Object.prototype.hasOwnProperty,l5=Object.prototype.propertyIsEnumerable,ru=(t,e,r)=>e in t?c5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vi=(t,e)=>{for(var r in e||(e={}))u5.call(e,r)&&ru(t,r,e[r]);if(i0)for(var r of i0(e))l5.call(e,r)&&ru(t,r,e[r]);return t},Se=(t,e,r)=>ru(t,typeof e!="symbol"?e+"":e,r);class h5 extends Pw{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,Se(this,"context",f4),Se(this,"storagePrefix",zt),Se(this,"storageVersion",h4),Se(this,"events",new Map),Se(this,"shouldPersist",!1),Se(this,"init",async()=>{if(!tc())try{const i={eventId:vd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:yd(this.core.relayer.protocol,this.core.relayer.version,Vc)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Se(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=vd(),l=this.core.projectId||"",f=Date.now(),h=Vi({eventId:u,timestamp:f,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,h),this.shouldPersist=!0),h}),Se(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Vi(Vi({},a),this.setMethods(a.eventId))}),Se(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Se(this,"setEventListeners",()=>{this.core.heartbeat.on(jr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>d4&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Se(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Se(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Se(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Vi(Vi({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Se(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Se(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${p4}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Vc}${s}`,{method:"POST",body:JSON.stringify(i)})}),Se(this,"getAppDomain",()=>gd().url),this.logger=He(r,this.context),this.telemetryEnabled=n,n?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var f5=Object.defineProperty,s0=Object.getOwnPropertySymbols,d5=Object.prototype.hasOwnProperty,p5=Object.prototype.propertyIsEnumerable,nu=(t,e,r)=>e in t?f5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,o0=(t,e)=>{for(var r in e||(e={}))d5.call(e,r)&&nu(t,r,e[r]);if(s0)for(var r of s0(e))p5.call(e,r)&&nu(t,r,e[r]);return t},ue=(t,e,r)=>nu(t,typeof e!="symbol"?e+"":e,r);class iu extends mw{constructor(e){var r;super(e),ue(this,"protocol",Eg),ue(this,"version",xg),ue(this,"name",fo),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new Ce.exports.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ig,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Ro({level:typeof e?.logger=="string"&&e.logger?e.logger:UI.logger,name:fo}),{logger:s,chunkLoggerController:o}=yw({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=He(s,this.name),this.heartbeat=new Do,this.crypto=new jD(this,this.logger,e?.keychain),this.history=new JA(this,this.logger),this.expirer=new t5(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new jy(o0(o0({},NI),e?.storageOptions)),this.relayer=new gA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ZA(this,this.logger),this.verify=new i5(this,this.logger,this.storage),this.echoClient=new a5(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new h5(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new iu(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(YI,n),r}get context(){return Je(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(Dg,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(Dg)||[],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 r=`_walletConnectCore_${e}`,n=`${r}_count`;return globalThis[n]=(globalThis[n]||0)+1,globalThis[n]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[n]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const su=iu,a0="wc",c0=2,u0="client",ou=`${a0}@${c0}:${u0}:`,au={name:u0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},l0="WALLETCONNECT_DEEPLINK_CHOICE",g5="proposal",h0="Proposal expired",y5="session",Vn=M.SEVEN_DAYS,w5="engine",Pe={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},cu={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Ht={idle:"IDLE",active:"ACTIVE"},b5={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:""}},m5="request",v5=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],E5="wc",x5="auth",_5="authKeys",S5="pairingTopics",I5="requests",yo=`${E5}@${1.5}:${x5}:`,wo=`${yo}:PUB_KEY`;var D5=Object.defineProperty,A5=Object.defineProperties,$5=Object.getOwnPropertyDescriptors,f0=Object.getOwnPropertySymbols,O5=Object.prototype.hasOwnProperty,B5=Object.prototype.propertyIsEnumerable,uu=(t,e,r)=>e in t?D5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,se=(t,e)=>{for(var r in e||(e={}))O5.call(e,r)&&uu(t,r,e[r]);if(f0)for(var r of f0(e))B5.call(e,r)&&uu(t,r,e[r]);return t},Ke=(t,e)=>A5(t,$5(e)),F=(t,e,r)=>uu(t,typeof e!="symbol"?e+"":e,r);class T5 extends Nw{constructor(e){super(e),F(this,"name",w5),F(this,"events",new Ce.exports),F(this,"initialized",!1),F(this,"requestQueue",{state:Ht.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Ht.idle,queue:[]}),F(this,"emittedSessionRequests",new Yx({limit:500})),F(this,"requestQueueDelay",M.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(Pe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Ke(se({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=i6(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,f,h=!1;try{if(l){const C=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=C.active}}catch(C){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),C}if(!l||!h){const{topic:C,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=C,f=U}if(!l){const{message:C}=q("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(C)}const d=await this.client.core.crypto.generateKeyPair(),p=Pe.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=me(p),w=Ke(se(se({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Sg}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:qt()}),S=ie("session_connect",w.id),{reject:D,resolve:E,done:O}=tn(p,h0),R=({id:C})=>{C===w.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(w.id),this.events.emit(S,{error:{message:h0,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(S,({error:C,session:U})=>{this.client.events.off("proposal_expire",R),C?D(C):U&&E(U)}),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}),await this.setProposal(w.id,w),{uri:f,approval:O}}),F(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(n){throw this.client.logger.error("pair() failed"),n}}),F(this,"approve",async r=>{var n,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(n=r?.id)==null?void 0:n.toString(),trace:[kr.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch($){throw o.setError(Li.no_internet_connection),$}try{await this.isValidProposalId(r?.id)}catch($){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Li.proposal_not_found),$}try{await this.isValidApprove(r)}catch($){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Li.session_approve_namespace_validation_failure),$}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=r,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:w,optionalNamespaces:S}=d;let D=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:p});D||(D=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:kr.session_approve_started,properties:{topic:p,trace:[kr.session_approve_started,kr.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),O=g.publicKey,R=await this.client.core.crypto.generateSharedKey(E,O),C=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:me(Vn)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),U=le.relay;D.addTrace(kr.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:U,internal:{skipSubscribe:!0}})}catch($){throw D.setError(Li.subscribe_session_topic_failure),$}D.addTrace(kr.subscribe_session_topic_success);const N=Ke(se({},C),{topic:R,requiredNamespaces:w,optionalNamespaces:S,pairingTopic:p,acknowledged:!1,self:C.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:E,transportType:le.relay});await this.client.session.set(R,N),D.addTrace(kr.store_session);try{await this.sendApproveSession({sessionTopic:R,proposal:d,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:E},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),D.addTrace(kr.session_approve_publish_success)}catch($){throw this.client.logger.error($),this.client.session.delete(R,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),$}return this.client.core.eventClient.deleteEvent({eventId:D.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(R,me(Vn)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),F(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:n,reason:i}=r;let s;try{s=this.client.proposal.get(n).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${n}) failed`),o}s&&await this.sendError({id:n,topic:s,error:i,rpcOpts:Pe.wc_sessionPropose.reject}),await this.deleteProposal(n)}),F(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:n,namespaces:i}=r,{done:s,resolve:o,reject:a}=tn(),c=qt(),u=Fr().toString(),l=this.client.session.get(n).namespaces;return this.events.once(ie("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(n,{namespaces:i}),await this.sendRequest({topic:n,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(n,{namespaces:l}),a(f)}),{acknowledged:s}}),F(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:n}=r,i=qt(),{done:s,resolve:o,reject:a}=tn();return this.events.once(ie("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(Vn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),F(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=Pe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const c=qt(),u=Fr().toString(),{done:l,resolve:f,reject:h}=tn(o,"Request expired. Please try again.");this.events.once(ie("session_request",c),({error:w,result:S})=>{w?h(w):f(S)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:Ke(se({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>h(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const g={request:Ke(se({},i),{expiryTimestamp:me(o)}),chainId:n};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(S=>h(S)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var S;if(!((S=a.sessionConfig)!=null&&S.disableDeepLink)){const D=await Vx(this.client.core.storage,l0);await jx({id:c,topic:s,wcDeepLink:D})}w()}),l()]).then(w=>w[2])}),F(this,"respond",async r=>{this.isInitialized(),await this.isValidRespond(r);const{topic:n,response:i}=r,{id:s}=i,o=this.client.session.get(n);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);jt(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):_t(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),F(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:n}=r;if(this.client.session.keys.includes(n)){const i=qt(),s=Fr().toString(),{done:o,resolve:a,reject:c}=tn();this.events.once(ie("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:n,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(n)&&(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:n}))}),F(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Fr().toString(),a=qt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:n}=r;if(this.client.session.keys.includes(n))await this.sendRequest({topic:n,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:n,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(n))await this.client.core.pairing.disconnect({topic:n});else{const{message:i}=q("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),F(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>a6(n,r)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(r,n)=>{var i;this.isInitialized(),this.isValidAuthenticate(r);const s=n&&this.client.core.linkModeSupportedApps.includes(n)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:h,exp:d,nbf:p,methods:g=[],expiry:w}=r,S=[...r.resources||[]],{topic:D,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:E}});const O=await this.client.core.crypto.generateKeyPair(),R=oo(O);if(await Promise.all([this.client.auth.authKeys.set(wo,{responseTopic:R,publicKey:O}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:D})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),g.length>0){const{namespace:x}=Ls(a[0]);let I=o8(x,"request",g);Gs(S)&&(I=c8(I,S.pop())),S.push(I)}const C=w&&w>Pe.wc_sessionAuthenticate.req.ttl?w:Pe.wc_sessionAuthenticate.req.ttl,U={authPayload:{type:h??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:d,nbf:p,resources:S},requester:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:me(C)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:O,metadata:this.client.metadata},expiryTimestamp:me(Pe.wc_sessionPropose.req.ttl),id:qt()},{done:G,resolve:W,reject:P}=tn(C,"Request expired"),v=qt(),m=ie("session_connect",$.id),y=ie("session_request",v),b=async({error:x,session:I})=>{this.events.off(y,_),x?P(x):I&&W({session:I})},_=async x=>{var I,B,T;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),x.error){const V=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===V.code?void 0:(this.events.off(m,b),P(x.error.message))}await this.deleteProposal($.id),this.events.off(m,b);const{cacaos:j,responder:L}=x.result,k=[],z=[];for(const V of j){await Vd({cacao:V,projectId:this.client.core.projectId})||(this.client.logger.error(V,"Signature verification failed"),P(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=V,he=Gs(Y.resources),Ve=[lc(Y.iss)],yt=Ws(Y.iss);if(he){const hr=Gd(he),du=Zd(he);k.push(...hr),Ve.push(...du)}for(const hr of Ve)z.push(`${hr}:${yt}`)}const H=await this.client.core.crypto.generateSharedKey(O,L.publicKey);let Z;k.length>0&&(Z={topic:H,acknowledged:!0,self:{publicKey:O,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:me(Vn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:rg([...new Set(k)],[...new Set(z)]),transportType:o},await this.client.core.relayer.subscribe(H,{transportType:o}),await this.client.session.set(H,Z),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:L.metadata}),Z=this.client.session.get(H)),(I=this.client.metadata.redirect)!=null&&I.linkMode&&(B=L.metadata.redirect)!=null&&B.linkMode&&(T=L.metadata.redirect)!=null&&T.universal&&n&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(H,{transportType:le.link_mode})),W({auths:j,session:Z})};this.events.once(m,b),this.events.once(y,_);let A;try{if(s){const x=ur("wc_sessionAuthenticate",U,v);this.client.core.history.set(D,x);const I=await this.client.core.crypto.encode("",x,{type:Bi,encoding:Nr});A=co(n,D,I)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:U,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:$,expiry:Pe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(x){throw this.events.off(m,b),this.events.off(y,_),x}return await this.setProposal($.id,$),await this.setAuthRequest(v,{request:Ke(se({},U),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:A??E,response:G}}),F(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[hn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(Mi.no_internet_connection),w}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(Mi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=oo(c),f={type:or,receiverPublicKey:c,senderPublicKey:u},h=[],d=[];for(const w of i){if(!await Vd({cacao:w,projectId:this.client.core.projectId})){s.setError(Mi.invalid_cacao);const R=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:R,encodeOpts:f}),new Error(R.message)}s.addTrace(hn.cacaos_verified);const{p:S}=w,D=Gs(S.resources),E=[lc(S.iss)],O=Ws(S.iss);if(D){const R=Gd(D),C=Zd(D);h.push(...R),E.push(...C)}for(const R of E)d.push(`${R}:${O}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(hn.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(Vn),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:rg([...new Set(h)],[...new Set(d)]),transportType:a},s.addTrace(hn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(Mi.subscribe_authenticated_session_topic_failure),w}s.addTrace(hn.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(hn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(hn.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:n,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(Mi.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(n,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),F(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:n,reason:i}=r,s=this.getPendingAuthRequest(n);if(!s)throw new Error(`Could not find pending auth request with id ${n}`);s.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=oo(o),u={type:or,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Pe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.deleteProposal(n)}),F(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return Hd(n,i)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),F(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const n=this.client.core.pairing.pairings.get(r.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&s.topic&&s.topic!==n.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(n){this.client.logger.error(n)}}),F(this,"deleteSession",async r=>{var n;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(l0).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=Ht.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),F(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Li.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),F(this,"deletePendingSessionRequest",async(r,n,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),i&&(this.sessionRequestQueue.state=Ht.idle,this.client.events.emit("session_request_expire",{id:r}))}),F(this,"deletePendingAuthRequest",async(r,n,i=!1)=>{await Promise.all([this.client.auth.requests.delete(r,n),i?Promise.resolve():this.client.core.expirer.del(r)])}),F(this,"setExpiry",async(r,n)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,n),await this.client.session.update(r,{expiry:n}))}),F(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Pe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),F(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=le.relay}=n;this.client.core.expirer.set(r,i.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:r,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Pe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(n,a),await this.client.pendingRequest.set(n,{id:n,topic:i,params:s,verifyContext:o})}),F(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:h={}}=r,d=ur(i,s,c);let p;const g=!!l;try{const D=g?Nr:it;p=await this.client.core.crypto.encode(n,d,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),D}let w;if(v5.includes(i)){const D=xt(JSON.stringify(d)),E=xt(p);w=await this.client.core.verify.register({id:E,decryptedId:D})}const S=se(se({},Pe[i].req),h);if(S.attestation=w,o&&(S.ttl=o),a&&(S.id=a),this.client.core.history.set(n,d),g){const D=co(l,n,p);await global.Linking.openURL(D,this.client.name)}else S.tvf=Ke(se({},f),{correlationId:d.id}),u?(S.internal=Ke(se({},S.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,S)):this.client.core.relayer.publish(n,p,S).catch(D=>this.client.logger.error(D));return d.id}),F(this,"sendProposeSession",async r=>{const{proposal:n,publishOpts:i}=r,s=ur("wc_sessionPropose",n,n.id);this.client.core.history.set(n.pairingTopic,s);const o=await this.client.core.crypto.encode(n.pairingTopic,s,{encoding:it}),a=xt(JSON.stringify(s)),c=xt(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:n.pairingTopic,sessionProposal:o},opts:Ke(se({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),F(this,"sendApproveSession",async r=>{const{sessionTopic:n,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=lo(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:it}),l=ur("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(n,l,{encoding:it});this.client.core.history.set(n,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:n,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Ke(se({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=lo(n,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Nr:it;l=await this.client.core.crypto.encode(i,u,Ke(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,d;try{h=await this.client.core.history.get(i,n);const p=h.request;try{d=this.getTVFParams(n,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),p}if(f){const p=co(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Pe[p].res;g.tvf=Ke(se({},d),{correlationId:n}),o?(g.internal=Ke(se({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(u)}),F(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=zc(n,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=f?Nr:it;l=await this.client.core.crypto.encode(i,u,Ke(se({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let h;try{h=await this.client.core.history.get(i,n)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${n}) failed`),d}if(f){const d=co(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=h.request.method,p=a||Pe[d].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),F(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;xr(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&r.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{xr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),F(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),F(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Ht.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=Ht.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=Ht.idle}),F(this,"processRequest",async r=>{const{topic:n,payload:i,attestation:s,transportType:o,encryptedId:a}=r,c=i.method;if(!this.shouldIgnorePairingRequest({topic:n,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:n,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(n,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(n,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(n,i);case"wc_sessionPing":return await this.onSessionPingRequest(n,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(n,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(n,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:n,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async r=>{const{topic:n,payload:i,transportType:s}=r,o=(await this.client.core.history.get(n,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(n,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(n,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(n,i);case"wc_sessionExtend":return this.onSessionExtendResponse(n,i);case"wc_sessionPing":return this.onSessionPingResponse(n,i);case"wc_sessionRequest":return this.onSessionRequestResponse(n,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(n,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=q("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),F(this,"shouldIgnorePairingRequest",r=>{const{topic:n,requestMethod:i}=r,s=this.expectedPairingMethodMap.get(n);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async r=>{const{topic:n,payload:i,attestation:s,encryptedId:o}=r,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:n});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(lr.proposal_listener_not_found)),this.isValidConnect(se({},i.params));const l=a.expiryTimestamp||me(Pe.wc_sessionPropose.req.ttl),f=se({id:c,pairingTopic:n,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const h=await this.getVerifyContext({attestationId:s,hash:xt(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(Kt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:h})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Pe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),F(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(jt(n)){const{result:o}=n;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:r,proposalId:s,publicKey:c});const f=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:r})}else if(_t(n)){await this.deleteProposal(s);const o=ie("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:n.error})}}),F(this,"onSessionSettleRequest",async(r,n)=>{const{id:i,params:s}=n;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=n.params,d=[...this.pendingSessions.values()].find(w=>w.sessionTopic===r);if(!d)return this.client.logger.error(`Pending session not found for topic ${r}`);const p=this.client.proposal.get(d.proposalId),g=Ke(se(se(se({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),{transportType:le.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ie("session_connect",d.proposalId),{session:g}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:n.id,topic:r,result:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;jt(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ie("session_approve",i),{})):_t(n)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ie("session_approve",i),{error:n.error}))}),F(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Ci.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:r},i));try{Ci.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Ci.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:i})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=ie("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);jt(n)?this.events.emit(ie("session_update",i),{}):_t(n)&&this.events.emit(ie("session_update",i),{error:n.error})}),F(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(Vn)),await this.sendResult({id:i,topic:r,result:!0}),this.client.events.emit("session_extend",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),F(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=ie("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);jt(n)?this.events.emit(ie("session_extend",i),{}):_t(n)&&this.events.emit(ie("session_extend",i),{error:n.error})}),F(this,"onSessionPingRequest",async(r,n)=>{const{id:i}=n;try{this.isValidPing({topic:r}),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:r})}catch(s){await this.sendError({id:i,topic:r,error:s}),this.client.logger.error(s)}}),F(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=ie("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);jt(n)?this.events.emit(ie("session_ping",i),{}):_t(n)&&this.events.emit(ie("session_ping",i),{error:n.error})},500)}),F(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(pe.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),F(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:f,params:h}=a;try{await this.isValidRequest(se({topic:o},h));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:xt(JSON.stringify(ur("wc_sessionRequest",h,f))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:f,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),l===le.link_mode&&(n=d.peer.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp((i=d.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:f,topic:o,error:d}),this.client.logger.error(d)}}),F(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=ie("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);jt(n)?this.events.emit(ie("session_request",i),{result:n.result}):_t(n)&&this.events.emit(ie("session_request",i),{error:n.error})}),F(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Ci.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(se({topic:r},s)),this.client.events.emit("session_event",{id:i,topic:r,params:s}),Ci.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),jt(n)?this.events.emit(ie("session_request",i),{result:n.result}):_t(n)&&this.events.emit(ie("session_request",i),{error:n.error})}),F(this,"onSessionAuthenticateRequest",async r=>{var n;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,h=await this.getVerifyContext({attestationId:o,hash:xt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:h,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:d,pairingTopic:i,transportType:c}),c===le.link_mode&&(n=u.metadata.redirect)!=null&&n.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:or,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:d,rpcOpts:Pe.wc_sessionAuthenticate.autoReject,appLink:h})}}),F(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),F(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Ht.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:n})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ie("session_request",s.request.id),{error:n})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Ht.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),F(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Ht.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),F(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const n=this.client.proposal.getAll().find(i=>i.pairingTopic===r.topic);n&&this.onSessionProposeRequest({topic:r.topic,payload:ur("wc_sessionPropose",Ke(se({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id),attestation:n.attestation,encryptedId:n.encryptedId})}),F(this,"isValidConnect",async r=>{if(!st(r)){const{message:u}=q("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:n,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(Ee(n)||await this.isValidPairingTopic(n),!m6(c,!0)){const{message:u}=q("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Ee(i)&&Ri(i)!==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(i,"requiredNamespaces")}if(!Ee(s)&&Ri(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Ee(o)||this.validateSessionProps(o,"sessionProperties"),!Ee(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.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",(r,n)=>{const i=b6(r,"connect()",n);if(i)throw new Error(i.message)}),F(this,"isValidApprove",async r=>{if(!st(r))throw new Error(q("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:n,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(n),await this.isValidProposalId(n);const c=this.client.proposal.get(n),u=Nc(i,"approve()");if(u)throw new Error(u.message);const l=ag(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ge(s,!0)){const{message:f}=q("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(Ee(o)||this.validateSessionProps(o,"sessionProperties"),!Ee(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(h=>f.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),F(this,"isValidReject",async r=>{if(!st(r)){const{message:s}=q("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!E6(i)){const{message:s}=q("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),F(this,"isValidSessionSettleRequest",r=>{if(!st(r)){const{message:u}=q("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!sg(n)){const{message:u}=q("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=f6(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Nc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(xr(o)){const{message:u}=q("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),F(this,"isValidUpdate",async r=>{if(!st(r)){const{message:c}=q("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:n,namespaces:i}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const s=this.client.session.get(n),o=Nc(i,"update()");if(o)throw new Error(o.message);const a=ag(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async r=>{if(!st(r)){const{message:i}=q("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),F(this,"isValidRequest",async r=>{if(!st(r)){const{message:c}=q("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:n,request:i,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n);const{namespaces:a}=this.client.session.get(n);if(!og(a,s)){const{message:c}=q("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!x6(i)){const{message:c}=q("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!I6(a,s,i.method)){const{message:c}=q("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!O6(o,cu)){const{message:c}=q("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${cu.min} and ${cu.max}`);throw new Error(c)}}),F(this,"isValidRespond",async r=>{var n;if(!st(r)){const{message:o}=q("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(o)}const{topic:i,response:s}=r;try{await this.isValidSessionTopic(i)}catch(o){throw(n=r?.response)!=null&&n.id&&this.cleanupAfterResponse(r),o}if(!_6(s)){const{message:o}=q("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),F(this,"isValidPing",async r=>{if(!st(r)){const{message:i}=q("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),F(this,"isValidEmit",async r=>{if(!st(r)){const{message:a}=q("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:n,event:i,chainId:s}=r;await this.isValidSessionTopic(n);const{namespaces:o}=this.client.session.get(n);if(!og(o,s)){const{message:a}=q("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!S6(i)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!D6(o,s,i.name)){const{message:a}=q("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async r=>{if(!st(r)){const{message:i}=q("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),F(this,"isValidAuthenticate",r=>{const{chains:n,uri:i,domain:s,nonce:o}=r;if(!Array.isArray(n)||n.length===0)throw new Error("chains is required and must be a non-empty array");if(!ge(i,!1))throw new Error("uri is required parameter");if(!ge(s,!1))throw new Error("domain is required parameter");if(!ge(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Ls(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ls(n[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 r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||ki,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:n,hash:i,encryptedId:s,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",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=q("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),F(this,"addToRecentlyDeleted",(r,n)=>{if(this.recentlyDeletedMap.set(r,n),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=q("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),F(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,f,h;return!r||n!==le.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.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)!==""&&((l=r?.redirect)==null?void 0:l.universal)!==void 0&&((f=r?.redirect)==null?void 0:f.universal)!==""&&((h=r?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),F(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=md(r,"topic")||"",i=decodeURIComponent(md(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),F(this,"registerLinkModeListeners",async()=>{var r;if(tc()||Er()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const n=global==null?void 0:global.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await n.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),F(this,"getTVFParams",(r,n,i)=>{var s,o,a;if(!((s=n.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[n.request.method],chainId:n.chainId};try{const u=this.extractTxHashesFromResult(n.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(n.request.params)?[(a=(o=n.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",r=>{var n;if(!r)return!1;try{const i=r?.data||((n=r?.[0])==null?void 0:n.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(r,n)=>{var i;try{if(!n)return[];const s=r.method,o=b5[s];if(s==="sui_signTransaction")return[z_(n.transactionBytes)];if(s==="near_signTransaction")return[qd(n)];if(s==="near_signTransactions")return n.map(c=>qd(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=n.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[K6({transaction:r.params.transactionPayload,signature:n.signature})];if(s==="algo_signTxn")return jn(n)?n.map(c=>jd(c)):[jd(n)];if(s==="cosmos_signDirect")return[V_(n)];if(s==="wallet_sendCalls")return H_(n);if(typeof n=="string")return[n];const a=n[o.key];if(jn(a))return s==="solana_signAllTransactions"?a.map(c=>j_(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[n,i]of Object.entries(r))for(const s of i)try{await this.onProviderMessageEvent({topic:n,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${n}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=q("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:n,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(wo)?this.client.auth.authKeys.get(wo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===le.link_mode?Nr:it});Kc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:xt(n)})):ho(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(r,n)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(It.expired,async e=>{const{topic:r,id:n}=bd(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,q("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,q("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):n&&(await this.deleteProposal(n,!0),this.client.events.emit("proposal_expire",{id:n}))})}registerPairingEvents(){this.client.core.pairing.events.on(ln.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(ln.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ge(e,!1)){const{message:r}=q("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=q("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(xr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=q("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ge(e,!1)){const{message:r}=q("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=q("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(xr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=q("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=q("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ge(e,!1)){const{message:r}=q("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=q("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!v6(e)){const{message:r}=q("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=q("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(xr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=q("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class P5 extends fn{constructor(e,r){super(e,r,g5,ou),this.core=e,this.logger=r}}class d0 extends fn{constructor(e,r){super(e,r,y5,ou),this.core=e,this.logger=r}}class R5 extends fn{constructor(e,r){super(e,r,m5,ou,n=>n.id),this.core=e,this.logger=r}}class C5 extends fn{constructor(e,r){super(e,r,_5,yo,()=>wo),this.core=e,this.logger=r}}class U5 extends fn{constructor(e,r){super(e,r,S5,yo),this.core=e,this.logger=r}}class N5 extends fn{constructor(e,r){super(e,r,I5,yo,n=>n.id),this.core=e,this.logger=r}}var F5=Object.defineProperty,k5=(t,e,r)=>e in t?F5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lu=(t,e,r)=>k5(t,typeof e!="symbol"?e+"":e,r);class L5{constructor(e,r){this.core=e,this.logger=r,lu(this,"authKeys"),lu(this,"pairingTopics"),lu(this,"requests"),this.authKeys=new C5(this.core,this.logger),this.pairingTopics=new U5(this.core,this.logger),this.requests=new N5(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var M5=Object.defineProperty,q5=(t,e,r)=>e in t?M5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>q5(t,typeof e!="symbol"?e+"":e,r);class hu extends Uw{constructor(e){super(e),ee(this,"protocol",a0),ee(this,"version",c0),ee(this,"name",au.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new Ce.exports.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(n,i)=>this.events.on(n,i)),ee(this,"once",(n,i)=>this.events.once(n,i)),ee(this,"off",(n,i)=>this.events.off(n,i)),ee(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),ee(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),ee(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),ee(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||au.name,this.metadata=Nx(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Wt(Ro({level:e?.logger||au.logger}));this.core=e?.core||new su(e),this.logger=He(r,this.name),this.session=new d0(this.core,this.logger),this.proposal=new P5(this.core,this.logger),this.pendingRequest=new R5(this.core,this.logger),this.engine=new T5(this),this.auth=new L5(this.core,this.logger)}static async init(e){const r=new hu(e);return await r.initialize(),r}get context(){return Je(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 j5=d0,z5=hu;class K5 extends Ce.exports{constructor(){super()}}class p0{constructor(e){this.opts=e}}class g0{constructor(e){this.client=e}}var V5=Object.defineProperty,H5=Object.defineProperties,W5=Object.getOwnPropertyDescriptors,y0=Object.getOwnPropertySymbols,G5=Object.prototype.hasOwnProperty,Z5=Object.prototype.propertyIsEnumerable,w0=(t,e,r)=>e in t?V5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y5=(t,e)=>{for(var r in e||(e={}))G5.call(e,r)&&w0(t,r,e[r]);if(y0)for(var r of y0(e))Z5.call(e,r)&&w0(t,r,e[r]);return t},X5=(t,e)=>H5(t,W5(e));class J5 extends g0{constructor(e){super(e),this.init=async()=>{this.signClient=await z5.init({core:this.client.core,metadata:this.client.metadata,signConfig:this.client.signConfig}),this.signClient.core.eventClient.init().catch(r=>{this.client.logger.warn(r)})},this.pair=async r=>{await this.client.core.pairing.pair(r)},this.approveSession=async r=>{const{topic:n,acknowledged:i}=await this.signClient.approve(X5(Y5({},r),{id:r.id,namespaces:r.namespaces,sessionProperties:r.sessionProperties,sessionConfig:r.sessionConfig}));return await i(),this.signClient.session.get(n)},this.rejectSession=async r=>await this.signClient.reject(r),this.updateSession=async r=>await this.signClient.update(r),this.extendSession=async r=>await this.signClient.extend(r),this.respondSessionRequest=async r=>await this.signClient.respond(r),this.disconnectSession=async r=>await this.signClient.disconnect(r),this.emitSessionEvent=async r=>await this.signClient.emit(r),this.getActiveSessions=()=>this.signClient.session.getAll().reduce((r,n)=>(r[n.topic]=n,r),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.approveSessionAuthenticate=async r=>await this.signClient.approveSessionAuthenticate(r),this.rejectSessionAuthenticate=async r=>await this.signClient.rejectSessionAuthenticate(r),this.formatAuthMessage=r=>this.signClient.formatAuthMessage(r),this.registerDeviceToken=r=>this.client.core.echoClient.registerDeviceToken(r),this.on=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"on"),this.client.events.on(r,n)),this.once=(r,n)=>(this.setEvent(r,"off"),this.setEvent(r,"once"),this.client.events.once(r,n)),this.off=(r,n)=>(this.setEvent(r,"off"),this.client.events.off(r,n)),this.removeListener=(r,n)=>(this.setEvent(r,"removeListener"),this.client.events.removeListener(r,n)),this.onSessionRequest=r=>{this.client.events.emit("session_request",r)},this.onSessionProposal=r=>{this.client.events.emit("session_proposal",r)},this.onSessionDelete=r=>{this.client.events.emit("session_delete",r)},this.onProposalExpire=r=>{this.client.events.emit("proposal_expire",r)},this.onSessionRequestExpire=r=>{this.client.events.emit("session_request_expire",r)},this.onSessionRequestAuthenticate=r=>{this.client.events.emit("session_authenticate",r)},this.setEvent=(r,n)=>{switch(r){case"session_request":this.signClient.events[n]("session_request",this.onSessionRequest);break;case"session_proposal":this.signClient.events[n]("session_proposal",this.onSessionProposal);break;case"session_delete":this.signClient.events[n]("session_delete",this.onSessionDelete);break;case"proposal_expire":this.signClient.events[n]("proposal_expire",this.onProposalExpire);break;case"session_request_expire":this.signClient.events[n]("session_request_expire",this.onSessionRequestExpire);break;case"session_authenticate":this.signClient.events[n]("session_authenticate",this.onSessionRequestAuthenticate);break}},this.signClient={}}}const Q5={decryptMessage:async t=>{const e={core:new su({storageOptions:t.storageOptions,storage:t.storage})};await e.core.crypto.init();const r=e.core.crypto.decode(t.topic,t.encryptedMessage);return e.core=null,r},getMetadata:async t=>{const e={core:new su({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new j5(e.core,e.core.logger),await e.sessionStore.init();const r=e.sessionStore.get(t.topic),n=r?.peer.metadata;return e.core=null,e.sessionStore=null,n}},b0=class extends p0{constructor(t){super(t),this.events=new Ce.exports,this.on=(e,r)=>this.engine.on(e,r),this.once=(e,r)=>this.engine.once(e,r),this.off=(e,r)=>this.engine.off(e,r),this.removeListener=(e,r)=>this.engine.removeListener(e,r),this.pair=async e=>{try{return await this.engine.pair(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(r){throw this.logger.error(r.message),r}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(r){throw this.logger.error(r.message),r}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(r){throw this.logger.error(r.message),r}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(r){throw this.logger.error(r.message),r}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(r){throw this.logger.error(r.message),r}},this.getActiveSessions=()=>{try{return this.engine.getActiveSessions()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionProposals=()=>{try{return this.engine.getPendingSessionProposals()}catch(e){throw this.logger.error(e.message),e}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(e){throw this.logger.error(e.message),e}},this.registerDeviceToken=e=>{try{return this.engine.registerDeviceToken(e)}catch(r){throw this.logger.error(r.message),r}},this.approveSessionAuthenticate=e=>{try{return this.engine.approveSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.rejectSessionAuthenticate=e=>{try{return this.engine.rejectSessionAuthenticate(e)}catch(r){throw this.logger.error(r.message),r}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(r){throw this.logger.error(r.message),r}},this.metadata=t.metadata,this.name=t.name||bo,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new J5(this)}static async init(t){const e=new b0(t);return await e.initialize(),e}async initialize(){this.logger.trace("Initialized");try{await this.engine.init(),this.logger.info("WalletKit Initialization Success")}catch(t){throw this.logger.info("WalletKit Initialization Failure"),this.logger.error(t.message),t}}};let fu=b0;fu.notifications=Q5;const e$=fu;Re.CLIENT_CONTEXT=bo,Re.CLIENT_STORAGE_OPTIONS=C0,Re.CLIENT_STORAGE_PREFIX=R0,Re.IWalletKit=p0,Re.IWalletKitEngine=g0,Re.IWalletKitEvents=K5,Re.PROTOCOL=Du,Re.PROTOCOL_VERSION=P0,Re.REQUEST_CONTEXT=U0,Re.WalletKit=e$,Re.default=fu,Object.defineProperty(Re,"__esModule",{value:!0})});
42
42
  //# sourceMappingURL=index.umd.js.map