@reown/walletkit 1.2.10 → 1.2.11-canary-a-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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(Ve,Xt){typeof exports=="object"&&typeof module<"u"?Xt(exports):typeof define=="function"&&define.amd?define(["exports"],Xt):(Ve=typeof globalThis<"u"?globalThis:Ve||self,Xt(Ve["@reown/walletkit"]={}))})(this,function(Ve){"use strict";var Xt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Vl(t){var e=t.default;if(typeof e=="function"){var n=function(){return e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var Ke={exports:{}},Yr=typeof Reflect=="object"?Reflect:null,Kl=Yr&&typeof Yr.apply=="function"?Yr.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},Ls;Yr&&typeof Yr.ownKeys=="function"?Ls=Yr.ownKeys:Object.getOwnPropertySymbols?Ls=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Ls=function(e){return Object.getOwnPropertyNames(e)};function zy(t){console&&console.warn&&console.warn(t)}var Gl=Number.isNaN||function(e){return e!==e};function de(){de.init.call(this)}Ke.exports=de,Ke.exports.once=Gy,de.EventEmitter=de,de.prototype._events=void 0,de.prototype._eventsCount=0,de.prototype._maxListeners=void 0;var Wl=10;function ks(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(de,"defaultMaxListeners",{enumerable:!0,get:function(){return Wl},set:function(t){if(typeof t!="number"||t<0||Gl(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Wl=t}}),de.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},de.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Gl(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 Zl(t){return t._maxListeners===void 0?de.defaultMaxListeners:t._maxListeners}de.prototype.getMaxListeners=function(){return Zl(this)},de.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);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(n.length>0&&(o=n[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")Kl(c,this,n);else for(var u=c.length,l=ef(c,u),r=0;r<u;++r)Kl(l[r],this,n);return!0};function Yl(t,e,n,r){var i,s,o;if(ks(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),o=s[e]),o===void 0)o=s[e]=n,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=Zl(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,zy(a)}return t}de.prototype.addListener=function(e,n){return Yl(this,e,n,!1)},de.prototype.on=de.prototype.addListener,de.prototype.prependListener=function(e,n){return Yl(this,e,n,!0)};function Hy(){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 Xl(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=Hy.bind(r);return i.listener=n,r.wrapFn=i,i}de.prototype.once=function(e,n){return ks(n),this.on(e,Xl(this,e,n)),this},de.prototype.prependOnceListener=function(e,n){return ks(n),this.prependListener(e,Xl(this,e,n)),this},de.prototype.removeListener=function(e,n){var r,i,s,o,a;if(ks(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(s=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,s=o;break}if(s<0)return this;s===0?r.shift():Vy(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},de.prototype.off=de.prototype.removeListener,de.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var s=Object.keys(r),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(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Jl(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?Ky(i):ef(i,i.length)}de.prototype.listeners=function(e){return Jl(this,e,!0)},de.prototype.rawListeners=function(e){return Jl(this,e,!1)},de.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Ql.call(t,e)},de.prototype.listenerCount=Ql;function Ql(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}de.prototype.eventNames=function(){return this._eventsCount>0?Ls(this._events):[]};function ef(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function Vy(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Ky(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function Gy(t,e){return new Promise(function(n,r){function i(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}tf(t,e,s,{once:!0}),e!=="error"&&Wy(t,i,{once:!0})})}function Wy(t,e,n){typeof t.on=="function"&&tf(t,"error",e,n)}function tf(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const nf="wc",Zy=2,Oa="WalletKit",Yy=`${nf}@2:${Oa}:`,Xy={database:":memory:"},Jy="request";var K={};/*! *****************************************************************************
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,20 @@
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 Da=function(t,e){return Da=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Da(t,e)};function Qy(t,e){Da(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var $a=function(){return $a=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},$a.apply(this,arguments)};function eb(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function tb(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function nb(t,e){return function(n,r){e(n,r,t)}}function rb(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ib(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function sb(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,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(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=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 n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function ob(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function ab(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Pa(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function rf(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function cb(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(rf(arguments[e]));return t}function ub(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Ti(t){return this instanceof Ti?(this.v=t,this):new Ti(t)}function lb(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){r[d]&&(i[d]=function(h){return new Promise(function(p,b){s.push([d,h,p,b])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ti?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function fb(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Ti(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function hb(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Pa=="function"?Pa(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[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 db(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function pb(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function gb(t){return t&&t.__esModule?t:{default:t}}function yb(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function bb(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var wb=Object.freeze({__proto__:null,__extends:Qy,get __assign(){return $a},__rest:eb,__decorate:tb,__param:nb,__metadata:rb,__awaiter:ib,__generator:sb,__createBinding:ob,__exportStar:ab,__values:Pa,__read:rf,__spread:cb,__spreadArrays:ub,__await:Ti,__asyncGenerator:lb,__asyncDelegator:fb,__asyncValues:hb,__makeTemplateObject:db,__importStar:pb,__importDefault:gb,__classPrivateFieldGet:yb,__classPrivateFieldSet:bb}),qs=Vl(wb),Ta={},Ri={},sf;function mb(){if(sf)return Ri;sf=1,Object.defineProperty(Ri,"__esModule",{value:!0}),Ri.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return Ri.delay=t,Ri}var vr={},Ra={},Er={},of;function vb(){return of||(of=1,Object.defineProperty(Er,"__esModule",{value:!0}),Er.ONE_THOUSAND=Er.ONE_HUNDRED=void 0,Er.ONE_HUNDRED=100,Er.ONE_THOUSAND=1e3),Er}var Na={},af;function Eb(){return af||(af=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}(Na)),Na}var cf;function uf(){return cf||(cf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=qs;e.__exportStar(vb(),t),e.__exportStar(Eb(),t)}(Ra)),Ra}var lf;function xb(){if(lf)return vr;lf=1,Object.defineProperty(vr,"__esModule",{value:!0}),vr.fromMiliseconds=vr.toMiliseconds=void 0;const t=uf();function e(r){return r*t.ONE_THOUSAND}vr.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return vr.fromMiliseconds=n,vr}var ff;function _b(){return ff||(ff=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=qs;e.__exportStar(mb(),t),e.__exportStar(xb(),t)}(Ta)),Ta}var Xr={},hf;function Sb(){if(hf)return Xr;hf=1,Object.defineProperty(Xr,"__esModule",{value:!0}),Xr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const i=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:i})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return Xr.Watch=t,Xr.default=t,Xr}var Ca={},Ni={},df;function Ib(){if(df)return Ni;df=1,Object.defineProperty(Ni,"__esModule",{value:!0}),Ni.IWatch=void 0;class t{}return Ni.IWatch=t,Ni}var pf;function Ab(){return pf||(pf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),qs.__exportStar(Ib(),t)}(Ca)),Ca}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=qs;e.__exportStar(_b(),t),e.__exportStar(Sb(),t),e.__exportStar(Ab(),t),e.__exportStar(uf(),t)})(K);class xr{}class Bb extends xr{constructor(e){super()}}const gf=K.FIVE_SECONDS,_r={pulse:"heartbeat_pulse"};class Ua extends Bb{constructor(e){super(e),this.events=new Ke.exports.EventEmitter,this.interval=gf,this.interval=e?.interval||gf}static async init(e){const n=new Ua(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),K.toMiliseconds(this.interval))}pulse(){this.events.emit(_r.pulse)}}const Ob=/"(?:_|\\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*:/,Db=/"(?: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*:/,$b=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Pb(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Tb(t);return}return e}function Tb(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Ms(t,e={}){if(typeof t!="string")return t;const n=t.trim();if(t[0]==='"'&&t.endsWith('"')&&!t.includes("\\"))return n.slice(1,-1);if(n.length<=9){const r=n.toLowerCase();if(r==="true")return!0;if(r==="false")return!1;if(r==="undefined")return;if(r==="null")return null;if(r==="nan")return Number.NaN;if(r==="infinity")return Number.POSITIVE_INFINITY;if(r==="-infinity")return Number.NEGATIVE_INFINITY}if(!$b.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Ob.test(t)||Db.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Pb)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Rb(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Te(t,...e){try{return Rb(t(...e))}catch(n){return Promise.reject(n)}}function Nb(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Cb(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function js(t){if(Nb(t))return String(t);if(Cb(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return js(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function yf(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const Fa="base64:";function Ub(t){if(typeof t=="string")return t;yf();const e=Buffer.from(t).toString("base64");return Fa+e}function Fb(t){return typeof t!="string"||!t.startsWith(Fa)?t:(yf(),Buffer.from(t.slice(Fa.length),"base64"))}function ft(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Lb(...t){return ft(t.join(":"))}function zs(t){return t=ft(t),t?t+":":""}function qD(t){return t}const kb="memory",qb=()=>{const t=new Map;return{name:kb,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,n){t.set(e,n)},setItemRaw(e,n){t.set(e,n)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Mb(t={}){const e={mounts:{"":t.driver||qb()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=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[""]}},r=(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=ft(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 bf(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 d=new Map,h=p=>{let b=d.get(p.base);return b||(b={driver:p.driver,base:p.base,items:[]},d.set(p.base,b)),b};for(const p of u){const b=typeof p=="string",v=ft(b?p:p.key),B=b?void 0:p.value,D=b||!p.options?l:{...l,...p.options},_=n(v);h(_).items.push({key:v,value:B,relativeKey:_.relativeKey,options:D})}return Promise.all([...d.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=ft(u);const{relativeKey:f,driver:d}=n(u);return Te(d.hasItem,f,l)},getItem(u,l={}){u=ft(u);const{relativeKey:f,driver:d}=n(u);return Te(d.getItem,f,l).then(h=>Ms(h))},getItems(u,l){return a(u,l,f=>f.driver.getItems?Te(f.driver.getItems,f.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(h=>({key:Lb(f.base,h.key),value:Ms(h.value)}))):Promise.all(f.items.map(d=>Te(f.driver.getItem,d.relativeKey,d.options).then(h=>({key:d.key,value:Ms(h)})))))},getItemRaw(u,l={}){u=ft(u);const{relativeKey:f,driver:d}=n(u);return d.getItemRaw?Te(d.getItemRaw,f,l):Te(d.getItem,f,l).then(h=>Fb(h))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=ft(u);const{relativeKey:d,driver:h}=n(u);h.setItem&&(await Te(h.setItem,d,js(l),f),h.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return Te(f.driver.setItems,f.items.map(d=>({key:d.relativeKey,value:js(d.value),options:d.options})),l);f.driver.setItem&&await Promise.all(f.items.map(d=>Te(f.driver.setItem,d.relativeKey,js(d.value),d.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=ft(u);const{relativeKey:d,driver:h}=n(u);if(h.setItemRaw)await Te(h.setItemRaw,d,l,f);else if(h.setItem)await Te(h.setItem,d,Ub(l),f);else return;h.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=ft(u);const{relativeKey:f,driver:d}=n(u);d.removeItem&&(await Te(d.removeItem,f,l),(l.removeMeta||l.removeMata)&&await Te(d.removeItem,f+"$",l),d.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=ft(u);const{relativeKey:f,driver:d}=n(u),h=Object.create(null);if(d.getMeta&&Object.assign(h,await Te(d.getMeta,f,l)),!l.nativeOnly){const p=await Te(d.getItem,f+"$",l).then(b=>Ms(b));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(h,p))}return h},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=zs(u);const f=r(u,!0);let d=[];const h=[];for(const p of f){const b=await Te(p.driver.getKeys,p.relativeBase,l);for(const v of b){const B=p.mountpoint+ft(v);d.some(D=>B.startsWith(D))||h.push(B)}d=[p.mountpoint,...d.filter(v=>!v.startsWith(p.mountpoint))]}return u?h.filter(p=>p.startsWith(u)&&p[p.length-1]!=="$"):h.filter(p=>p[p.length-1]!=="$")},async clear(u,l={}){u=zs(u),await Promise.all(r(u,!1).map(async f=>{if(f.driver.clear)return Te(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const d=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(d.map(h=>f.driver.removeItem(h,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>wf(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=zs(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,d)=>d.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(bf(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=zs(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),l&&await wf(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=ft(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=ft(u),r(u,l.parents).map(d=>({driver:d.driver,base:d.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 bf(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function wf(t){typeof t.dispose=="function"&&await Te(t.dispose)}function Sr(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function mf(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Sr(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let La;function Ci(){return La||(La=mf("keyval-store","keyval")),La}function vf(t,e=Ci()){return e("readonly",n=>Sr(n.get(t)))}function jb(t,e,n=Ci()){return n("readwrite",r=>(r.put(e,t),Sr(r.transaction)))}function zb(t,e=Ci()){return e("readwrite",n=>(n.delete(t),Sr(n.transaction)))}function Hb(t=Ci()){return t("readwrite",e=>(e.clear(),Sr(e.transaction)))}function Vb(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Sr(t.transaction)}function Kb(t=Ci()){return t("readonly",e=>{if(e.getAllKeys)return Sr(e.getAllKeys());const n=[];return Vb(e,r=>n.push(r.key)).then(()=>n)})}const Gb=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),Wb=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,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function Jr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Wb(t)}catch{return t}}function Ir(t){return typeof t=="string"?t:Gb(t)||""}const Zb="idb-keyval";var Yb=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=mf(t.dbName,t.storeName)),{name:Zb,options:t,async hasItem(i){return!(typeof await vf(n(i),r)>"u")},async getItem(i){return await vf(n(i),r)??null},setItem(i,s){return jb(n(i),s,r)},removeItem(i){return zb(n(i),r)},getKeys(){return Kb(r)},clear(){return Hb(r)}}};const Xb="WALLET_CONNECT_V2_INDEXED_DB",Jb="keyvaluestorage";class Qb{constructor(){this.indexedDb=Mb({driver:Yb({dbName:Xb,storeName:Jb})})}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 n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Ir(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var ka=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Hs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ka<"u"&&ka.localStorage?Hs.exports=ka.localStorage:typeof window<"u"&&window.localStorage?Hs.exports=window.localStorage:Hs.exports=new e})();function ew(t){var e;return[t[0],Jr((e=t[1])!=null?e:"")]}class tw{constructor(){this.localStorage=Hs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(ew)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return Jr(n)}async setItem(e,n){this.localStorage.setItem(e,Ir(n))}async removeItem(e){this.localStorage.removeItem(e)}}const nw="wc_storage_version",Ef=1,rw=async(t,e,n)=>{const r=nw,i=await e.getItem(r);if(i&&i>=Ef){n(e);return}const s=await t.getKeys();if(!s.length){n(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(r,Ef),n(e),iw(t,o)},iw=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class sw{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new tw;this.storage=e;try{const n=new Qb;rw(e,n,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,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}function ow(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var aw=cw;function cw(t,e,n){var r=n&&n.stringify||ow,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]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,f=-1,d=t&&t.length||0,h=0;h<d;){if(t.charCodeAt(h)===37&&h+1<d){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Number(e[l]),f=h+2,h++;break;case 105:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Math.floor(Number(e[l])),f=h+2,h++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<h&&(u+=t.slice(f,h));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=h+2,h++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=h+2,h++;break}u+=r(e[l]),f=h+2,h++;break;case 115:if(l>=c)break;f<h&&(u+=t.slice(f,h)),u+=String(e[l]),f=h+2,h++;break;case 37:f<h&&(u+=t.slice(f,h)),u+="%",f=h+2,h++,l--;break}++l}++h}return f===-1?t:(f<d&&(u+=t.slice(f)),u)}const xf=aw;var hn=Jt;const Ui=ww().console||{},uw={mapHttpRequest:Ks,mapHttpResponse:Ks,wrapRequestSerializer:Ma,wrapResponseSerializer:Ma,wrapErrorSerializer:Ma,req:Ks,res:Ks,err:pw};function lw(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Jt(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 n=t.browser.write||Ui;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=lw(t.browser.serialize,r);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 n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=Fi),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:f,set:d});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:gw(t)};c.levels=Jt.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=Fi,c.serializers=r,c._serialize=i,c._stdErrSerialize=s,c.child=h,e&&(c._logEvent=qa());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function f(){return this._level}function d(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,Qr(u,c,"error","log"),Qr(u,c,"fatal","error"),Qr(u,c,"warn","error"),Qr(u,c,"info","log"),Qr(u,c,"debug","log"),Qr(u,c,"trace","log")}function h(p,b){if(!p)throw new Error("missing bindings for child Pino");b=b||{},i&&p.serializers&&(b.serializers=p.serializers);const v=b.serializers;if(i&&v){var B=Object.assign({},r,v),D=t.browser.serialize===!0?Object.keys(B):i;delete p.serializers,Vs([p],D,B,this._stdErrSerialize)}function _(x){this._childLevel=(x._childLevel|0)+1,this.error=ei(x,p,"error"),this.fatal=ei(x,p,"fatal"),this.warn=ei(x,p,"warn"),this.info=ei(x,p,"info"),this.debug=ei(x,p,"debug"),this.trace=ei(x,p,"trace"),B&&(this.serializers=B,this._serialize=D),e&&(this._logEvent=qa([].concat(x._logEvent.bindings,p)))}return _.prototype=this,new _(this)}return c}Jt.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"}},Jt.stdSerializers=uw,Jt.stdTimeFunctions=Object.assign({},{nullTime:_f,epochTime:Sf,unixTime:yw,isoTime:bw});function Qr(t,e,n,r){const i=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?Fi:i[n]?i[n]:Ui[n]||Ui[r]||Fi,fw(t,e,n)}function fw(t,e,n){!t.transmit&&e[n]===Fi||(e[n]=function(r){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Ui?Ui:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&Vs(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,hw(this,n,o,s)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Jt.levels.values[u],f=Jt.levels.values[n];if(f<l)return;dw(this,{ts:s,methodLevel:n,methodValue:f,transmitLevel:u,transmitValue:Jt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[n]))}function hw(t,e,n,r){t._serialize&&Vs(n,t._serialize,t.serializers,t._stdErrSerialize);const i=n.slice();let s=i[0];const o={};r&&(o.time=r),o.level=Jt.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?xf(i.shift(),i):void 0}else typeof s=="string"&&(s=xf(i.shift(),i));return s!==void 0&&(o.msg=s),o}function Vs(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=Jt.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 n&&(t[i][s]=n[s](t[i][s]))}function ei(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var i=1;i<r.length;i++)r[i]=arguments[i-1];return t[n].apply(this,r)}}function dw(t,e,n){const r=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;Vs(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=n.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,r(s,t._logEvent,a),t._logEvent=qa(c)}function qa(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function pw(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function gw(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?_f:Sf}function Ks(){return{}}function Ma(t){return t}function Fi(){}function _f(){return!1}function Sf(){return Date.now()}function yw(){return Math.round(Date.now()/1e3)}function bw(){return new Date(Date.now()).toISOString()}function ww(){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 mw={level:"info"},Li="custom_context",ja=1e3*1024;class vw{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 If{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new vw(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.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 n=this.head;for(;n!==null;)e.push(n.value),n=n.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 n=e.value;return e=e.next,{done:!1,value:n}}}}}class Af{constructor(e,n=ja){this.level=e??"error",this.levelValue=hn.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new If(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===hn.levels.values.error?console.error(e):n===hn.levels.values.warn?console.warn(e):n===hn.levels.values.debug?console.debug(e):n===hn.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ir({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new If(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Ir({extraMetadata:e})),new Blob(n,{type:"application/json"})}}class Ew{constructor(e,n=ja){this.baseChunkLogger=new Af(e,n)}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 n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}class xw{constructor(e,n=ja){this.baseChunkLogger=new Af(e,n)}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 _w=Object.defineProperty,Sw=Object.defineProperties,Iw=Object.getOwnPropertyDescriptors,Bf=Object.getOwnPropertySymbols,Aw=Object.prototype.hasOwnProperty,Bw=Object.prototype.propertyIsEnumerable,Of=(t,e,n)=>e in t?_w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gs=(t,e)=>{for(var n in e||(e={}))Aw.call(e,n)&&Of(t,n,e[n]);if(Bf)for(var n of Bf(e))Bw.call(e,n)&&Of(t,n,e[n]);return t},Ws=(t,e)=>Sw(t,Iw(e));function za(t){return Ws(Gs({},t),{level:t?.level||mw.level})}function Ow(t,e=Li){return t[e]||""}function Dw(t,e,n=Li){return t[n]=e,t}function ht(t,e=Li){let n="";return typeof t.bindings>"u"?n=Ow(t,e):n=t.bindings().context||"",n}function $w(t,e,n=Li){const r=ht(t,n);return r.trim()?`${r}/${e}`:e}function rt(t,e,n=Li){const r=$w(t,e,n),i=t.child({context:r});return Dw(i,r,n)}function Pw(t){var e,n;const r=new Ew((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:hn(Ws(Gs({},t.opts),{level:"trace",browser:Ws(Gs({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Tw(t){var e;const n=new xw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:hn(Ws(Gs({},t.opts),{level:"trace"})),chunkLoggerController:n}}function Rw(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Pw(t):Tw(t)}var Nw=Object.defineProperty,Cw=(t,e,n)=>e in t?Nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Df=(t,e,n)=>Cw(t,typeof e!="symbol"?e+"":e,n);class Uw extends xr{constructor(e){super(),this.opts=e,Df(this,"protocol","wc"),Df(this,"version",2)}}var Fw=Object.defineProperty,Lw=(t,e,n)=>e in t?Fw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kw=(t,e,n)=>Lw(t,typeof e!="symbol"?e+"":e,n);class qw extends xr{constructor(e,n){super(),this.core=e,this.logger=n,kw(this,"records",new Map)}}class Mw{constructor(e,n){this.logger=e,this.core=n}}class jw extends xr{constructor(e,n){super(),this.relayer=e,this.logger=n}}class zw extends xr{constructor(e){super()}}class Hw{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class Vw extends xr{constructor(e,n){super(),this.relayer=e,this.logger=n}}class Kw extends xr{constructor(e,n){super(),this.core=e,this.logger=n}}class Gw{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class Ww{constructor(e,n){this.projectId=e,this.logger=n}}class Zw{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var Yw=Object.defineProperty,Xw=(t,e,n)=>e in t?Yw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$f=(t,e,n)=>Xw(t,typeof e!="symbol"?e+"":e,n);class Jw{constructor(e){this.opts=e,$f(this,"protocol","wc"),$f(this,"version",2)}}class Qw{constructor(e){this.client=e}}function em(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Pf(t,...e){if(!em(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 Tf(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 tm(t,e){Pf(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const ti=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ha=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function nm(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Rf(t){return typeof t=="string"&&(t=nm(t)),Pf(t),t}class rm{clone(){return this._cloneInto()}}function im(t){const e=r=>t().update(Rf(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Nf(t=32){if(ti&&typeof ti.getRandomValues=="function")return ti.getRandomValues(new Uint8Array(t));if(ti&&typeof ti.randomBytes=="function")return ti.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function sm(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}class om extends rm{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Ha(this.buffer)}update(e){Tf(this);const{view:n,buffer:r,blockLen:i}=this;e=Rf(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=Ha(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Tf(this),tm(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;sm(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Ha(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const Zs=BigInt(2**32-1),Va=BigInt(32);function Cf(t,e=!1){return e?{h:Number(t&Zs),l:Number(t>>Va&Zs)}:{h:Number(t>>Va&Zs)|0,l:Number(t&Zs)|0}}function am(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=Cf(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const cm=(t,e)=>BigInt(t>>>0)<<Va|BigInt(e>>>0),um=(t,e,n)=>t>>>n,lm=(t,e,n)=>t<<32-n|e>>>n,fm=(t,e,n)=>t>>>n|e<<32-n,hm=(t,e,n)=>t<<32-n|e>>>n,dm=(t,e,n)=>t<<64-n|e>>>n-32,pm=(t,e,n)=>t>>>n-32|e<<64-n,gm=(t,e)=>e,ym=(t,e)=>t,bm=(t,e,n)=>t<<n|e>>>32-n,wm=(t,e,n)=>e<<n|t>>>32-n,mm=(t,e,n)=>e<<n-32|t>>>64-n,vm=(t,e,n)=>t<<n-32|e>>>64-n;function Em(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const xm=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),_m=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Sm=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Im=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Am=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Bm=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,ne={fromBig:Cf,split:am,toBig:cm,shrSH:um,shrSL:lm,rotrSH:fm,rotrSL:hm,rotrBH:dm,rotrBL:pm,rotr32H:gm,rotr32L:ym,rotlSH:bm,rotlSL:wm,rotlBH:mm,rotlBL:vm,add:Em,add3L:xm,add3H:_m,add4L:Sm,add4H:Im,add5H:Bm,add5L:Am},[Om,Dm]=(()=>ne.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))))(),Ln=new Uint32Array(80),kn=new Uint32Array(80);class $m extends om{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:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:b,Hl:v}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v){this.Ah=e|0,this.Al=n|0,this.Bh=r|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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=b|0,this.Hl=v|0}process(e,n){for(let _=0;_<16;_++,n+=4)Ln[_]=e.getUint32(n),kn[_]=e.getUint32(n+=4);for(let _=16;_<80;_++){const x=Ln[_-15]|0,P=kn[_-15]|0,R=ne.rotrSH(x,P,1)^ne.rotrSH(x,P,8)^ne.shrSH(x,P,7),N=ne.rotrSL(x,P,1)^ne.rotrSL(x,P,8)^ne.shrSL(x,P,7),F=Ln[_-2]|0,$=kn[_-2]|0,z=ne.rotrSH(F,$,19)^ne.rotrBH(F,$,61)^ne.shrSH(F,$,6),M=ne.rotrSL(F,$,19)^ne.rotrBL(F,$,61)^ne.shrSL(F,$,6),E=ne.add4L(N,M,kn[_-7],kn[_-16]),y=ne.add4H(E,R,z,Ln[_-7],Ln[_-16]);Ln[_]=y|0,kn[_]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:b,Gl:v,Hh:B,Hl:D}=this;for(let _=0;_<80;_++){const x=ne.rotrSH(f,d,14)^ne.rotrSH(f,d,18)^ne.rotrBH(f,d,41),P=ne.rotrSL(f,d,14)^ne.rotrSL(f,d,18)^ne.rotrBL(f,d,41),R=f&h^~f&b,N=d&p^~d&v,F=ne.add5L(D,P,N,Dm[_],kn[_]),$=ne.add5H(F,B,x,R,Om[_],Ln[_]),z=F|0,M=ne.rotrSH(r,i,28)^ne.rotrBH(r,i,34)^ne.rotrBH(r,i,39),E=ne.rotrSL(r,i,28)^ne.rotrBL(r,i,34)^ne.rotrBL(r,i,39),y=r&s^r&a^s&a,m=i&o^i&c^o&c;B=b|0,D=v|0,b=h|0,v=p|0,h=f|0,p=d|0,{h:f,l:d}=ne.add(u|0,l|0,$|0,z|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const g=ne.add3L(z,E,m);r=ne.add3H(g,$,M,y),i=g|0}({h:r,l:i}=ne.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ne.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ne.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ne.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ne.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ne.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:b,l:v}=ne.add(this.Gh|0,this.Gl|0,b|0,v|0),{h:B,l:D}=ne.add(this.Hh|0,this.Hl|0,B|0,D|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,b,v,B,D)}roundClean(){Ln.fill(0),kn.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 Pm=im(()=>new $m);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ka=BigInt(0),Uf=BigInt(1),Tm=BigInt(2);function Ga(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wa(t){if(!Ga(t))throw new Error("Uint8Array expected")}function Za(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Rm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ya(t){Wa(t);let e="";for(let n=0;n<t.length;n++)e+=Rm[t[n]];return e}function Ff(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ka:BigInt("0x"+t)}const dn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Lf(t){if(t>=dn._0&&t<=dn._9)return t-dn._0;if(t>=dn.A&&t<=dn.F)return t-(dn.A-10);if(t>=dn.a&&t<=dn.f)return t-(dn.a-10)}function kf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Lf(t.charCodeAt(s)),a=Lf(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)}r[i]=o*16+a}return r}function Nm(t){return Ff(Ya(t))}function Ys(t){return Wa(t),Ff(Ya(Uint8Array.from(t).reverse()))}function qf(t,e){return kf(t.toString(16).padStart(e*2,"0"))}function Xa(t,e){return qf(t,e).reverse()}function pn(t,e,n){let r;if(typeof e=="string")try{r=kf(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Ga(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function Mf(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Wa(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const Ja=t=>typeof t=="bigint"&&Ka<=t;function Cm(t,e,n){return Ja(t)&&Ja(e)&&Ja(n)&&e<=t&&t<n}function ki(t,e,n,r){if(!Cm(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Um(t){let e;for(e=0;t>Ka;t>>=Uf,e+=1);return e}const Fm=t=>(Tm<<BigInt(t-1))-Uf,Lm={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"||Ga(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 Qa(t,e,n={}){const r=(i,s,o)=>{const a=Lm[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))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function jf(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Re=BigInt(0),xe=BigInt(1),Ar=BigInt(2),km=BigInt(3),ec=BigInt(4),zf=BigInt(5),Hf=BigInt(8);function Be(t,e){const n=t%e;return n>=Re?n:e+n}function qm(t,e,n){if(e<Re)throw new Error("invalid exponent, negatives unsupported");if(n<=Re)throw new Error("invalid modulus");if(n===xe)return Re;let r=xe;for(;e>Re;)e&xe&&(r=r*t%n),t=t*t%n,e>>=xe;return r}function Qt(t,e,n){let r=t;for(;e-- >Re;)r*=r,r%=n;return r}function Vf(t,e){if(t===Re)throw new Error("invert: expected non-zero number");if(e<=Re)throw new Error("invert: expected positive modulus, got "+e);let n=Be(t,e),r=e,i=Re,s=xe;for(;n!==Re;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==xe)throw new Error("invert: does not exist");return Be(i,e)}function Mm(t){const e=(t-xe)/Ar;let n,r,i;for(n=t-xe,r=0;n%Ar===Re;n/=Ar,r++);for(i=Ar;i<t&&qm(i,e,t)!==t-xe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+xe)/ec;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=(n+xe)/Ar;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,i),n),l=o.pow(a,s),f=o.pow(a,n);for(;!o.eql(f,o.ONE);){if(o.eql(f,o.ZERO))return o.ZERO;let d=1;for(let p=o.sqr(f);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const h=o.pow(u,xe<<BigInt(c-d-1));u=o.sqr(h),l=o.mul(l,h),f=o.mul(f,u),c=d}return l}}function jm(t){if(t%ec===km){const e=(t+xe)/ec;return function(n,r){const i=n.pow(r,e);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%Hf===zf){const e=(t-zf)/Hf;return function(n,r){const i=n.mul(r,Ar),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Ar),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return Mm(t)}const zm=(t,e)=>(Be(t,e)&xe)===xe,Hm=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Hm.reduce((r,i)=>(r[i]="function",r),e);return Qa(t,n)}function Km(t,e,n){if(n<Re)throw new Error("invalid exponent, negatives unsupported");if(n===Re)return t.ONE;if(n===xe)return e;let r=t.ONE,i=e;for(;n>Re;)n&xe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=xe;return r}function Gm(t,e){const n=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(n[a]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(n[a]=t.mul(s,n[a]),t.mul(s,o)),i),n}function Kf(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Gf(t,e,n=!1,r={}){if(t<=Re)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Kf(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:Fm(i),ZERO:Re,ONE:xe,create:c=>Be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Re<=c&&c<t},is0:c=>c===Re,isOdd:c=>(c&xe)===xe,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)=>Km(a,c,u),div:(c,u)=>Be(c*Vf(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Vf(c,t),sqrt:r.sqrt||(c=>(o||(o=jm(t)),o(a,c))),invertBatch:c=>Gm(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?Xa(c,s):qf(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?Ys(c):Nm(c)}});return Object.freeze(a)}const Wf=BigInt(0),Xs=BigInt(1);function tc(t,e){const n=e.negate();return t?n:e}function Zf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function nc(t,e){Zf(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function Wm(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function Zm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const rc=new WeakMap,Yf=new WeakMap;function ic(t){return Yf.get(t)||1}function Ym(t,e){return{constTimeNegate:tc,hasPrecomputes(n){return ic(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Wf;)r&Xs&&(i=i.add(s)),s=s.double(),r>>=Xs;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=nc(r,e),o=[];let a=n,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(n,r,i){const{windows:s,windowSize:o}=nc(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let d=0;d<s;d++){const h=d*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=Xs);const b=h,v=h+Math.abs(p)-1,B=d%2!==0,D=p<0;p===0?c=c.add(tc(B,r[b])):a=a.add(tc(D,r[v]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=nc(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let f=0;f<o;f++){const d=f*a;if(i===Wf)break;let h=Number(i&c);if(i>>=l,h>a&&(h-=u,i+=Xs),h===0)continue;let p=r[d+Math.abs(h)-1];h<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=rc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&rc.set(r,i(s))),s},wNAFCached(n,r,i){const s=ic(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=ic(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Zf(r,e),Yf.set(n,r),rc.delete(n)}}}function Xm(t,e,n,r){if(Wm(n,t),Zm(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Um(BigInt(n.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 h=0;h<r.length;h++){const p=r[h],b=Number(p>>BigInt(f)&BigInt(a));c[b]=c[b].add(n[h])}let d=i;for(let h=c.length-1,p=i;h>0;h--)p=p.add(c[h]),d=d.add(p);if(l=l.add(d),f!==0)for(let h=0;h<o;h++)l=l.double()}return l}function Jm(t){return Vm(t.Fp),Qa(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Kf(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const jt=BigInt(0),dt=BigInt(1),Js=BigInt(2),Qm=BigInt(8),e2={zip215:!0};function t2(t){const e=Jm(t);return Qa(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function n2(t){const e=t2(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=Js<<BigInt(a*8)-dt,l=n.create,f=Gf(e.n,e.nBitLength),d=e.uvRatio||((g,w)=>{try{return{isValid:!0,value:n.sqrt(g*n.inv(w))}}catch{return{isValid:!1,value:jt}}}),h=e.adjustScalarBytes||(g=>g),p=e.domain||((g,w,S)=>{if(Za("phflag",S),w.length||S)throw new Error("Contexts/pre-hash are not supported");return g});function b(g,w){ki("coordinate "+g,w,jt,u)}function v(g){if(!(g instanceof _))throw new Error("ExtendedPoint expected")}const B=jf((g,w)=>{const{ex:S,ey:A,ez:I}=g,O=g.is0();w==null&&(w=O?Qm:n.inv(I));const T=l(S*w),L=l(A*w),U=l(I*w);if(O)return{x:jt,y:dt};if(U!==dt)throw new Error("invZ was invalid");return{x:T,y:L}}),D=jf(g=>{const{a:w,d:S}=e;if(g.is0())throw new Error("bad point: ZERO");const{ex:A,ey:I,ez:O,et:T}=g,L=l(A*A),U=l(I*I),k=l(O*O),C=l(k*k),q=l(L*w),j=l(k*l(q+U)),W=l(C+l(S*l(L*U)));if(j!==W)throw new Error("bad point: equation left != right (1)");const V=l(A*I),Z=l(O*T);if(V!==Z)throw new Error("bad point: equation left != right (2)");return!0});class _{constructor(w,S,A,I){this.ex=w,this.ey=S,this.ez=A,this.et=I,b("x",w),b("y",S),b("z",A),b("t",I),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof _)throw new Error("extended point not allowed");const{x:S,y:A}=w||{};return b("x",S),b("y",A),new _(S,A,dt,l(S*A))}static normalizeZ(w){const S=n.invertBatch(w.map(A=>A.ez));return w.map((A,I)=>A.toAffine(S[I])).map(_.fromAffine)}static msm(w,S){return Xm(_,f,w,S)}_setWindowSize(w){R.setWindowSize(this,w)}assertValidity(){D(this)}equals(w){v(w);const{ex:S,ey:A,ez:I}=this,{ex:O,ey:T,ez:L}=w,U=l(S*L),k=l(O*I),C=l(A*L),q=l(T*I);return U===k&&C===q}is0(){return this.equals(_.ZERO)}negate(){return new _(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:S,ey:A,ez:I}=this,O=l(S*S),T=l(A*A),L=l(Js*l(I*I)),U=l(w*O),k=S+A,C=l(l(k*k)-O-T),q=U+T,j=q-L,W=U-T,V=l(C*j),Z=l(q*W),Q=l(C*W),ee=l(j*q);return new _(V,Z,ee,Q)}add(w){v(w);const{a:S,d:A}=e,{ex:I,ey:O,ez:T,et:L}=this,{ex:U,ey:k,ez:C,et:q}=w;if(S===BigInt(-1)){const Uy=l((O-I)*(k+U)),Fy=l((O+I)*(k-U)),Hl=l(Fy-Uy);if(Hl===jt)return this.double();const Ly=l(T*Js*q),ky=l(L*Js*C),qy=ky+Ly,My=Fy+Uy,jy=ky-Ly,UD=l(qy*Hl),FD=l(My*jy),LD=l(qy*jy),kD=l(Hl*My);return new _(UD,FD,kD,LD)}const j=l(I*U),W=l(O*k),V=l(L*A*q),Z=l(T*C),Q=l((I+O)*(U+k)-j-W),ee=Z-V,ie=Z+V,he=l(W-S*j),ve=l(Q*ee),Fn=l(ie*he),Ba=l(Q*he),CD=l(ee*ie);return new _(ve,Fn,CD,Ba)}subtract(w){return this.add(w.negate())}wNAF(w){return R.wNAFCached(this,w,_.normalizeZ)}multiply(w){const S=w;ki("scalar",S,dt,r);const{p:A,f:I}=this.wNAF(S);return _.normalizeZ([A,I])[0]}multiplyUnsafe(w,S=_.ZERO){const A=w;return ki("scalar",A,jt,r),A===jt?P:this.is0()||A===dt?this:R.wNAFCachedUnsafe(this,A,_.normalizeZ,S)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return R.unsafeLadder(this,r).is0()}toAffine(w){return B(this,w)}clearCofactor(){const{h:w}=e;return w===dt?this:this.multiplyUnsafe(w)}static fromHex(w,S=!1){const{d:A,a:I}=e,O=n.BYTES;w=pn("pointHex",w,O),Za("zip215",S);const T=w.slice(),L=w[O-1];T[O-1]=L&-129;const U=Ys(T),k=S?u:n.ORDER;ki("pointHex.y",U,jt,k);const C=l(U*U),q=l(C-dt),j=l(A*C-I);let{isValid:W,value:V}=d(q,j);if(!W)throw new Error("Point.fromHex: invalid y coordinate");const Z=(V&dt)===dt,Q=(L&128)!==0;if(!S&&V===jt&&Q)throw new Error("Point.fromHex: x=0 and x_0=1");return Q!==Z&&(V=l(-V)),_.fromAffine({x:V,y:U})}static fromPrivateKey(w){return $(w).point}toRawBytes(){const{x:w,y:S}=this.toAffine(),A=Xa(S,n.BYTES);return A[A.length-1]|=w&dt?128:0,A}toHex(){return Ya(this.toRawBytes())}}_.BASE=new _(e.Gx,e.Gy,dt,l(e.Gx*e.Gy)),_.ZERO=new _(jt,dt,dt,jt);const{BASE:x,ZERO:P}=_,R=Ym(_,a*8);function N(g){return Be(g,r)}function F(g){return N(Ys(g))}function $(g){const w=n.BYTES;g=pn("private key",g,w);const S=pn("hashed private key",s(g),2*w),A=h(S.slice(0,w)),I=S.slice(w,2*w),O=F(A),T=x.multiply(O),L=T.toRawBytes();return{head:A,prefix:I,scalar:O,point:T,pointBytes:L}}function z(g){return $(g).pointBytes}function M(g=new Uint8Array,...w){const S=Mf(...w);return F(s(p(S,pn("context",g),!!i)))}function E(g,w,S={}){g=pn("message",g),i&&(g=i(g));const{prefix:A,scalar:I,pointBytes:O}=$(w),T=M(S.context,A,g),L=x.multiply(T).toRawBytes(),U=M(S.context,L,O,g),k=N(T+U*I);ki("signature.s",k,jt,r);const C=Mf(L,Xa(k,n.BYTES));return pn("result",C,n.BYTES*2)}const y=e2;function m(g,w,S,A=y){const{context:I,zip215:O}=A,T=n.BYTES;g=pn("signature",g,2*T),w=pn("message",w),S=pn("publicKey",S,T),O!==void 0&&Za("zip215",O),i&&(w=i(w));const L=Ys(g.slice(T,2*T));let U,k,C;try{U=_.fromHex(S,O),k=_.fromHex(g.slice(0,T),O),C=x.multiplyUnsafe(L)}catch{return!1}if(!O&&U.isSmallOrder())return!1;const q=M(I,k.toRawBytes(),U.toRawBytes(),w);return k.add(U.multiplyUnsafe(q)).subtract(C).clearCofactor().equals(_.ZERO)}return x._setWindowSize(8),{CURVE:e,getPublicKey:z,sign:E,verify:m,ExtendedPoint:_,utils:{getExtendedPublicKey:$,randomPrivateKey:()=>o(n.BYTES),precompute(g=8,w=_.BASE){return w._setWindowSize(g),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const sc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Xf=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const r2=BigInt(1),Jf=BigInt(2);BigInt(3);const i2=BigInt(5),s2=BigInt(8);function o2(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=sc,o=t*t%s*t%s,a=Qt(o,Jf,s)*o%s,c=Qt(a,r2,s)*t%s,u=Qt(c,i2,s)*c%s,l=Qt(u,e,s)*u%s,f=Qt(l,n,s)*l%s,d=Qt(f,r,s)*f%s,h=Qt(d,i,s)*d%s,p=Qt(h,i,s)*d%s,b=Qt(p,e,s)*u%s;return{pow_p_5_8:Qt(b,Jf,s)*t%s,b2:o}}function a2(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function c2(t,e){const n=sc,r=Be(e*e*e,n),i=Be(r*r*e,n),s=o2(t*i).pow_p_5_8;let o=Be(t*r*s,n);const a=Be(e*o*o,n),c=o,u=Be(o*Xf,n),l=a===t,f=a===Be(-t,n),d=a===Be(-t*Xf,n);return l&&(o=c),(f||d)&&(o=u),zm(o,n)&&(o=Be(-o,n)),{isValid:l||f,value:o}}const u2=(()=>Gf(sc,void 0,!0))(),l2=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:u2,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:s2,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Pm,randomBytes:Nf,adjustScalarBytes:a2,uvRatio:c2}))(),Qf=(()=>n2(l2))(),f2="EdDSA",h2="JWT",Qs=".",eo="base64url",eh="utf8",th="utf8",d2=":",p2="did",g2="key",nh="base58btc",y2="z",b2="K36",w2=32;function oc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function rh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?oc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function ih(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=rh(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return oc(n)}function m2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[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 b=0,v=0,B=0,D=p.length;B!==D&&p[B]===0;)B++,b++;for(var _=(D-B)*l+1>>>0,x=new Uint8Array(_);B!==D;){for(var P=p[B],R=0,N=_-1;(P!==0||R<v)&&N!==-1;N--,R++)P+=256*x[N]>>>0,x[N]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");v=R,B++}for(var F=_-v;F!==_&&x[F]===0;)F++;for(var $=c.repeat(b);F<_;++F)$+=t.charAt(x[F]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,B=0;p[b]===c;)v++,b++;for(var D=(p.length-b)*u+1>>>0,_=new Uint8Array(D);p[b];){var x=n[p.charCodeAt(b)];if(x===255)return;for(var P=0,R=D-1;(x!==0||P<B)&&R!==-1;R--,P++)x+=a*_[R]>>>0,_[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");B=P,b++}if(p[b]!==" "){for(var N=D-B;N!==D&&_[N]===0;)N++;for(var F=new Uint8Array(v+(D-N)),$=v;N!==D;)F[$++]=_[N++];return F}}}function h(p){var b=d(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var v2=m2,E2=v2;const sh=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")},x2=t=>new TextEncoder().encode(t),_2=t=>new TextDecoder().decode(t);class S2{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class I2{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return oh(this,e)}}class A2{constructor(e){this.decoders=e}or(e){return oh(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const oh=(t,e)=>new A2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class B2{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new S2(e,n,r),this.decoder=new I2(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const to=({name:t,prefix:e,encode:n,decode:r})=>new B2(t,e,n,r),qi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=E2(n,e);return to({prefix:t,name:e,encode:r,decode:s=>sh(i(s))})},O2=(t,e,n,r)=>{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*n/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-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},D2=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Fe=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>to({prefix:e,name:t,encode(i){return D2(i,r,n)},decode(i){return O2(i,r,n,t)}}),$2=to({prefix:"\0",name:"identity",encode:t=>_2(t),decode:t=>x2(t)});var P2=Object.freeze({__proto__:null,identity:$2});const T2=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var R2=Object.freeze({__proto__:null,base2:T2});const N2=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var C2=Object.freeze({__proto__:null,base8:N2});const U2=qi({prefix:"9",name:"base10",alphabet:"0123456789"});var F2=Object.freeze({__proto__:null,base10:U2});const L2=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),k2=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var q2=Object.freeze({__proto__:null,base16:L2,base16upper:k2});const M2=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j2=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),z2=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),H2=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),V2=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),K2=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),G2=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),W2=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Z2=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Y2=Object.freeze({__proto__:null,base32:M2,base32upper:j2,base32pad:z2,base32padupper:H2,base32hex:V2,base32hexupper:K2,base32hexpad:G2,base32hexpadupper:W2,base32z:Z2});const X2=qi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),J2=qi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Q2=Object.freeze({__proto__:null,base36:X2,base36upper:J2});const ev=qi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),tv=qi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var nv=Object.freeze({__proto__:null,base58btc:ev,base58flickr:tv});const rv=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),iv=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sv=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),ov=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var av=Object.freeze({__proto__:null,base64:rv,base64pad:iv,base64url:sv,base64urlpad:ov});const ah=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}"),cv=ah.reduce((t,e,n)=>(t[n]=e,t),[]),uv=ah.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function lv(t){return t.reduce((e,n)=>(e+=cv[n],e),"")}function fv(t){const e=[];for(const n of t){const r=uv[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const hv=to({prefix:"\u{1F680}",name:"base256emoji",encode:lv,decode:fv});var dv=Object.freeze({__proto__:null,base256emoji:hv}),pv=uh,ch=128,gv=127,yv=~gv,bv=Math.pow(2,31);function uh(t,e,n){e=e||[],n=n||0;for(var r=n;t>=bv;)e[n++]=t&255|ch,t/=128;for(;t&yv;)e[n++]=t&255|ch,t>>>=7;return e[n]=t|0,uh.bytes=n-r+1,e}var wv=ac,mv=128,lh=127;function ac(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw ac.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&lh)<<i:(o&lh)*Math.pow(2,i),i+=7}while(o>=mv);return ac.bytes=s-r,n}var vv=Math.pow(2,7),Ev=Math.pow(2,14),xv=Math.pow(2,21),_v=Math.pow(2,28),Sv=Math.pow(2,35),Iv=Math.pow(2,42),Av=Math.pow(2,49),Bv=Math.pow(2,56),Ov=Math.pow(2,63),Dv=function(t){return t<vv?1:t<Ev?2:t<xv?3:t<_v?4:t<Sv?5:t<Iv?6:t<Av?7:t<Bv?8:t<Ov?9:10},$v={encode:pv,decode:wv,encodingLength:Dv},fh=$v;const hh=(t,e,n=0)=>(fh.encode(t,e,n),e),dh=t=>fh.encodingLength(t),cc=(t,e)=>{const n=e.byteLength,r=dh(t),i=r+dh(n),s=new Uint8Array(i+n);return hh(t,s,0),hh(n,s,r),s.set(e,i),new Pv(t,n,e,s)};class Pv{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const ph=({name:t,code:e,encode:n})=>new Tv(t,e,n);class Tv{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?cc(this.code,n):n.then(r=>cc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const gh=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Rv=ph({name:"sha2-256",code:18,encode:gh("SHA-256")}),Nv=ph({name:"sha2-512",code:19,encode:gh("SHA-512")});var Cv=Object.freeze({__proto__:null,sha256:Rv,sha512:Nv});const yh=0,Uv="identity",bh=sh;var Fv=Object.freeze({__proto__:null,identity:{code:yh,name:Uv,encode:bh,digest:t=>cc(yh,bh(t))}});new TextEncoder,new TextDecoder;const wh={...P2,...R2,...C2,...F2,...q2,...Y2,...Q2,...nv,...av,...dv};({...Cv,...Fv});function mh(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const vh=mh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),uc=mh("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=rh(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Eh={utf8:vh,"utf-8":vh,hex:wh.base16,latin1:uc,ascii:uc,binary:uc,...wh};function no(t,e="utf8"){const n=Eh[e];if(!n)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"):n.encoder.encode(t).substring(1)}function ni(t,e="utf8"){const n=Eh[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?oc(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function xh(t){return Jr(no(ni(t,eo),eh))}function ro(t){return no(ni(Ir(t),eh),eo)}function _h(t){const e=ni(b2,nh),n=y2+no(ih([e,t]),nh);return[p2,g2,n].join(d2)}function Lv(t){return no(t,eo)}function kv(t){return ni(t,eo)}function qv(t){return ni([ro(t.header),ro(t.payload)].join(Qs),th)}function Mv(t){return[ro(t.header),ro(t.payload),Lv(t.signature)].join(Qs)}function lc(t){const e=t.split(Qs),n=xh(e[0]),r=xh(e[1]),i=kv(e[2]),s=ni(e.slice(0,2).join(Qs),th);return{header:n,payload:r,signature:i,data:s}}function Sh(t=Nf(w2)){const e=Qf.getPublicKey(t);return{secretKey:ih([t,e]),publicKey:e}}async function jv(t,e,n,r,i=K.fromMiliseconds(Date.now())){const s={alg:f2,typ:h2},o=_h(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=qv({header:s,payload:c}),l=Qf.sign(u,r.secretKey.slice(0,32));return Mv({header:s,payload:c,signature:l})}var Ih=function(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},zv=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),Hv=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Vv=function(){function t(e,n,r,i){this.name=e,this.version=n,this.os=r,this.bot=i,this.type="bot-device"}return t}(),Kv=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Gv=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Wv=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Zv=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Ah=3,Yv=[["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",Wv]],Bh=[["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 Xv(t){return t?Oh(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Gv:typeof navigator<"u"?Oh(navigator.userAgent):e3()}function Jv(t){return t!==""&&Yv.reduce(function(e,n){var r=n[0],i=n[1];if(e)return e;var s=i.exec(t);return!!s&&[r,s]},!1)}function Oh(t){var e=Jv(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new Kv;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<Ah&&(i=Ih(Ih([],i,!0),t3(Ah-i.length),!0)):i=[];var s=i.join("."),o=Qv(t),a=Zv.exec(t);return a&&a[1]?new Vv(n,s,o,a[1]):new zv(n,s,o)}function Qv(t){for(var e=0,n=Bh.length;e<n;e++){var r=Bh[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function e3(){var t=typeof process<"u"&&process.version;return t?new Hv(process.version.slice(1)):null}function t3(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var be={};Object.defineProperty(be,"__esModule",{value:!0}),be.getLocalStorage=be.getLocalStorageOrThrow=be.getCrypto=be.getCryptoOrThrow=Dh=be.getLocation=be.getLocationOrThrow=fc=be.getNavigator=be.getNavigatorOrThrow=Or=be.getDocument=be.getDocumentOrThrow=be.getFromWindowOrThrow=be.getFromWindow=void 0;function Br(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}be.getFromWindow=Br;function ri(t){const e=Br(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}be.getFromWindowOrThrow=ri;function n3(){return ri("document")}be.getDocumentOrThrow=n3;function r3(){return Br("document")}var Or=be.getDocument=r3;function i3(){return ri("navigator")}be.getNavigatorOrThrow=i3;function s3(){return Br("navigator")}var fc=be.getNavigator=s3;function o3(){return ri("location")}be.getLocationOrThrow=o3;function a3(){return Br("location")}var Dh=be.getLocation=a3;function c3(){return ri("crypto")}be.getCryptoOrThrow=c3;function u3(){return Br("crypto")}be.getCrypto=u3;function l3(){return ri("localStorage")}be.getLocalStorageOrThrow=l3;function f3(){return Br("localStorage")}be.getLocalStorage=f3;var hc={};Object.defineProperty(hc,"__esModule",{value:!0});var $h=hc.getWindowMetadata=void 0;const Ph=be;function h3(){let t,e;try{t=Ph.getDocumentOrThrow(),e=Ph.getLocationOrThrow()}catch{return null}function n(){const f=t.getElementsByTagName("link"),d=[];for(let h=0;h<f.length;h++){const p=f[h],b=p.getAttribute("rel");if(b&&b.toLowerCase().indexOf("icon")>-1){const v=p.getAttribute("href");if(v)if(v.toLowerCase().indexOf("https:")===-1&&v.toLowerCase().indexOf("http:")===-1&&v.indexOf("//")!==0){let B=e.protocol+"//"+e.host;if(v.indexOf("/")===0)B+=v;else{const D=e.pathname.split("/");D.pop();const _=D.join("/");B+=_+"/"+v}d.push(B)}else if(v.indexOf("//")===0){const B=e.protocol+v;d.push(B)}else d.push(v)}}return d}function r(...f){const d=t.getElementsByTagName("meta");for(let h=0;h<d.length;h++){const p=d[h],b=["itemprop","property","name"].map(v=>p.getAttribute(v)).filter(v=>v?f.includes(v):!1);if(b.length&&b){const v=p.getAttribute("content");if(v)return v}}return""}function i(){let f=r("name","og:site_name","og:title","twitter:title");return f||(f=t.title),f}function s(){return r("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=n();return{description:a,url:c,icons:u,name:o}}$h=hc.getWindowMetadata=h3;const d3="0.1.1";function p3(){return d3}class ge extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof ge){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=(()=>n.cause instanceof ge&&n.cause.docsPath||n.docsPath)(),o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
15
+ `);super(a,n.cause?{cause:n.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@${p3()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Th(this,e)}}function Th(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Th(t.cause,e):e?null:t}const ii=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function g3(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Dr(t,...e){if(!g3(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 y3(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Mi(t.outputLen),Mi(t.blockLen)}function si(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 Rh(t,e){Dr(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function b3(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function dc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function en(t,e){return t<<32-e|t>>>e}const w3=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function m3(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function v3(t){for(let e=0;e<t.length;e++)t[e]=m3(t[e]);return t}const Nh=w3?t=>t:v3;function E3(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function io(t){return typeof t=="string"&&(t=E3(t)),Dr(t),t}function x3(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Dr(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class pc{}function so(t){const e=r=>t().update(io(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Ch(t=32){if(ii&&typeof ii.getRandomValues=="function")return ii.getRandomValues(new Uint8Array(t));if(ii&&typeof ii.randomBytes=="function")return Uint8Array.from(ii.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function _3(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function S3(t,e,n){return t&e^~t&n}function I3(t,e,n){return t&e^t&n^e&n}class Uh extends pc{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=dc(this.buffer)}update(e){si(this),e=io(e),Dr(e);const{view:n,buffer:r,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=dc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){si(this),Rh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qn(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;_3(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=dc(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const gn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),We=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),oo=BigInt(2**32-1),Fh=BigInt(32);function A3(t,e=!1){return e?{h:Number(t&oo),l:Number(t>>Fh&oo)}:{h:Number(t>>Fh&oo)|0,l:Number(t&oo)|0}}function Lh(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=A3(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const kh=(t,e,n)=>t>>>n,qh=(t,e,n)=>t<<32-n|e>>>n,oi=(t,e,n)=>t>>>n|e<<32-n,ai=(t,e,n)=>t<<32-n|e>>>n,ao=(t,e,n)=>t<<64-n|e>>>n-32,co=(t,e,n)=>t>>>n-32|e<<64-n,B3=(t,e,n)=>t<<n|e>>>32-n,O3=(t,e,n)=>e<<n|t>>>32-n,D3=(t,e,n)=>e<<n-32|t>>>64-n,$3=(t,e,n)=>t<<n-32|e>>>64-n;function yn(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const P3=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),T3=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,R3=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),N3=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,C3=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),U3=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,F3=BigInt(0),ji=BigInt(1),L3=BigInt(2),k3=BigInt(7),q3=BigInt(256),M3=BigInt(113),Mh=[],jh=[],zh=[];for(let t=0,e=ji,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Mh.push(2*(5*r+n)),jh.push((t+1)*(t+2)/2%64);let i=F3;for(let s=0;s<7;s++)e=(e<<ji^(e>>k3)*M3)%q3,e&L3&&(i^=ji<<(ji<<BigInt(s))-ji);zh.push(i)}const Hh=Lh(zh,!0),j3=Hh[0],z3=Hh[1],Vh=(t,e,n)=>n>32?D3(t,e,n):B3(t,e,n),Kh=(t,e,n)=>n>32?$3(t,e,n):O3(t,e,n);function H3(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[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=n[c],l=n[c+1],f=Vh(u,l,1)^n[a],d=Kh(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=jh[o],c=Vh(i,s,a),u=Kh(i,s,a),l=Mh[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++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=j3[r],t[1]^=z3[r]}qn(n)}class gc extends pc{constructor(e,n,r,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=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Mi(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=b3(this.state)}clone(){return this._cloneInto()}keccak(){Nh(this.state32),H3(this.state32,this.rounds),Nh(this.state32),this.posOut=0,this.pos=0}update(e){si(this),e=io(e),Dr(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,n&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){si(this,!1),Dr(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.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 Mi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Rh(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,qn(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new gc(n,r,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=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const V3=(t,e,n)=>so(()=>new gc(e,t,n)),K3=(()=>V3(1,136,256/8))(),G3=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]),Mn=new Uint32Array(64);class W3 extends Uh{constructor(e=32){super(64,e,8,!1),this.A=gn[0]|0,this.B=gn[1]|0,this.C=gn[2]|0,this.D=gn[3]|0,this.E=gn[4]|0,this.F=gn[5]|0,this.G=gn[6]|0,this.H=gn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)Mn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=Mn[f-15],h=Mn[f-2],p=en(d,7)^en(d,18)^d>>>3,b=en(h,17)^en(h,19)^h>>>10;Mn[f]=b+Mn[f-7]+p+Mn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=en(a,6)^en(a,11)^en(a,25),h=l+d+S3(a,c,u)+G3[f]+Mn[f]|0,b=(en(r,2)^en(r,13)^en(r,22))+I3(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+b|0}r=r+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(r,i,s,o,a,c,u,l)}roundClean(){qn(Mn)}destroy(){this.set(0,0,0,0,0,0,0,0),qn(this.buffer)}}const Gh=(()=>Lh(["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))))(),Z3=(()=>Gh[0])(),Y3=(()=>Gh[1])(),jn=new Uint32Array(80),zn=new Uint32Array(80);class Wh extends Uh{constructor(e=64){super(128,e,16,!1),this.Ah=We[0]|0,this.Al=We[1]|0,this.Bh=We[2]|0,this.Bl=We[3]|0,this.Ch=We[4]|0,this.Cl=We[5]|0,this.Dh=We[6]|0,this.Dl=We[7]|0,this.Eh=We[8]|0,this.El=We[9]|0,this.Fh=We[10]|0,this.Fl=We[11]|0,this.Gh=We[12]|0,this.Gl=We[13]|0,this.Hh=We[14]|0,this.Hl=We[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:b,Hl:v}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v){this.Ah=e|0,this.Al=n|0,this.Bh=r|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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=b|0,this.Hl=v|0}process(e,n){for(let _=0;_<16;_++,n+=4)jn[_]=e.getUint32(n),zn[_]=e.getUint32(n+=4);for(let _=16;_<80;_++){const x=jn[_-15]|0,P=zn[_-15]|0,R=oi(x,P,1)^oi(x,P,8)^kh(x,P,7),N=ai(x,P,1)^ai(x,P,8)^qh(x,P,7),F=jn[_-2]|0,$=zn[_-2]|0,z=oi(F,$,19)^ao(F,$,61)^kh(F,$,6),M=ai(F,$,19)^co(F,$,61)^qh(F,$,6),E=R3(N,M,zn[_-7],zn[_-16]),y=N3(E,R,z,jn[_-7],jn[_-16]);jn[_]=y|0,zn[_]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:b,Gl:v,Hh:B,Hl:D}=this;for(let _=0;_<80;_++){const x=oi(f,d,14)^oi(f,d,18)^ao(f,d,41),P=ai(f,d,14)^ai(f,d,18)^co(f,d,41),R=f&h^~f&b,N=d&p^~d&v,F=C3(D,P,N,Y3[_],zn[_]),$=U3(F,B,x,R,Z3[_],jn[_]),z=F|0,M=oi(r,i,28)^ao(r,i,34)^ao(r,i,39),E=ai(r,i,28)^co(r,i,34)^co(r,i,39),y=r&s^r&a^s&a,m=i&o^i&c^o&c;B=b|0,D=v|0,b=h|0,v=p|0,h=f|0,p=d|0,{h:f,l:d}=yn(u|0,l|0,$|0,z|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const g=P3(z,E,m);r=T3(g,$,M,y),i=g|0}({h:r,l:i}=yn(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=yn(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=yn(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=yn(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=yn(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=yn(this.Fh|0,this.Fl|0,h|0,p|0),{h:b,l:v}=yn(this.Gh|0,this.Gl|0,b|0,v|0),{h:B,l:D}=yn(this.Hh|0,this.Hl|0,B|0,D|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,b,v,B,D)}roundClean(){qn(jn,zn)}destroy(){qn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class X3 extends Wh{constructor(){super(48),this.Ah=Ge[0]|0,this.Al=Ge[1]|0,this.Bh=Ge[2]|0,this.Bl=Ge[3]|0,this.Ch=Ge[4]|0,this.Cl=Ge[5]|0,this.Dh=Ge[6]|0,this.Dl=Ge[7]|0,this.Eh=Ge[8]|0,this.El=Ge[9]|0,this.Fh=Ge[10]|0,this.Fl=Ge[11]|0,this.Gh=Ge[12]|0,this.Gl=Ge[13]|0,this.Hh=Ge[14]|0,this.Hl=Ge[15]|0}}const uo=so(()=>new W3),J3=so(()=>new Wh),Q3=so(()=>new X3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const yc=BigInt(0),lo=BigInt(1);function zi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hn(t){if(!zi(t))throw new Error("Uint8Array expected")}function Hi(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function fo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Zh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?yc:BigInt("0x"+t)}const Yh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",eE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function $r(t){if(Hn(t),Yh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=eE[t[n]];return e}const bn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Xh(t){if(t>=bn._0&&t<=bn._9)return t-bn._0;if(t>=bn.A&&t<=bn.F)return t-(bn.A-10);if(t>=bn.a&&t<=bn.f)return t-(bn.a-10)}function ho(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Yh)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Xh(t.charCodeAt(s)),a=Xh(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)}r[i]=o*16+a}return r}function it(t){return Zh($r(t))}function Jh(t){return Hn(t),Zh($r(Uint8Array.from(t).reverse()))}function Oe(t,e){return ho(t.toString(16).padStart(e*2,"0"))}function Qh(t,e){return Oe(t,e).reverse()}function Ze(t,e,n){let r;if(typeof e=="string")try{r=ho(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(zi(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function _e(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Hn(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}function bc(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const wc=t=>typeof t=="bigint"&&yc<=t;function mc(t,e,n){return wc(t)&&wc(e)&&wc(n)&&e<=t&&t<n}function ci(t,e,n,r){if(!mc(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Vi(t){let e;for(e=0;t>yc;t>>=lo,e+=1);return e}function tE(t,e){return t>>BigInt(e)&lo}const Pr=t=>(lo<<BigInt(t))-lo,vc=t=>new Uint8Array(t),ed=t=>Uint8Array.from(t);function nE(t,e,n){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 n!="function")throw new Error("hmacFn must be a function");let r=vc(t),i=vc(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...f)=>n(i,r,...f),c=(f=vc(0))=>{i=a(ed([0]),f),r=a(),f.length!==0&&(i=a(ed([1]),f),r=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){r=a();const h=r.slice();d.push(h),f+=r.length}return _e(...d)};return(f,d)=>{o(),c(f);let h;for(;!(h=d(u()));)c();return o(),h}}const rE={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"||zi(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 Ki(t,e,n={}){const r=(i,s,o)=>{const a=rE[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))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}const td=()=>{throw new Error("not implemented")};function Ec(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}function iE(t,e){if(ad(t)>e)throw new AE({givenSize:ad(t),maxSize:e})}const wn={zero:48,nine:57,A:65,F:70,a:97,f:102};function nd(t){if(t>=wn.zero&&t<=wn.nine)return t-wn.zero;if(t>=wn.A&&t<=wn.F)return t-(wn.A-10);if(t>=wn.a&&t<=wn.f)return t-(wn.a-10)}function sE(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new BE({size:t.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=t[o?s:t.length-s-1]}return i}function xc(t,e){if(vn(t)>e)throw new yE({givenSize:vn(t),maxSize:e})}function oE(t,e){if(typeof e=="number"&&e>0&&e>vn(t)-1)throw new od({offset:e,position:"start",size:vn(t)})}function aE(t,e,n){if(typeof e=="number"&&typeof n=="number"&&vn(t)!==n-e)throw new od({offset:n,position:"end",size:vn(t)})}function rd(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const i=t.replace("0x","");if(i.length>r*2)throw new bE({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const cE="#__bigint";function _c(t,e,n){return JSON.stringify(t,(r,i)=>typeof e=="function"?e(r,i):typeof i=="bigint"?i.toString()+cE:i,n)}const uE=new TextEncoder,lE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function fE(t,e={}){const{strict:n=!1}=e;if(!t)throw new id(t);if(typeof t!="string")throw new id(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new sd(t);if(!t.startsWith("0x"))throw new sd(t)}function Sc(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function Ic(t){return t instanceof Uint8Array?Gi(t):Array.isArray(t)?Gi(new Uint8Array(t)):t}function hE(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(xc(n,e.size),go(n,e.size)):n}function Gi(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=lE[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(xc(r,e.size),Ac(r,e.size)):r}function po(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new gE({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:n,size:r,value:`${t}${u}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?go(c,r):c}function dE(t,e={}){return Gi(uE.encode(t),e)}function go(t,e){return rd(t,{dir:"left",size:e})}function Ac(t,e){return rd(t,{dir:"right",size:e})}function mn(t,e,n,r={}){const{strict:i}=r;oE(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return i&&aE(s,e,n),s}function vn(t){return Math.ceil((t.length-2)/2)}function pE(t,e={}){const{strict:n=!1}=e;try{return fE(t,{strict:n}),!0}catch{return!1}}class gE extends ge{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class id extends ge{constructor(e){super(`Value \`${typeof e=="object"?_c(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class sd extends ge{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class yE extends ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class od extends ge{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class bE extends ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const wE=new TextEncoder;function mE(t){if(!(t instanceof Uint8Array)){if(!t)throw new yo(t);if(typeof t!="object")throw new yo(t);if(!("BYTES_PER_ELEMENT"in t))throw new yo(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new yo(t)}}function vE(t){return t instanceof Uint8Array?t:typeof t=="string"?xE(t):EE(t)}function EE(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function xE(t,e={}){const{size:n}=e;let r=t;n&&(xc(t,n),r=Ac(t,n));let i=r.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=nd(i.charCodeAt(c++)),l=nd(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new ge(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function _E(t,e={}){const{size:n}=e,r=wE.encode(t);return typeof n=="number"?(iE(r,n),SE(r,n)):r}function SE(t,e){return sE(t,{dir:"right",size:e})}function ad(t){return t.length}function IE(t){try{return mE(t),!0}catch{return!1}}class yo extends ge{constructor(e){super(`Value \`${typeof e=="object"?_c(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class AE extends ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class BE extends ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function cd(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=K3(vE(t));return n==="Bytes"?r:Gi(r)}class OE extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Bc={checksum:new OE(8192)}.checksum;function ud(t,e={}){const{compressed:n}=e,{prefix:r,x:i,y:s}=t;if(n===!1||typeof i=="bigint"&&typeof s=="bigint"){if(r!==4)throw new fd({prefix:r,cause:new NE});return}if(n===!0||typeof i=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new fd({prefix:r,cause:new RE});return}throw new TE({publicKey:t})}function DE(t){const e=(()=>{if(pE(t))return ld(t);if(IE(t))return $E(t);const{prefix:n,x:r,y:i}=t;return typeof r=="bigint"&&typeof i=="bigint"?{prefix:n??4,x:r,y:i}:{prefix:n,x:r}})();return ud(e),e}function $E(t){return ld(Gi(t))}function ld(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new CE({publicKey:t});if(t.length===130){const r=BigInt(mn(t,0,32)),i=BigInt(mn(t,32,64));return{prefix:4,x:r,y:i}}if(t.length===132){const r=Number(mn(t,0,1)),i=BigInt(mn(t,1,33)),s=BigInt(mn(t,33,65));return{prefix:r,x:i,y:s}}const e=Number(mn(t,0,1)),n=BigInt(mn(t,1,33));return{prefix:e,x:n}}function PE(t,e={}){ud(t);const{prefix:n,x:r,y:i}=t,{includePrefix:s=!0}=e;return Sc(s?po(n,{size:1}):"0x",po(r,{size:32}),typeof i=="bigint"?po(i,{size:32}):"0x")}class TE extends ge{constructor({publicKey:e}){super(`Value \`${_c(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class fd extends ge{constructor({prefix:e,cause:n}){super(`Prefix "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class RE extends ge{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class NE extends ge{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class CE extends ge{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${vn(Ic(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const UE=/^0x[a-fA-F0-9]{40}$/;function Oc(t,e={}){const{strict:n=!0}=e;if(!UE.test(t))throw new dd({address:t,cause:new kE});if(n){if(t.toLowerCase()===t)return;if(hd(t)!==t)throw new dd({address:t,cause:new qE})}}function hd(t){if(Bc.has(t))return Bc.get(t);Oc(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=cd(_E(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return Bc.set(t,i),i}function FE(t,e={}){const{checksum:n=!1}=e;return Oc(t),n?hd(t):t}function LE(t,e={}){const n=cd(`0x${PE(t).slice(4)}`).substring(26);return FE(`0x${n}`,e)}class dd extends ge{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class kE extends ge{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 qE extends ge{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const ME=/^(.*)\[([0-9]*)\]$/,jE=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,zE=/^(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 Dc(t,e){if(t.length!==e.length)throw new VE({expectedLength:t.length,givenLength:e.length});const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r];n.push(Dc.encode(i,s))}return Sc(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return Oc(c),go(c.toLowerCase(),i?32:0)}if(n==="string")return dE(r);if(n==="bytes")return r;if(n==="bool")return go(hE(r),i?32:1);const s=n.match(zE);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return po(r,{size:i?32:f,signed:u==="int"})}const o=n.match(jE);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(r.length-2)/2)throw new HE({expectedSize:Number.parseInt(u,10),value:r});return Ac(r,i?32:0)}const a=n.match(ME);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let f=0;f<r.length;f++)l.push(e(u,r[f],!0));return l.length===0?"0x":Sc(...l)}throw new KE(n)}t.encode=e})(Dc||(Dc={}));class HE extends ge{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${vn(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class VE extends ge{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
16
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class KE extends ge{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 pd extends pc{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,y3(e);const r=io(n);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(r.length>i?e.create().update(r).digest():r);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),qn(s)}update(e){return si(this),this.iHash.update(e),this}digestInto(e){si(this),Dr(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:n,iHash:r,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=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const gd=(t,e,n)=>new pd(t,e).update(n).digest();gd.create=(t,e)=>new pd(t,e);const pt=BigInt(0),st=BigInt(1),Tr=BigInt(2),GE=BigInt(3),yd=BigInt(4),bd=BigInt(5),wd=BigInt(8);function ot(t,e){const n=t%e;return n>=pt?n:e+n}function Pt(t,e,n){let r=t;for(;e-- >pt;)r*=r,r%=n;return r}function $c(t,e){if(t===pt)throw new Error("invert: expected non-zero number");if(e<=pt)throw new Error("invert: expected positive modulus, got "+e);let n=ot(t,e),r=e,i=pt,s=st;for(;n!==pt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==st)throw new Error("invert: does not exist");return ot(i,e)}function md(t,e){const n=(t.ORDER+st)/yd,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function WE(t,e){const n=(t.ORDER-bd)/wd,r=t.mul(e,Tr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Tr),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 ZE(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-st,n=0;for(;e%Tr===pt;)e/=Tr,n++;let r=Tr;const i=Vn(t);for(;wo(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return md;let s=i.pow(r,e);const o=(e+st)/Tr;return function(c,u){if(c.is0(u))return u;if(wo(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,b=c.sqr(d);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===l)throw new Error("Cannot find square root");const v=st<<BigInt(l-p-1),B=c.pow(f,v);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function YE(t){return t%yd===GE?md:t%wd===bd?WE:ZE(t)}const XE=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function vd(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=XE.reduce((r,i)=>(r[i]="function",r),e);return Ki(t,n)}function bo(t,e,n){if(n<pt)throw new Error("invalid exponent, negatives unsupported");if(n===pt)return t.ONE;if(n===st)return e;let r=t.ONE,i=e;for(;n>pt;)n&st&&(r=t.mul(r,i)),i=t.sqr(i),n>>=st;return r}function Rr(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function wo(t,e){const n=(t.ORDER-st)/Tr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Ed(t,e){e!==void 0&&Mi(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Vn(t,e,n=!1,r={}){if(t<=pt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Ed(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:Pr(i),ZERO:pt,ONE:st,create:c=>ot(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return pt<=c&&c<t},is0:c=>c===pt,isOdd:c=>(c&st)===st,neg:c=>ot(-c,t),eql:(c,u)=>c===u,sqr:c=>ot(c*c,t),add:(c,u)=>ot(c+u,t),sub:(c,u)=>ot(c-u,t),mul:(c,u)=>ot(c*u,t),pow:(c,u)=>bo(a,c,u),div:(c,u)=>ot(c*$c(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>$c(c,t),sqrt:r.sqrt||(c=>(o||(o=YE(t)),o(a,c))),toBytes:c=>n?Qh(c,s):Oe(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?Jh(c):it(c)},invertBatch:c=>Rr(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function xd(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 Pc(t){const e=xd(t);return e+Math.ceil(e/2)}function _d(t,e,n=!1){const r=t.length,i=xd(e),s=Pc(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Jh(t):it(t),a=ot(o,e-st)+st;return n?Qh(a,i):Oe(a,i)}const Sd=BigInt(0),Tc=BigInt(1);function Rc(t,e){const n=e.negate();return t?n:e}function Id(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Nc(t,e){Id(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Pr(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Ad(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=Tc);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function JE(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function QE(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Cc=new WeakMap,Bd=new WeakMap;function Uc(t){return Bd.get(t)||1}function e8(t,e){return{constTimeNegate:Rc,hasPrecomputes(n){return Uc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Sd;)r&Tc&&(i=i.add(s)),s=s.double(),r>>=Tc;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Nc(r,e),o=[];let a=n,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(n,r,i){let s=t.ZERO,o=t.BASE;const a=Nc(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Ad(i,c,a);i=u,f?o=o.add(Rc(h,r[p])):s=s.add(Rc(d,r[l]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=Nc(n,e);for(let a=0;a<o.windows&&i!==Sd;a++){const{nextN:c,offset:u,isZero:l,isNeg:f}=Ad(i,a,o);if(i=c,!l){const d=r[u];s=s.add(f?d.negate():d)}}return s},getPrecomputes(n,r,i){let s=Cc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Cc.set(r,i(s))),s},wNAFCached(n,r,i){const s=Uc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Uc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Id(r,e),Bd.set(n,r),Cc.delete(n)}}}function t8(t,e,n,r){JE(n,t),QE(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Vi(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Pr(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let b=0;b<s;b++){const v=r[b],B=Number(v>>BigInt(h)&u);l[B]=l[B].add(n[b])}let p=o;for(let b=l.length-1,v=o;b>0;b--)v=v.add(l[b]),p=p.add(v);if(d=d.add(p),h!==0)for(let b=0;b<c;b++)d=d.double()}return d}function Od(t){return vd(t.Fp),Ki(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Ed(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Dd(t){t.lowS!==void 0&&Hi("lowS",t.lowS),t.prehash!==void 0&&Hi("prehash",t.prehash)}function n8(t){const e=Od(t);Ki(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class r8 extends Error{constructor(e=""){super(e)}}const En={Err:r8,_tlv:{encode:(t,e)=>{const{Err:n}=En;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=fo(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?fo(i.length/2|128):"";return fo(t)+s+i+e},decode(t,e){const{Err:n}=En;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=En;if(t<zt)throw new e("integer: negative integers are not allowed");let n=fo(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=En;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 it(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=En,i=Ze("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=En,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}};function Fc(t,e){return $r(Oe(t,e))}const zt=BigInt(0),pe=BigInt(1),Kn=BigInt(2),Wi=BigInt(3),Lc=BigInt(4);function kc(t){const e=n8(t),{Fp:n}=e,r=Vn(e.n,e.nBitLength),i=e.toBytes||((_,x,P)=>{const R=x.toAffine();return _e(Uint8Array.from([4]),n.toBytes(R.x),n.toBytes(R.y))}),s=e.fromBytes||(_=>{const x=_.subarray(1),P=n.fromBytes(x.subarray(0,n.BYTES)),R=n.fromBytes(x.subarray(n.BYTES,2*n.BYTES));return{x:P,y:R}});function o(_){const{a:x,b:P}=e,R=n.sqr(_),N=n.mul(R,_);return n.add(n.add(N,n.mul(_,x)),P)}function a(_,x){const P=n.sqr(x),R=o(_);return n.eql(P,R)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,Wi),Lc),u=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,u)))throw new Error("bad curve params: a or b");function l(_){return mc(_,pe,e.n)}function f(_){const{allowedPrivateKeyLengths:x,nByteLength:P,wrapPrivateKey:R,n:N}=e;if(x&&typeof _!="bigint"){if(zi(_)&&(_=$r(_)),typeof _!="string"||!x.includes(_.length))throw new Error("invalid private key");_=_.padStart(P*2,"0")}let F;try{F=typeof _=="bigint"?_:it(Ze("private key",_,P))}catch{throw new Error("invalid private key, expected hex or "+P+" bytes, got "+typeof _)}return R&&(F=ot(F,N)),ci("private key",F,pe,N),F}function d(_){if(!(_ instanceof b))throw new Error("ProjectivePoint expected")}const h=Ec((_,x)=>{const{px:P,py:R,pz:N}=_;if(n.eql(N,n.ONE))return{x:P,y:R};const F=_.is0();x==null&&(x=F?n.ONE:n.inv(N));const $=n.mul(P,x),z=n.mul(R,x),M=n.mul(N,x);if(F)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:$,y:z}}),p=Ec(_=>{if(_.is0()){if(e.allowInfinityPoint&&!n.is0(_.py))return;throw new Error("bad point: ZERO")}const{x,y:P}=_.toAffine();if(!n.isValid(x)||!n.isValid(P))throw new Error("bad point: x or y not FE");if(!a(x,P))throw new Error("bad point: equation left != right");if(!_.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class b{constructor(x,P,R){if(x==null||!n.isValid(x))throw new Error("x required");if(P==null||!n.isValid(P)||n.is0(P))throw new Error("y required");if(R==null||!n.isValid(R))throw new Error("z required");this.px=x,this.py=P,this.pz=R,Object.freeze(this)}static fromAffine(x){const{x:P,y:R}=x||{};if(!x||!n.isValid(P)||!n.isValid(R))throw new Error("invalid affine point");if(x instanceof b)throw new Error("projective point not allowed");const N=F=>n.eql(F,n.ZERO);return N(P)&&N(R)?b.ZERO:new b(P,R,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(x){const P=Rr(n,x.map(R=>R.pz));return x.map((R,N)=>R.toAffine(P[N])).map(b.fromAffine)}static fromHex(x){const P=b.fromAffine(s(Ze("pointHex",x)));return P.assertValidity(),P}static fromPrivateKey(x){return b.BASE.multiply(f(x))}static msm(x,P){return t8(b,r,x,P)}_setWindowSize(x){D.setWindowSize(this,x)}assertValidity(){p(this)}hasEvenY(){const{y:x}=this.toAffine();if(n.isOdd)return!n.isOdd(x);throw new Error("Field doesn't support isOdd")}equals(x){d(x);const{px:P,py:R,pz:N}=this,{px:F,py:$,pz:z}=x,M=n.eql(n.mul(P,z),n.mul(F,N)),E=n.eql(n.mul(R,z),n.mul($,N));return M&&E}negate(){return new b(this.px,n.neg(this.py),this.pz)}double(){const{a:x,b:P}=e,R=n.mul(P,Wi),{px:N,py:F,pz:$}=this;let z=n.ZERO,M=n.ZERO,E=n.ZERO,y=n.mul(N,N),m=n.mul(F,F),g=n.mul($,$),w=n.mul(N,F);return w=n.add(w,w),E=n.mul(N,$),E=n.add(E,E),z=n.mul(x,E),M=n.mul(R,g),M=n.add(z,M),z=n.sub(m,M),M=n.add(m,M),M=n.mul(z,M),z=n.mul(w,z),E=n.mul(R,E),g=n.mul(x,g),w=n.sub(y,g),w=n.mul(x,w),w=n.add(w,E),E=n.add(y,y),y=n.add(E,y),y=n.add(y,g),y=n.mul(y,w),M=n.add(M,y),g=n.mul(F,$),g=n.add(g,g),y=n.mul(g,w),z=n.sub(z,y),E=n.mul(g,m),E=n.add(E,E),E=n.add(E,E),new b(z,M,E)}add(x){d(x);const{px:P,py:R,pz:N}=this,{px:F,py:$,pz:z}=x;let M=n.ZERO,E=n.ZERO,y=n.ZERO;const m=e.a,g=n.mul(e.b,Wi);let w=n.mul(P,F),S=n.mul(R,$),A=n.mul(N,z),I=n.add(P,R),O=n.add(F,$);I=n.mul(I,O),O=n.add(w,S),I=n.sub(I,O),O=n.add(P,N);let T=n.add(F,z);return O=n.mul(O,T),T=n.add(w,A),O=n.sub(O,T),T=n.add(R,N),M=n.add($,z),T=n.mul(T,M),M=n.add(S,A),T=n.sub(T,M),y=n.mul(m,O),M=n.mul(g,A),y=n.add(M,y),M=n.sub(S,y),y=n.add(S,y),E=n.mul(M,y),S=n.add(w,w),S=n.add(S,w),A=n.mul(m,A),O=n.mul(g,O),S=n.add(S,A),A=n.sub(w,A),A=n.mul(m,A),O=n.add(O,A),w=n.mul(S,O),E=n.add(E,w),w=n.mul(T,O),M=n.mul(I,M),M=n.sub(M,w),w=n.mul(I,S),y=n.mul(T,y),y=n.add(y,w),new b(M,E,y)}subtract(x){return this.add(x.negate())}is0(){return this.equals(b.ZERO)}wNAF(x){return D.wNAFCached(this,x,b.normalizeZ)}multiplyUnsafe(x){const{endo:P,n:R}=e;ci("scalar",x,zt,R);const N=b.ZERO;if(x===zt)return N;if(this.is0()||x===pe)return this;if(!P||D.hasPrecomputes(this))return D.wNAFCachedUnsafe(this,x,b.normalizeZ);let{k1neg:F,k1:$,k2neg:z,k2:M}=P.splitScalar(x),E=N,y=N,m=this;for(;$>zt||M>zt;)$&pe&&(E=E.add(m)),M&pe&&(y=y.add(m)),m=m.double(),$>>=pe,M>>=pe;return F&&(E=E.negate()),z&&(y=y.negate()),y=new b(n.mul(y.px,P.beta),y.py,y.pz),E.add(y)}multiply(x){const{endo:P,n:R}=e;ci("scalar",x,pe,R);let N,F;if(P){const{k1neg:$,k1:z,k2neg:M,k2:E}=P.splitScalar(x);let{p:y,f:m}=this.wNAF(z),{p:g,f:w}=this.wNAF(E);y=D.constTimeNegate($,y),g=D.constTimeNegate(M,g),g=new b(n.mul(g.px,P.beta),g.py,g.pz),N=y.add(g),F=m.add(w)}else{const{p:$,f:z}=this.wNAF(x);N=$,F=z}return b.normalizeZ([N,F])[0]}multiplyAndAddUnsafe(x,P,R){const N=b.BASE,F=(z,M)=>M===zt||M===pe||!z.equals(N)?z.multiplyUnsafe(M):z.multiply(M),$=F(this,P).add(F(x,R));return $.is0()?void 0:$}toAffine(x){return h(this,x)}isTorsionFree(){const{h:x,isTorsionFree:P}=e;if(x===pe)return!0;if(P)return P(b,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:x,clearCofactor:P}=e;return x===pe?this:P?P(b,this):this.multiplyUnsafe(e.h)}toRawBytes(x=!0){return Hi("isCompressed",x),this.assertValidity(),i(b,this,x)}toHex(x=!0){return Hi("isCompressed",x),$r(this.toRawBytes(x))}}b.BASE=new b(e.Gx,e.Gy,n.ONE),b.ZERO=new b(n.ZERO,n.ONE,n.ZERO);const{endo:v,nBitLength:B}=e,D=e8(b,v?Math.ceil(B/2):B);return{CURVE:e,ProjectivePoint:b,normPrivateKeyToScalar:f,weierstrassEquation:o,isWithinCurveOrder:l}}function i8(t){const e=Od(t);return Ki(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function s8(t){const e=i8(t),{Fp:n,n:r,nByteLength:i,nBitLength:s}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(g){return ot(g,r)}function u(g){return $c(g,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:d,isWithinCurveOrder:h}=kc({...e,toBytes(g,w,S){const A=w.toAffine(),I=n.toBytes(A.x),O=_e;return Hi("isCompressed",S),S?O(Uint8Array.from([w.hasEvenY()?2:3]),I):O(Uint8Array.from([4]),I,n.toBytes(A.y))},fromBytes(g){const w=g.length,S=g[0],A=g.subarray(1);if(w===o&&(S===2||S===3)){const I=it(A);if(!mc(I,pe,n.ORDER))throw new Error("Point is not on curve");const O=d(I);let T;try{T=n.sqrt(O)}catch(k){const C=k instanceof Error?": "+k.message:"";throw new Error("Point is not on curve"+C)}const L=(T&pe)===pe;return(S&1)===1!==L&&(T=n.neg(T)),{x:I,y:T}}else if(w===a&&S===4){const I=n.fromBytes(A.subarray(0,n.BYTES)),O=n.fromBytes(A.subarray(n.BYTES,2*n.BYTES));return{x:I,y:O}}else{const I=o,O=a;throw new Error("invalid Point, expected length of "+I+", or uncompressed "+O+", got "+w)}}});function p(g){const w=r>>pe;return g>w}function b(g){return p(g)?c(-g):g}const v=(g,w,S)=>it(g.slice(w,S));class B{constructor(w,S,A){ci("r",w,pe,r),ci("s",S,pe,r),this.r=w,this.s=S,A!=null&&(this.recovery=A),Object.freeze(this)}static fromCompact(w){const S=i;return w=Ze("compactSignature",w,S*2),new B(v(w,0,S),v(w,S,2*S))}static fromDER(w){const{r:S,s:A}=En.toSig(Ze("DER",w));return new B(S,A)}assertValidity(){}addRecoveryBit(w){return new B(this.r,this.s,w)}recoverPublicKey(w){const{r:S,s:A,recovery:I}=this,O=N(Ze("msgHash",w));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const T=I===2||I===3?S+e.n:S;if(T>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=I&1?"03":"02",U=l.fromHex(L+Fc(T,n.BYTES)),k=u(T),C=c(-O*k),q=c(A*k),j=l.BASE.multiplyAndAddUnsafe(U,C,q);if(!j)throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new B(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ho(this.toDERHex())}toDERHex(){return En.hexFromSig(this)}toCompactRawBytes(){return ho(this.toCompactHex())}toCompactHex(){const w=i;return Fc(this.r,w)+Fc(this.s,w)}}const D={isValidPrivateKey(g){try{return f(g),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const g=Pc(e.n);return _d(e.randomBytes(g),e.n)},precompute(g=8,w=l.BASE){return w._setWindowSize(g),w.multiply(BigInt(3)),w}};function _(g,w=!0){return l.fromPrivateKey(g).toRawBytes(w)}function x(g){if(typeof g=="bigint")return!1;if(g instanceof l)return!0;const S=Ze("key",g).length,A=n.BYTES,I=A+1,O=2*A+1;if(!(e.allowedPrivateKeyLengths||i===I))return S===I||S===O}function P(g,w,S=!0){if(x(g)===!0)throw new Error("first arg must be private key");if(x(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(f(g)).toRawBytes(S)}const R=e.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const w=it(g),S=g.length*8-s;return S>0?w>>BigInt(S):w},N=e.bits2int_modN||function(g){return c(R(g))},F=Pr(s);function $(g){return ci("num < 2^"+s,g,zt,F),Oe(g,i)}function z(g,w,S=M){if(["recovered","canonical"].some(V=>V in S))throw new Error("sign() legacy options not supported");const{hash:A,randomBytes:I}=e;let{lowS:O,prehash:T,extraEntropy:L}=S;O==null&&(O=!0),g=Ze("msgHash",g),Dd(S),T&&(g=Ze("prehashed msgHash",A(g)));const U=N(g),k=f(w),C=[$(k),$(U)];if(L!=null&&L!==!1){const V=L===!0?I(n.BYTES):L;C.push(Ze("extraEntropy",V))}const q=_e(...C),j=U;function W(V){const Z=R(V);if(!h(Z))return;const Q=u(Z),ee=l.BASE.multiply(Z).toAffine(),ie=c(ee.x);if(ie===zt)return;const he=c(Q*c(j+ie*k));if(he===zt)return;let ve=(ee.x===ie?0:2)|Number(ee.y&pe),Fn=he;return O&&p(he)&&(Fn=b(he),ve^=1),new B(ie,Fn,ve)}return{seed:q,k2sig:W}}const M={lowS:e.lowS,prehash:!1},E={lowS:e.lowS,prehash:!1};function y(g,w,S=M){const{seed:A,k2sig:I}=z(g,w,S),O=e;return nE(O.hash.outputLen,O.nByteLength,O.hmac)(A,I)}l.BASE._setWindowSize(8);function m(g,w,S,A=E){const I=g;w=Ze("msgHash",w),S=Ze("publicKey",S);const{lowS:O,prehash:T,format:L}=A;if(Dd(A),"strict"in A)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 U=typeof I=="string"||zi(I),k=!U&&!L&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!U&&!k)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let C,q;try{if(k&&(C=new B(I.r,I.s)),U){try{L!=="compact"&&(C=B.fromDER(I))}catch(ve){if(!(ve instanceof En.Err))throw ve}!C&&L!=="der"&&(C=B.fromCompact(I))}q=l.fromHex(S)}catch{return!1}if(!C||O&&C.hasHighS())return!1;T&&(w=e.hash(w));const{r:j,s:W}=C,V=N(w),Z=u(W),Q=c(V*Z),ee=c(j*Z),ie=l.BASE.multiplyAndAddUnsafe(q,Q,ee)?.toAffine();return ie?c(ie.x)===j:!1}return{CURVE:e,getPublicKey:_,getSharedSecret:P,sign:y,verify:m,ProjectivePoint:l,Signature:B,utils:D}}function o8(t,e){const n=t.ORDER;let r=zt;for(let p=n-pe;p%Kn===zt;p/=Kn)r+=pe;const i=r,s=Kn<<i-pe-pe,o=s*Kn,a=(n-pe)/o,c=(a-pe)/Kn,u=o-pe,l=s,f=t.pow(e,a),d=t.pow(e,(a+pe)/Kn);let h=(p,b)=>{let v=f,B=t.pow(b,u),D=t.sqr(B);D=t.mul(D,b);let _=t.mul(p,D);_=t.pow(_,c),_=t.mul(_,B),B=t.mul(_,b),D=t.mul(_,p);let x=t.mul(D,B);_=t.pow(x,l);let P=t.eql(_,t.ONE);B=t.mul(D,d),_=t.mul(x,v),D=t.cmov(B,D,P),x=t.cmov(_,x,P);for(let R=i;R>pe;R--){let N=R-Kn;N=Kn<<N-pe;let F=t.pow(x,N);const $=t.eql(F,t.ONE);B=t.mul(D,v),v=t.mul(v,v),F=t.mul(x,v),D=t.cmov(B,D,$),x=t.cmov(F,x,$)}return{isValid:P,value:D}};if(t.ORDER%Lc===Wi){const p=(t.ORDER-Wi)/Lc,b=t.sqrt(t.neg(e));h=(v,B)=>{let D=t.sqr(B);const _=t.mul(v,B);D=t.mul(D,_);let x=t.pow(D,p);x=t.mul(x,_);const P=t.mul(x,b),R=t.mul(t.sqr(x),B),N=t.eql(R,v);let F=t.cmov(P,x,N);return{isValid:N,value:F}}}return h}function $d(t,e){if(vd(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=o8(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,u,l,f;i=t.sqr(r),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:d,value:h}=n(s,u);f=t.mul(i,r),f=t.mul(f,h),l=t.cmov(l,o,d),f=t.cmov(f,h,d);const p=t.isOdd(r)===t.isOdd(f);f=t.cmov(t.neg(f),f,p);const b=Rr(t,[a],!0)[0];return l=t.mul(l,b),{x:l,y:f}}}function a8(t){return{hash:t,hmac:(e,...n)=>gd(t,e,x3(...n)),randomBytes:Ch}}function mo(t,e){const n=r=>s8({...t,...a8(r)});return{...n(e),create:n}}const c8=it;function Gn(t,e){if(Zi(t),Zi(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function u8(t,e){const n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function Zi(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function l8(t,e,n,r){Hn(t),Hn(e),Zi(n),e.length>255&&(e=r(_e(bc("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=_e(e,Gn(e.length,1)),c=Gn(0,s),u=Gn(n,2),l=new Array(o),f=r(_e(c,t,u,Gn(0,1),a));l[0]=r(_e(f,Gn(1,1),a));for(let h=1;h<=o;h++){const p=[u8(f,l[h-1]),Gn(h+1,1),a];l[h]=r(_e(...p))}return _e(...l).slice(0,n)}function f8(t,e,n,r,i){if(Hn(t),Hn(e),Zi(n),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(bc("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(t).update(Gn(n,2)).update(e).update(Gn(e.length,1)).digest()}function Pd(t,e,n){Ki(n,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;Hn(t),Zi(e);const u=typeof c=="string"?bc(c):c,l=r.toString(2).length,f=Math.ceil((l+i)/8),d=e*s*f;let h;if(a==="xmd")h=l8(t,u,d,o);else if(a==="xof")h=f8(t,u,d,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const p=new Array(e);for(let b=0;b<e;b++){const v=new Array(s);for(let B=0;B<s;B++){const D=f*(B+b*s),_=h.subarray(D,D+f);v[B]=ot(c8(_),r)}p[b]=v}return p}function Td(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(f=>f.reduce((d,h)=>t.add(t.mul(d,r),h))),[u,l]=Rr(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}function Rd(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(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:n,hashToCurve(s,o){const a=Pd(s,2,{...n,DST:n.DST,...o}),c=r(a[0]),u=r(a[1]);return i(c.add(u))},encodeToCurve(s,o){const a=Pd(s,1,{...n,DST:n.encodeDST,...o});return i(r(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(r(s))}}}const Nd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Cd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h8=BigInt(0),d8=BigInt(1),qc=BigInt(2),Ud=(t,e)=>(t+e/qc)/e;function p8(t){const e=Nd,n=BigInt(3),r=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=Pt(l,n,e)*l%e,d=Pt(f,n,e)*l%e,h=Pt(d,qc,e)*u%e,p=Pt(h,i,e)*h%e,b=Pt(p,s,e)*p%e,v=Pt(b,a,e)*b%e,B=Pt(v,c,e)*v%e,D=Pt(B,a,e)*b%e,_=Pt(D,n,e)*l%e,x=Pt(_,o,e)*p%e,P=Pt(x,r,e)*u%e,R=Pt(P,qc,e);if(!Mc.eql(Mc.sqr(R),t))throw new Error("Cannot find square root");return R}const Mc=Vn(Nd,void 0,void 0,{sqrt:p8}),g8=mo({a:h8,b:BigInt(7),Fp:Mc,n:Cd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Cd,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-d8*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Ud(s*t,e),c=Ud(-r*t,e);let u=ot(t-a*n-c*i,e),l=ot(-a*r-c*s,e);const f=u>o,d=l>o;if(f&&(u=e-u),d&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},uo);function y8(t){if(t.length!==130&&t.length!==132)throw new w8({signature:t});const e=BigInt(mn(t,0,32)),n=BigInt(mn(t,32,64)),r=(()=>{const i=+`0x${t.slice(130)}`;if(!Number.isNaN(i))try{return b8(i)}catch{throw new m8({value:i})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function b8(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new v8({value:t})}class w8 extends ge{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${vn(Ic(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class m8 extends ge{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class v8 extends ge{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}Object.freeze({1:0n,2:1n,3:2n,4:3n,5:4n,6:5n,7:6n,8:7n,9:8n,A:9n,B:10n,C:11n,D:12n,E:13n,F:14n,G:15n,H:16n,J:17n,K:18n,L:19n,M:20n,N:21n,P:22n,Q:23n,R:24n,S:25n,T:26n,U:27n,V:28n,W:29n,X:30n,Y:31n,Z:32n,a:33n,b:34n,c:35n,d:36n,e:37n,f:38n,g:39n,h:40n,i:41n,j:42n,k:43n,m:44n,n:45n,o:46n,p:47n,q:48n,r:49n,s:50n,t:51n,u:52n,v:53n,w:54n,x:55n,y:56n,z:57n}),Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[e,t.charCodeAt(0)]),{...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[t.charCodeAt(0),e])),["=".charCodeAt(0)]:0,["-".charCodeAt(0)]:0,["_".charCodeAt(0)]:0},gn.slice();const E8=BigInt(0),vo=BigInt(1),Fd=BigInt(2),ui=BigInt(3);function x8(t){const e=[];for(;t>vo;t>>=vo)(t&vo)===E8?e.unshift(0):(t&ui)===ui?(e.unshift(-1),t+=vo):e.unshift(1);return e}function _8(t){const{Fp:e,Fr:n,Fp2:r,Fp6:i,Fp12:s}=t.fields,o=t.params.xNegative,a=t.params.twistType,c=kc({n:n.ORDER,...t.G1}),u=Object.assign(c,Rd(c.ProjectivePoint,t.G1.mapToCurve,{...t.htfDefaults,...t.G1.htfDefaults})),l=kc({n:n.ORDER,...t.G2}),f=Object.assign(l,Rd(l.ProjectivePoint,t.G2.mapToCurve,{...t.htfDefaults,...t.G2.htfDefaults}));let d;if(a==="multiplicative")d=(U,k,C,q,j,W)=>s.mul014(q,U,r.mul(k,j),r.mul(C,W));else if(a==="divisive")d=(U,k,C,q,j,W)=>s.mul034(q,r.mul(C,W),r.mul(k,j),U);else throw new Error("bls: unknown twist type");const h=r.div(r.ONE,r.mul(r.ONE,Fd));function p(U,k,C,q){const j=r.sqr(C),W=r.sqr(q),V=r.mulByB(r.mul(W,ui)),Z=r.mul(V,ui),Q=r.sub(r.sub(r.sqr(r.add(C,q)),W),j),ee=r.sub(V,j),ie=r.mul(r.sqr(k),ui),he=r.neg(Q);return U.push([ee,ie,he]),k=r.mul(r.mul(r.mul(r.sub(j,Z),k),C),h),C=r.sub(r.sqr(r.mul(r.add(j,Z),h)),r.mul(r.sqr(V),ui)),q=r.mul(j,Q),{Rx:k,Ry:C,Rz:q}}function b(U,k,C,q,j,W){const V=r.sub(C,r.mul(W,q)),Z=r.sub(k,r.mul(j,q)),Q=r.sub(r.mul(V,j),r.mul(Z,W)),ee=r.neg(V),ie=Z;U.push([Q,ee,ie]);const he=r.sqr(Z),ve=r.mul(he,Z),Fn=r.mul(he,k),Ba=r.add(r.sub(ve,r.mul(Fn,Fd)),r.mul(r.sqr(V),q));return k=r.mul(Z,Ba),C=r.sub(r.mul(r.sub(Fn,Ba),V),r.mul(ve,C)),q=r.mul(q,ve),{Rx:k,Ry:C,Rz:q}}const v=x8(t.params.ateLoopSize),B=Ec(U=>{const k=U,{x:C,y:q}=k.toAffine(),j=C,W=q,V=r.neg(q);let Z=j,Q=W,ee=r.ONE;const ie=[];for(const he of v){const ve=[];({Rx:Z,Ry:Q,Rz:ee}=p(ve,Z,Q,ee)),he&&({Rx:Z,Ry:Q,Rz:ee}=b(ve,Z,Q,ee,j,he===-1?V:W)),ie.push(ve)}if(t.postPrecompute){const he=ie[ie.length-1];t.postPrecompute(Z,Q,ee,j,W,b.bind(null,he))}return ie});function D(U,k=!1){let C=s.ONE;if(U.length){const q=U[0][0].length;for(let j=0;j<q;j++){C=s.sqr(C);for(const[W,V,Z]of U)for(const[Q,ee,ie]of W[j])C=d(Q,ee,ie,C,V,Z)}}return o&&(C=s.conjugate(C)),k?s.finalExponentiate(C):C}function _(U,k=!0){const C=[];u.ProjectivePoint.normalizeZ(U.map(({g1:q})=>q)),f.ProjectivePoint.normalizeZ(U.map(({g2:q})=>q));for(const{g1:q,g2:j}of U){if(q.equals(u.ProjectivePoint.ZERO)||j.equals(f.ProjectivePoint.ZERO))throw new Error("pairing is not available for ZERO point");q.assertValidity(),j.assertValidity();const W=q.toAffine();C.push([B(j),W.x,W.y])}return D(C,k)}function x(U,k,C=!0){return _([{g1:U,g2:k}],C)}const P={randomPrivateKey:()=>{const U=Pc(n.ORDER);return _d(t.randomBytes(U),n.ORDER)},calcPairingPrecomputes:B},{ShortSignature:R}=t.G1,{Signature:N}=t.G2;function F(U){return U instanceof u.ProjectivePoint?U:u.ProjectivePoint.fromHex(U)}function $(U,k){return U instanceof u.ProjectivePoint?U:u.hashToCurve(Ze("point",U),k)}function z(U){return U instanceof f.ProjectivePoint?U:N.fromHex(U)}function M(U,k){return U instanceof f.ProjectivePoint?U:f.hashToCurve(Ze("point",U),k)}function E(U){return u.ProjectivePoint.fromPrivateKey(U).toRawBytes(!0)}function y(U){return f.ProjectivePoint.fromPrivateKey(U).toRawBytes(!0)}function m(U,k,C){const q=M(U,C);q.assertValidity();const j=q.multiply(u.normPrivateKeyToScalar(k));return U instanceof f.ProjectivePoint?j:N.toRawBytes(j)}function g(U,k,C){const q=$(U,C);q.assertValidity();const j=q.multiply(u.normPrivateKeyToScalar(k));return U instanceof u.ProjectivePoint?j:R.toRawBytes(j)}function w(U,k,C,q){const j=F(C),W=M(k,q),V=u.ProjectivePoint.BASE,Z=z(U),Q=_([{g1:j.negate(),g2:W},{g1:V,g2:Z}]);return s.eql(Q,s.ONE)}function S(U,k,C,q){const j=z(C),W=$(k,q),V=f.ProjectivePoint.BASE,Z=F(U),Q=_([{g1:W,g2:j},{g1:Z,g2:V.negate()}]);return s.eql(Q,s.ONE)}function A(U){if(!Array.isArray(U)||U.length===0)throw new Error("expected non-empty array")}function I(U){A(U);const C=U.map(F).reduce((q,j)=>q.add(j),u.ProjectivePoint.ZERO);return U[0]instanceof u.ProjectivePoint?(C.assertValidity(),C):C.toRawBytes(!0)}function O(U){A(U);const C=U.map(z).reduce((q,j)=>q.add(j),f.ProjectivePoint.ZERO);return U[0]instanceof f.ProjectivePoint?(C.assertValidity(),C):N.toRawBytes(C)}function T(U){A(U);const C=U.map(F).reduce((q,j)=>q.add(j),u.ProjectivePoint.ZERO);return U[0]instanceof u.ProjectivePoint?(C.assertValidity(),C):R.toRawBytes(C)}function L(U,k,C,q){if(A(k),C.length!==k.length)throw new Error("amount of public keys and messages should be equal");const j=z(U),W=k.map(ee=>M(ee,q)),V=C.map(F),Z=new Map;for(let ee=0;ee<V.length;ee++){const ie=V[ee],he=W[ee];let ve=Z.get(he);ve===void 0&&(ve=[],Z.set(he,ve)),ve.push(ie)}const Q=[];try{for(const[ee,ie]of Z){const he=ie.reduce((ve,Fn)=>ve.add(Fn));Q.push({g1:he,g2:ee})}return Q.push({g1:u.ProjectivePoint.BASE.negate(),g2:j}),s.eql(_(Q),s.ONE)}catch{return!1}}return u.ProjectivePoint.BASE._setWindowSize(4),{getPublicKey:E,getPublicKeyForShortSignatures:y,sign:m,signShortSignature:g,verify:w,verifyBatch:L,verifyShortSignature:S,aggregatePublicKeys:I,aggregateSignatures:O,aggregateShortSignatures:T,millerLoopBatch:D,pairing:x,pairingBatch:_,G1:u,G2:f,Signature:N,ShortSignature:R,fields:{Fr:n,Fp:e,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:t.params.ateLoopSize,r:t.params.r,G1b:t.G1.b,G2b:t.G2.b},utils:P}}const S8=BigInt(0),li=BigInt(1),xn=BigInt(2),Ld=BigInt(3);function jc(t,e,n,r,i=1,s){const o=BigInt(s===void 0?r:s),a=n**BigInt(r),c=[];for(let u=0;u<i;u++){const l=BigInt(u+1),f=[];for(let d=0,h=li;d<r;d++){const p=(l*h-l)/o%a;f.push(t.pow(e,p)),h*=n}c.push(f)}return c}function I8(t,e,n){const r=e.pow(n,(t.ORDER-li)/Ld),i=e.pow(n,(t.ORDER-li)/xn);function s(d,h){const p=e.mul(e.frobeniusMap(d,1),r),b=e.mul(e.frobeniusMap(h,1),i);return[p,b]}const o=e.pow(n,(t.ORDER**xn-li)/Ld),a=e.pow(n,(t.ORDER**xn-li)/xn);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(d,h){return[e.mul(d,o),e.neg(h)]}const u=d=>(h,p)=>{const b=p.toAffine(),v=d(b.x,b.y);return h.fromAffine({x:v[0],y:v[1]})},l=u(s),f=u(c);return{psi:s,psi2:c,G2psi:l,G2psi2:f,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:a}}function A8(t){const{ORDER:e}=t,n=Vn(e),r=n.create(t.NONRESIDUE||BigInt(-1)),i=n.div(n.ONE,xn),s=jc(n,r,n.ORDER,2)[0],o=({c0:E,c1:y},{c0:m,c1:g})=>({c0:n.add(E,m),c1:n.add(y,g)}),a=({c0:E,c1:y},{c0:m,c1:g})=>({c0:n.sub(E,m),c1:n.sub(y,g)}),c=({c0:E,c1:y},m)=>{if(typeof m=="bigint")return{c0:n.mul(E,m),c1:n.mul(y,m)};const{c0:g,c1:w}=m;let S=n.mul(E,g),A=n.mul(y,w);const I=n.sub(S,A),O=n.sub(n.mul(n.add(E,y),n.add(g,w)),n.add(S,A));return{c0:I,c1:O}},u=({c0:E,c1:y})=>{const m=n.add(E,y),g=n.sub(E,y),w=n.add(E,E);return{c0:n.mul(m,g),c1:n.mul(w,y)}},l=E=>{if(E.length!==2)throw new Error("invalid tuple");const y=E.map(m=>n.create(m));return{c0:y[0],c1:y[1]}},f=e*e,d=l(t.FP2_NONRESIDUE),h={ORDER:f,isLE:n.isLE,NONRESIDUE:d,BITS:Vi(f),BYTES:Math.ceil(Vi(f)/8),MASK:Pr(Vi(f)),ZERO:{c0:n.ZERO,c1:n.ZERO},ONE:{c0:n.ONE,c1:n.ZERO},create:E=>E,isValid:({c0:E,c1:y})=>typeof E=="bigint"&&typeof y=="bigint",is0:({c0:E,c1:y})=>n.is0(E)&&n.is0(y),eql:({c0:E,c1:y},{c0:m,c1:g})=>n.eql(E,m)&&n.eql(y,g),neg:({c0:E,c1:y})=>({c0:n.neg(E),c1:n.neg(y)}),pow:(E,y)=>bo(h,E,y),invertBatch:E=>Rr(h,E),add:o,sub:a,mul:c,sqr:u,addN:o,subN:a,mulN:c,sqrN:u,div:(E,y)=>h.mul(E,typeof y=="bigint"?n.inv(n.create(y)):h.inv(y)),inv:({c0:E,c1:y})=>{const m=n.inv(n.create(E*E+y*y));return{c0:n.mul(m,n.create(E)),c1:n.mul(m,n.create(-y))}},sqrt:E=>{if(t.Fp2sqrt)return t.Fp2sqrt(E);const{c0:y,c1:m}=E;if(n.is0(m))return wo(n,y)===1?h.create({c0:n.sqrt(y),c1:n.ZERO}):h.create({c0:n.ZERO,c1:n.sqrt(n.div(y,r))});const g=n.sqrt(n.sub(n.sqr(y),n.mul(n.sqr(m),r)));let w=n.mul(n.add(g,y),i);wo(n,w)===-1&&(w=n.sub(w,g));const A=n.sqrt(w),I=h.create({c0:A,c1:n.div(n.mul(m,i),A)});if(!h.eql(h.sqr(I),E))throw new Error("Cannot find square root");const O=I,T=h.neg(O),{re:L,im:U}=h.reim(O),{re:k,im:C}=h.reim(T);return U>C||U===C&&L>k?O:T},isOdd:E=>{const{re:y,im:m}=h.reim(E),g=y%xn,w=y===S8,S=m%xn;return BigInt(g||w&&S)==li},fromBytes(E){if(E.length!==h.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:n.fromBytes(E.subarray(0,n.BYTES)),c1:n.fromBytes(E.subarray(n.BYTES))}},toBytes:({c0:E,c1:y})=>_e(n.toBytes(E),n.toBytes(y)),cmov:({c0:E,c1:y},{c0:m,c1:g},w)=>({c0:n.cmov(E,m,w),c1:n.cmov(y,g,w)}),reim:({c0:E,c1:y})=>({re:E,im:y}),mulByNonresidue:({c0:E,c1:y})=>h.mul({c0:E,c1:y},d),mulByB:t.Fp2mulByB,fromBigTuple:l,frobeniusMap:({c0:E,c1:y},m)=>({c0:E,c1:n.mul(y,s[m%2])})},p=({c0:E,c1:y,c2:m},{c0:g,c1:w,c2:S})=>({c0:h.add(E,g),c1:h.add(y,w),c2:h.add(m,S)}),b=({c0:E,c1:y,c2:m},{c0:g,c1:w,c2:S})=>({c0:h.sub(E,g),c1:h.sub(y,w),c2:h.sub(m,S)}),v=({c0:E,c1:y,c2:m},g)=>{if(typeof g=="bigint")return{c0:h.mul(E,g),c1:h.mul(y,g),c2:h.mul(m,g)};const{c0:w,c1:S,c2:A}=g,I=h.mul(E,w),O=h.mul(y,S),T=h.mul(m,A);return{c0:h.add(I,h.mulByNonresidue(h.sub(h.mul(h.add(y,m),h.add(S,A)),h.add(O,T)))),c1:h.add(h.sub(h.mul(h.add(E,y),h.add(w,S)),h.add(I,O)),h.mulByNonresidue(T)),c2:h.sub(h.add(O,h.mul(h.add(E,m),h.add(w,A))),h.add(I,T))}},B=({c0:E,c1:y,c2:m})=>{let g=h.sqr(E),w=h.mul(h.mul(E,y),xn),S=h.mul(h.mul(y,m),xn),A=h.sqr(m);return{c0:h.add(h.mulByNonresidue(S),g),c1:h.add(h.mulByNonresidue(A),w),c2:h.sub(h.sub(h.add(h.add(w,h.sqr(h.add(h.sub(E,y),m))),S),g),A)}},[D,_]=jc(h,d,n.ORDER,6,2,3),x={ORDER:h.ORDER,isLE:h.isLE,BITS:3*h.BITS,BYTES:3*h.BYTES,MASK:Pr(3*h.BITS),ZERO:{c0:h.ZERO,c1:h.ZERO,c2:h.ZERO},ONE:{c0:h.ONE,c1:h.ZERO,c2:h.ZERO},create:E=>E,isValid:({c0:E,c1:y,c2:m})=>h.isValid(E)&&h.isValid(y)&&h.isValid(m),is0:({c0:E,c1:y,c2:m})=>h.is0(E)&&h.is0(y)&&h.is0(m),neg:({c0:E,c1:y,c2:m})=>({c0:h.neg(E),c1:h.neg(y),c2:h.neg(m)}),eql:({c0:E,c1:y,c2:m},{c0:g,c1:w,c2:S})=>h.eql(E,g)&&h.eql(y,w)&&h.eql(m,S),sqrt:td,div:(E,y)=>x.mul(E,typeof y=="bigint"?n.inv(n.create(y)):x.inv(y)),pow:(E,y)=>bo(x,E,y),invertBatch:E=>Rr(x,E),add:p,sub:b,mul:v,sqr:B,addN:p,subN:b,mulN:v,sqrN:B,inv:({c0:E,c1:y,c2:m})=>{let g=h.sub(h.sqr(E),h.mulByNonresidue(h.mul(m,y))),w=h.sub(h.mulByNonresidue(h.sqr(m)),h.mul(E,y)),S=h.sub(h.sqr(y),h.mul(E,m)),A=h.inv(h.add(h.mulByNonresidue(h.add(h.mul(m,w),h.mul(y,S))),h.mul(E,g)));return{c0:h.mul(A,g),c1:h.mul(A,w),c2:h.mul(A,S)}},fromBytes:E=>{if(E.length!==x.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:h.fromBytes(E.subarray(0,h.BYTES)),c1:h.fromBytes(E.subarray(h.BYTES,2*h.BYTES)),c2:h.fromBytes(E.subarray(2*h.BYTES))}},toBytes:({c0:E,c1:y,c2:m})=>_e(h.toBytes(E),h.toBytes(y),h.toBytes(m)),cmov:({c0:E,c1:y,c2:m},{c0:g,c1:w,c2:S},A)=>({c0:h.cmov(E,g,A),c1:h.cmov(y,w,A),c2:h.cmov(m,S,A)}),fromBigSix:E=>{if(!Array.isArray(E)||E.length!==6)throw new Error("invalid Fp6 usage");return{c0:h.fromBigTuple(E.slice(0,2)),c1:h.fromBigTuple(E.slice(2,4)),c2:h.fromBigTuple(E.slice(4,6))}},frobeniusMap:({c0:E,c1:y,c2:m},g)=>({c0:h.frobeniusMap(E,g),c1:h.mul(h.frobeniusMap(y,g),D[g%6]),c2:h.mul(h.frobeniusMap(m,g),_[g%6])}),mulByFp2:({c0:E,c1:y,c2:m},g)=>({c0:h.mul(E,g),c1:h.mul(y,g),c2:h.mul(m,g)}),mulByNonresidue:({c0:E,c1:y,c2:m})=>({c0:h.mulByNonresidue(m),c1:E,c2:y}),mul1:({c0:E,c1:y,c2:m},g)=>({c0:h.mulByNonresidue(h.mul(m,g)),c1:h.mul(E,g),c2:h.mul(y,g)}),mul01({c0:E,c1:y,c2:m},g,w){let S=h.mul(E,g),A=h.mul(y,w);return{c0:h.add(h.mulByNonresidue(h.sub(h.mul(h.add(y,m),w),A)),S),c1:h.sub(h.sub(h.mul(h.add(g,w),h.add(E,y)),S),A),c2:h.add(h.sub(h.mul(h.add(E,m),g),S),A)}}},P=jc(h,d,n.ORDER,12,1,6)[0],R=({c0:E,c1:y},{c0:m,c1:g})=>({c0:x.add(E,m),c1:x.add(y,g)}),N=({c0:E,c1:y},{c0:m,c1:g})=>({c0:x.sub(E,m),c1:x.sub(y,g)}),F=({c0:E,c1:y},m)=>{if(typeof m=="bigint")return{c0:x.mul(E,m),c1:x.mul(y,m)};let{c0:g,c1:w}=m,S=x.mul(E,g),A=x.mul(y,w);return{c0:x.add(S,x.mulByNonresidue(A)),c1:x.sub(x.mul(x.add(E,y),x.add(g,w)),x.add(S,A))}},$=({c0:E,c1:y})=>{let m=x.mul(E,y);return{c0:x.sub(x.sub(x.mul(x.add(x.mulByNonresidue(y),E),x.add(E,y)),m),x.mulByNonresidue(m)),c1:x.add(m,m)}};function z(E,y){const m=h.sqr(E),g=h.sqr(y);return{first:h.add(h.mulByNonresidue(g),m),second:h.sub(h.sub(h.sqr(h.add(E,y)),m),g)}}const M={ORDER:h.ORDER,isLE:x.isLE,BITS:2*x.BITS,BYTES:2*x.BYTES,MASK:Pr(2*x.BITS),ZERO:{c0:x.ZERO,c1:x.ZERO},ONE:{c0:x.ONE,c1:x.ZERO},create:E=>E,isValid:({c0:E,c1:y})=>x.isValid(E)&&x.isValid(y),is0:({c0:E,c1:y})=>x.is0(E)&&x.is0(y),neg:({c0:E,c1:y})=>({c0:x.neg(E),c1:x.neg(y)}),eql:({c0:E,c1:y},{c0:m,c1:g})=>x.eql(E,m)&&x.eql(y,g),sqrt:td,inv:({c0:E,c1:y})=>{let m=x.inv(x.sub(x.sqr(E),x.mulByNonresidue(x.sqr(y))));return{c0:x.mul(E,m),c1:x.neg(x.mul(y,m))}},div:(E,y)=>M.mul(E,typeof y=="bigint"?n.inv(n.create(y)):M.inv(y)),pow:(E,y)=>bo(M,E,y),invertBatch:E=>Rr(M,E),add:R,sub:N,mul:F,sqr:$,addN:R,subN:N,mulN:F,sqrN:$,fromBytes:E=>{if(E.length!==M.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:x.fromBytes(E.subarray(0,x.BYTES)),c1:x.fromBytes(E.subarray(x.BYTES))}},toBytes:({c0:E,c1:y})=>_e(x.toBytes(E),x.toBytes(y)),cmov:({c0:E,c1:y},{c0:m,c1:g},w)=>({c0:x.cmov(E,m,w),c1:x.cmov(y,g,w)}),fromBigTwelve:E=>({c0:x.fromBigSix(E.slice(0,6)),c1:x.fromBigSix(E.slice(6,12))}),frobeniusMap(E,y){const{c0:m,c1:g,c2:w}=x.frobeniusMap(E.c1,y),S=P[y%12];return{c0:x.frobeniusMap(E.c0,y),c1:x.create({c0:h.mul(m,S),c1:h.mul(g,S),c2:h.mul(w,S)})}},mulByFp2:({c0:E,c1:y},m)=>({c0:x.mulByFp2(E,m),c1:x.mulByFp2(y,m)}),conjugate:({c0:E,c1:y})=>({c0:E,c1:x.neg(y)}),mul014:({c0:E,c1:y},m,g,w)=>{let S=x.mul01(E,m,g),A=x.mul1(y,w);return{c0:x.add(x.mulByNonresidue(A),S),c1:x.sub(x.sub(x.mul01(x.add(y,E),m,h.add(g,w)),S),A)}},mul034:({c0:E,c1:y},m,g,w)=>{const S=x.create({c0:h.mul(E.c0,m),c1:h.mul(E.c1,m),c2:h.mul(E.c2,m)}),A=x.mul01(y,g,w),I=x.mul01(x.add(E,y),h.add(m,g),w);return{c0:x.add(x.mulByNonresidue(A),S),c1:x.sub(I,x.add(S,A))}},_cyclotomicSquare:t.Fp12cyclotomicSquare,_cyclotomicExp:t.Fp12cyclotomicExp,finalExponentiate:t.Fp12finalExponentiate};return{Fp:n,Fp2:h,Fp6:x,Fp4Square:z,Fp12:M}}const at=BigInt(0),Eo=BigInt(1),Ne=BigInt(2),xo=BigInt(3),Yi=BigInt(4),Wn=BigInt("0xd201000000010000"),B8=Vi(Wn),{Fp:X,Fp2:J,Fp6:zc,Fp4Square:Hc,Fp12:re}=A8({ORDER:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),FP2_NONRESIDUE:[Eo,Eo],Fp2mulByB:({c0:t,c1:e})=>{const n=X.mul(t,Yi),r=X.mul(e,Yi);return{c0:X.sub(n,r),c1:X.add(n,r)}},Fp12cyclotomicSquare:({c0:t,c1:e})=>{const{c0:n,c1:r,c2:i}=t,{c0:s,c1:o,c2:a}=e,{first:c,second:u}=Hc(n,o),{first:l,second:f}=Hc(s,i),{first:d,second:h}=Hc(r,a),p=J.mulByNonresidue(h);return{c0:zc.create({c0:J.add(J.mul(J.sub(c,n),Ne),c),c1:J.add(J.mul(J.sub(l,r),Ne),l),c2:J.add(J.mul(J.sub(d,i),Ne),d)}),c1:zc.create({c0:J.add(J.mul(J.add(p,s),Ne),p),c1:J.add(J.mul(J.add(u,o),Ne),u),c2:J.add(J.mul(J.add(f,a),Ne),f)})}},Fp12cyclotomicExp(t,e){let n=re.ONE;for(let r=B8-1;r>=0;r--)n=re._cyclotomicSquare(n),tE(e,r)&&(n=re.mul(n,t));return n},Fp12finalExponentiate:t=>{const e=Wn,n=re.div(re.frobeniusMap(t,6),t),r=re.mul(re.frobeniusMap(n,2),n),i=re.conjugate(re._cyclotomicExp(r,e)),s=re.mul(re.conjugate(re._cyclotomicSquare(r)),i),o=re.conjugate(re._cyclotomicExp(s,e)),a=re.conjugate(re._cyclotomicExp(o,e)),c=re.mul(re.conjugate(re._cyclotomicExp(a,e)),re._cyclotomicSquare(i)),u=re.conjugate(re._cyclotomicExp(c,e)),l=re.frobeniusMap(re.mul(i,a),2),f=re.frobeniusMap(re.mul(o,r),3),d=re.frobeniusMap(re.mul(c,re.conjugate(r)),1),h=re.mul(re.mul(u,re.conjugate(s)),r);return re.mul(re.mul(re.mul(l,f),d),h)}}),kd=Vn(BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")),O8=Td(J,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(t=>t.map(e=>J.fromBigTuple(e.map(BigInt))))),D8=Td(X,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),$8=$d(J,{A:J.create({c0:X.create(at),c1:X.create(BigInt(240))}),B:J.create({c0:X.create(BigInt(1012)),c1:X.create(BigInt(1012))}),Z:J.create({c0:X.create(BigInt(-2)),c1:X.create(BigInt(-1))})}),P8=$d(X,{A:X.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:X.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:X.create(BigInt(11))}),{G2psi:qd,G2psi2:T8}=I8(X,J,J.div(J.ONE,J.NONRESIDUE)),Vc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:X.ORDER,m:2,k:128,expand:"xmd",hash:uo}),_o=Xi(X.toBytes(at),{infinity:!0,compressed:!0});function So(t){t=t.slice();const e=t[0]&224,n=!!(e>>7&1),r=!!(e>>6&1),i=!!(e>>5&1);return t[0]&=31,{compressed:n,infinity:r,sort:i,value:t}}function Xi(t,e){if(t[0]&224)throw new Error("setMask: non-empty mask");return e.compressed&&(t[0]|=128),e.infinity&&(t[0]|=64),e.sort&&(t[0]|=32),t}function Md(t){t.assertValidity();const e=t.equals(Ht.G1.ProjectivePoint.ZERO),{x:n,y:r}=t.toAffine();if(e)return _o.slice();const i=X.ORDER,s=!!(r*Ne/i);return Xi(Oe(n,X.BYTES),{compressed:!0,sort:s})}function jd(t){t.assertValidity();const e=X.BYTES;if(t.equals(Ht.G2.ProjectivePoint.ZERO))return _e(_o,Oe(at,e));const{x:n,y:r}=t.toAffine(),{re:i,im:s}=J.reim(n),{re:o,im:a}=J.reim(r),u=!!((a>at?a*Ne:o*Ne)/X.ORDER&Eo),l=i;return _e(Xi(Oe(s,e),{sort:u,compressed:!0}),Oe(l,e))}const Ht=_8({fields:{Fp:X,Fp2:J,Fp6:zc,Fp12:re,Fr:kd},G1:{Fp:X,h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"),a:X.ZERO,b:Yi,htfDefaults:{...Vc,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(t,e)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new t(X.mul(e.px,n),e.py,e.pz);return e.multiplyUnsafe(Wn).negate().multiplyUnsafe(Wn).equals(r)},clearCofactor:(t,e)=>e.multiplyUnsafe(Wn).add(e),mapToCurve:t=>{const{x:e,y:n}=P8(X.create(t[0]));return D8(e,n)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=So(t);if(i.length===48&&e){const s=X.ORDER,o=it(i),a=X.create(o&X.MASK);if(n){if(a!==at)throw new Error("G1: non-empty compressed point at infinity");return{x:at,y:at}}const c=X.add(X.pow(a,xo),X.create(Ht.params.G1b));let u=X.sqrt(c);if(!u)throw new Error("invalid compressed G1 point");return u*Ne/s!==BigInt(r)&&(u=X.neg(u)),{x:X.create(a),y:X.create(u)}}else if(i.length===96&&!e){const s=it(i.subarray(0,X.BYTES)),o=it(i.subarray(X.BYTES));if(n){if(s!==at||o!==at)throw new Error("G1: non-empty point at infinity");return Ht.G1.ProjectivePoint.ZERO.toAffine()}return{x:X.create(s),y:X.create(o)}}else throw new Error("invalid point G1, expected 48/96 bytes")},toBytes:(t,e,n)=>{const r=e.equals(t.ZERO),{x:i,y:s}=e.toAffine();if(n){if(r)return _o.slice();const o=X.ORDER,a=!!(s*Ne/o);return Xi(Oe(i,X.BYTES),{compressed:!0,sort:a})}else return r?_e(new Uint8Array([64]),new Uint8Array(2*X.BYTES-1)):_e(Oe(i,X.BYTES),Oe(s,X.BYTES))},ShortSignature:{fromHex(t){const{infinity:e,sort:n,value:r}=So(Ze("signatureHex",t,48)),i=X.ORDER,s=it(r);if(e)return Ht.G1.ProjectivePoint.ZERO;const o=X.create(s&X.MASK),a=X.add(X.pow(o,xo),X.create(Ht.params.G1b));let c=X.sqrt(a);if(!c)throw new Error("invalid compressed G1 point");const u=BigInt(n);c*Ne/i!==u&&(c=X.neg(c));const l=Ht.G1.ProjectivePoint.fromAffine({x:o,y:c});return l.assertValidity(),l},toRawBytes(t){return Md(t)},toHex(t){return $r(Md(t))}}},G2:{Fp:J,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),Gx:J.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:J.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")]),a:J.ZERO,b:J.fromBigTuple([Yi,Yi]),hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Vc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:t=>{const{x:e,y:n}=$8(J.fromBigTuple(t));return O8(e,n)},isTorsionFree:(t,e)=>e.multiplyUnsafe(Wn).negate().equals(qd(t,e)),clearCofactor:(t,e)=>{const n=Wn;let r=e.multiplyUnsafe(n).negate(),i=qd(t,e),s=e.double();return s=T8(t,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(e)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=So(t);if(!e&&!n&&r||!e&&n&&r||r&&n&&e)throw new Error("invalid encoding flag: "+(t[0]&224));const s=X.BYTES,o=(a,c,u)=>it(a.slice(c,u));if(i.length===96&&e){const a=Ht.params.G2b,c=X.ORDER;if(n){if(i.reduce((b,v)=>b!==0?v+1:v,0)>0)throw new Error("invalid compressed G2 point");return{x:J.ZERO,y:J.ZERO}}const u=o(i,0,s),l=o(i,s,2*s),f=J.create({c0:X.create(l),c1:X.create(u)}),d=J.add(J.pow(f,xo),a);let h=J.sqrt(d);const p=h.c1===at?h.c0*Ne/c:h.c1*Ne/c?Eo:at;return h=r&&p>0?h:J.neg(h),{x:f,y:h}}else if(i.length===192&&!e){if(n){if(i.reduce((f,d)=>f!==0?d+1:d,0)>0)throw new Error("invalid uncompressed G2 point");return{x:J.ZERO,y:J.ZERO}}const a=o(i,0,s),c=o(i,s,2*s),u=o(i,2*s,3*s),l=o(i,3*s,4*s);return{x:J.fromBigTuple([c,a]),y:J.fromBigTuple([l,u])}}else throw new Error("invalid point G2, expected 96/192 bytes")},toBytes:(t,e,n)=>{const{BYTES:r,ORDER:i}=X,s=e.equals(t.ZERO),{x:o,y:a}=e.toAffine();if(n){if(s)return _e(_o,Oe(at,r));const c=!!(a.c1===at?a.c0*Ne/i:a.c1*Ne/i);return _e(Xi(Oe(o.c1,r),{compressed:!0,sort:c}),Oe(o.c0,r))}else{if(s)return _e(new Uint8Array([64]),new Uint8Array(4*r-1));const{re:c,im:u}=J.reim(o),{re:l,im:f}=J.reim(a);return _e(Oe(u,r),Oe(c,r),Oe(f,r),Oe(l,r))}},Signature:{fromHex(t){const{infinity:e,sort:n,value:r}=So(Ze("signatureHex",t)),i=X.ORDER,s=r.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, must be 96 or 192");const o=it(r.slice(0,s)),a=it(r.slice(s));if(e)return Ht.G2.ProjectivePoint.ZERO;const c=X.create(o&X.MASK),u=X.create(a),l=J.create({c0:u,c1:c}),f=J.add(J.pow(l,xo),Ht.params.G2b);let d=J.sqrt(f);if(!d)throw new Error("Failed to find a square root");const{re:h,im:p}=J.reim(d),b=BigInt(n),v=p>at&&p*Ne/i!==b,B=p===at&&h*Ne/i!==b;(v||B)&&(d=J.neg(d));const D=Ht.G2.ProjectivePoint.fromAffine({x:l,y:d});return D.assertValidity(),D},toRawBytes(t){return jd(t)},toHex(t){return $r(jd(t))}}},params:{ateLoopSize:Wn,r:kd.ORDER,xNegative:!0,twistType:"multiplicative"},htfDefaults:Vc,hash:uo,randomBytes:Ch});BigInt(0),BigInt(1),BigInt(2),BigInt(8),BigInt(0),BigInt(1),BigInt(2),BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),BigInt(0),BigInt(1),BigInt(2),BigInt(3),BigInt(5),BigInt(8);const fi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Io(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Kc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Nr(t,...e){if(!Io(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 zd(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Kc(t.outputLen),Kc(t.blockLen)}function Ao(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 R8(t,e){Nr(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Bo(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Gc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function tn(t,e){return t<<32-e|t>>>e}const Hd=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),N8=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function hi(t){if(Nr(t),Hd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=N8[t[n]];return e}const _n={_0:48,_9:57,A:65,F:70,a:97,f:102};function Vd(t){if(t>=_n._0&&t<=_n._9)return t-_n._0;if(t>=_n.A&&t<=_n.F)return t-(_n.A-10);if(t>=_n.a&&t<=_n.f)return t-(_n.a-10)}function Oo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Hd)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Vd(t.charCodeAt(s)),a=Vd(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)}r[i]=o*16+a}return r}function Wc(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Zc(t){return typeof t=="string"&&(t=Wc(t)),Nr(t),t}function Zn(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Nr(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class Kd{}function C8(t){const e=r=>t().update(Zc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Gd(t=32){if(fi&&typeof fi.getRandomValues=="function")return fi.getRandomValues(new Uint8Array(t));if(fi&&typeof fi.randomBytes=="function")return Uint8Array.from(fi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Yc=BigInt(0),Xc=BigInt(1);function Do(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Cr(t,e,n=""){const r=Io(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function $o(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Wd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Yc:BigInt("0x"+t)}function Po(t){return Wd(hi(t))}function Zd(t){return Nr(t),Wd(hi(Uint8Array.from(t).reverse()))}function Jc(t,e){return Oo(t.toString(16).padStart(e*2,"0"))}function Yd(t,e){return Jc(t,e).reverse()}function gt(t,e,n){let r;if(typeof e=="string")try{r=Oo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Io(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Qc=t=>typeof t=="bigint"&&Yc<=t;function U8(t,e,n){return Qc(t)&&Qc(e)&&Qc(n)&&e<=t&&t<n}function F8(t,e,n,r){if(!U8(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Xd(t){let e;for(e=0;t>Yc;t>>=Xc,e+=1);return e}const Ji=t=>(Xc<<BigInt(t))-Xc;function L8(t,e,n){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 n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...h)=>n(o,s,...h),l=(h=r(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 p=[];for(;h<e;){s=u();const b=s.slice();p.push(b),h+=s.length}return Zn(...p)};return(h,p)=>{c(),l(h);let b;for(;!(b=p(f()));)l();return c(),b}}function eu(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(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])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function Jd(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const yt=BigInt(0),ct=BigInt(1),Ur=BigInt(2),Qd=BigInt(3),ep=BigInt(4),tp=BigInt(5),k8=BigInt(7),np=BigInt(8),q8=BigInt(9),rp=BigInt(16);function Vt(t,e){const n=t%e;return n>=yt?n:e+n}function Tt(t,e,n){let r=t;for(;e-- >yt;)r*=r,r%=n;return r}function ip(t,e){if(t===yt)throw new Error("invert: expected non-zero number");if(e<=yt)throw new Error("invert: expected positive modulus, got "+e);let n=Vt(t,e),r=e,i=yt,s=ct;for(;n!==yt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==ct)throw new Error("invert: does not exist");return Vt(i,e)}function tu(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function sp(t,e){const n=(t.ORDER+ct)/ep,r=t.pow(e,n);return tu(t,r,e),r}function M8(t,e){const n=(t.ORDER-tp)/np,r=t.mul(e,Ur),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Ur),i),a=t.mul(s,t.sub(o,t.ONE));return tu(t,a,e),a}function j8(t){const e=Qi(t),n=op(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+k8)/rp;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const b=a.eql(a.sqr(l),c),v=a.cmov(u,l,b);return tu(a,v,c),v}}function op(t){if(t<Qd)throw new Error("sqrt is not defined for small field");let e=t-ct,n=0;for(;e%Ur===yt;)e/=Ur,n++;let r=Ur;const i=Qi(t);for(;cp(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return sp;let s=i.pow(r,e);const o=(e+ct)/Ur;return function(c,u){if(c.is0(u))return u;if(cp(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,b=c.sqr(d);for(;!c.eql(b,c.ONE);)if(p++,b=c.sqr(b),p===l)throw new Error("Cannot find square root");const v=ct<<BigInt(l-p-1),B=c.pow(f,v);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function z8(t){return t%ep===Qd?sp:t%np===tp?M8:t%rp===q8?j8(t):op(t)}const H8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function V8(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=H8.reduce((r,i)=>(r[i]="function",r),e);return eu(t,n),t}function K8(t,e,n){if(n<yt)throw new Error("invalid exponent, negatives unsupported");if(n===yt)return t.ONE;if(n===ct)return e;let r=t.ONE,i=e;for(;n>yt;)n&ct&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ct;return r}function ap(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function cp(t,e){const n=(t.ORDER-ct)/Ur,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function up(t,e){e!==void 0&&Kc(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Qi(t,e,n=!1,r={}){if(t<=yt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=up(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:Ji(c),ZERO:yt,ONE:ct,allowedLengths:a,create:d=>Vt(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return yt<=d&&d<t},is0:d=>d===yt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ct)===ct,neg:d=>Vt(-d,t),eql:(d,h)=>d===h,sqr:d=>Vt(d*d,t),add:(d,h)=>Vt(d+h,t),sub:(d,h)=>Vt(d-h,t),mul:(d,h)=>Vt(d*h,t),pow:(d,h)=>K8(f,d,h),div:(d,h)=>Vt(d*ip(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>ip(d,t),sqrt:s||(d=>(l||(l=z8(t)),l(f,d))),toBytes:d=>n?Yd(d,u):Jc(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const b=new Uint8Array(u);b.set(d,n?0:b.length-d.length),d=b}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?Zd(d):Po(d);if(o&&(p=Vt(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>ap(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function lp(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 fp(t){const e=lp(t);return e+Math.ceil(e/2)}function G8(t,e,n=!1){const r=t.length,i=lp(e),s=fp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Zd(t):Po(t),a=Vt(o,e-ct)+ct;return n?Yd(a,i):Jc(a,i)}function W8(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Z8(t,e,n){return t&e^~t&n}function Y8(t,e,n){return t&e^t&n^e&n}class X8 extends Kd{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Gc(this.buffer)}update(e){Ao(this),e=Zc(e),Nr(e);const{view:n,buffer:r,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=Gc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ao(this),R8(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Bo(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;W8(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Gc(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Yn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),J8=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]),Xn=new Uint32Array(64);class Q8 extends X8{constructor(e=32){super(64,e,8,!1),this.A=Yn[0]|0,this.B=Yn[1]|0,this.C=Yn[2]|0,this.D=Yn[3]|0,this.E=Yn[4]|0,this.F=Yn[5]|0,this.G=Yn[6]|0,this.H=Yn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)Xn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=Xn[f-15],h=Xn[f-2],p=tn(d,7)^tn(d,18)^d>>>3,b=tn(h,17)^tn(h,19)^h>>>10;Xn[f]=b+Xn[f-7]+p+Xn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=tn(a,6)^tn(a,11)^tn(a,25),h=l+d+Z8(a,c,u)+J8[f]+Xn[f]|0,b=(tn(r,2)^tn(r,13)^tn(r,22))+Y8(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+b|0}r=r+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(r,i,s,o,a,c,u,l)}roundClean(){Bo(Xn)}destroy(){this.set(0,0,0,0,0,0,0,0),Bo(this.buffer)}}const hp=C8(()=>new Q8);class dp extends Kd{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,zd(e);const r=Zc(n);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(r.length>i?e.create().update(r).digest():r);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),Bo(s)}update(e){return Ao(this),this.iHash.update(e),this}digestInto(e){Ao(this),Nr(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:n,iHash:r,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=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const pp=(t,e,n)=>new dp(t,e).update(n).digest();pp.create=(t,e)=>new dp(t,e);const di=BigInt(0),Fr=BigInt(1);function To(t,e){const n=e.negate();return t?n:e}function nu(t,e){const n=ap(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function gp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ru(t,e){gp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Ji(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function yp(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=Fr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function ex(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function tx(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const iu=new WeakMap,bp=new WeakMap;function su(t){return bp.get(t)||1}function wp(t){if(t!==di)throw new Error("invalid wNAF")}class nx{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>di;)n&Fr&&(r=r.add(i)),i=i.double(),n>>=Fr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=ru(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;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,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=ru(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=yp(r,a,o);r=c,l?s=s.add(To(d,n[h])):i=i.add(To(f,n[u]))}return wp(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=ru(e,this.bits);for(let o=0;o<s.windows&&r!==di;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=yp(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return wp(r),i}getPrecomputes(e,n,r){let i=iu.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),iu.set(n,i))),i}cached(e,n,r){const i=su(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=su(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){gp(n,this.bits),bp.set(e,n),iu.delete(e)}hasCache(e){return su(e)!==1}}function rx(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>di||r>di;)n&Fr&&(s=s.add(i)),r&Fr&&(o=o.add(i)),i=i.double(),n>>=Fr,r>>=Fr;return{p1:s,p2:o}}function ix(t,e,n,r){ex(n,t),tx(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Xd(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Ji(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let b=0;b<s;b++){const v=r[b],B=Number(v>>BigInt(h)&u);l[B]=l[B].add(n[b])}let p=o;for(let b=l.length-1,v=o;b>0;b--)v=v.add(l[b]),p=p.add(v);if(d=d.add(p),h!==0)for(let b=0;b<c;b++)d=d.double()}return d}function mp(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return V8(e),e}else return Qi(t,{isLE:n})}function sx(t,e,n={},r){if(r===void 0&&(r=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>di))throw new Error(`CURVE.${c} must be positive bigint`)}const i=mp(e.p,n.Fp,r),s=mp(e.n,n.Fn,r),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 vp=(t,e)=>(t+(t>=0?e:-e)/Ep)/e;function ox(t,e,n){const[[r,i],[s,o]]=e,a=vp(o*t,n),c=vp(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<In,d=l<In;f&&(u=-u),d&&(l=-l);const h=Ji(Math.ceil(Xd(n)/2))+pi;if(u<In||u>=h||l<In||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function ou(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function au(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Do(n.lowS,"lowS"),Do(n.prehash,"prehash"),n.format!==void 0&&ou(n.format),n}class ax extends Error{constructor(e=""){super(e)}}const Sn={Err:ax,_tlv:{encode:(t,e)=>{const{Err:n}=Sn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=$o(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?$o(i.length/2|128):"";return $o(t)+s+i+e},decode(t,e){const{Err:n}=Sn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=Sn;if(t<In)throw new e("integer: negative integers are not allowed");let n=$o(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=Sn;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 Po(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Sn,i=gt("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=Sn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},In=BigInt(0),pi=BigInt(1),Ep=BigInt(2),Ro=BigInt(3),cx=BigInt(4);function gi(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=gt("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function ux(t,e={}){const n=sx("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;eu(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=_p(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,y,m){const{x:g,y:w}=y.toAffine(),S=r.toBytes(g);if(Do(m,"isCompressed"),m){l();const A=!r.isOdd(w);return Zn(xp(A),S)}else return Zn(Uint8Array.of(4),S,r.toBytes(w))}function d(E){Cr(E,void 0,"Point");const{publicKey:y,publicKeyUncompressed:m}=u,g=E.length,w=E[0],S=E.subarray(1);if(g===y&&(w===2||w===3)){const A=r.fromBytes(S);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const I=b(A);let O;try{O=r.sqrt(I)}catch(U){const k=U instanceof Error?": "+U.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}l();const T=r.isOdd(O);return(w&1)===1!==T&&(O=r.neg(O)),{x:A,y:O}}else if(g===m&&w===4){const A=r.BYTES,I=r.fromBytes(S.subarray(0,A)),O=r.fromBytes(S.subarray(A,A*2));if(!v(I,O))throw new Error("bad point: is not on curve");return{x:I,y:O}}else throw new Error(`bad point: got length ${g}, expected compressed=${y} or uncompressed=${m}`)}const h=e.toBytes||f,p=e.fromBytes||d;function b(E){const y=r.sqr(E),m=r.mul(y,E);return r.add(r.add(m,r.mul(E,s.a)),s.b)}function v(E,y){const m=r.sqr(y),g=b(E);return r.eql(m,g)}if(!v(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,Ro),cx),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,D)))throw new Error("bad curve params: a or b");function _(E,y,m=!1){if(!r.isValid(y)||m&&r.is0(y))throw new Error(`bad point coordinate ${E}`);return y}function x(E){if(!(E instanceof $))throw new Error("ProjectivePoint expected")}function P(E){if(!c||!c.basises)throw new Error("no endo");return ox(E,c.basises,i.ORDER)}const R=Jd((E,y)=>{const{X:m,Y:g,Z:w}=E;if(r.eql(w,r.ONE))return{x:m,y:g};const S=E.is0();y==null&&(y=S?r.ONE:r.inv(w));const A=r.mul(m,y),I=r.mul(g,y),O=r.mul(w,y);if(S)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:A,y:I}}),N=Jd(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:m}=E.toAffine();if(!r.isValid(y)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!v(y,m))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(E,y,m,g,w){return m=new $(r.mul(m.X,E),m.Y,m.Z),y=To(g,y),m=To(w,m),y.add(m)}class ${constructor(y,m,g){this.X=_("x",y),this.Y=_("y",m,!0),this.Z=_("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){const{x:m,y:g}=y||{};if(!y||!r.isValid(m)||!r.isValid(g))throw new Error("invalid affine point");if(y instanceof $)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(g)?$.ZERO:new $(m,g,r.ONE)}static fromBytes(y){const m=$.fromAffine(p(Cr(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return $.fromBytes(gt("pointHex",y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return M.createCache(this,y),m||this.multiply(Ro),this}assertValidity(){N(this)}hasEvenY(){const{y}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(y)}equals(y){x(y);const{X:m,Y:g,Z:w}=this,{X:S,Y:A,Z:I}=y,O=r.eql(r.mul(m,I),r.mul(S,w)),T=r.eql(r.mul(g,I),r.mul(A,w));return O&&T}negate(){return new $(this.X,r.neg(this.Y),this.Z)}double(){const{a:y,b:m}=s,g=r.mul(m,Ro),{X:w,Y:S,Z:A}=this;let I=r.ZERO,O=r.ZERO,T=r.ZERO,L=r.mul(w,w),U=r.mul(S,S),k=r.mul(A,A),C=r.mul(w,S);return C=r.add(C,C),T=r.mul(w,A),T=r.add(T,T),I=r.mul(y,T),O=r.mul(g,k),O=r.add(I,O),I=r.sub(U,O),O=r.add(U,O),O=r.mul(I,O),I=r.mul(C,I),T=r.mul(g,T),k=r.mul(y,k),C=r.sub(L,k),C=r.mul(y,C),C=r.add(C,T),T=r.add(L,L),L=r.add(T,L),L=r.add(L,k),L=r.mul(L,C),O=r.add(O,L),k=r.mul(S,A),k=r.add(k,k),L=r.mul(k,C),I=r.sub(I,L),T=r.mul(k,U),T=r.add(T,T),T=r.add(T,T),new $(I,O,T)}add(y){x(y);const{X:m,Y:g,Z:w}=this,{X:S,Y:A,Z:I}=y;let O=r.ZERO,T=r.ZERO,L=r.ZERO;const U=s.a,k=r.mul(s.b,Ro);let C=r.mul(m,S),q=r.mul(g,A),j=r.mul(w,I),W=r.add(m,g),V=r.add(S,A);W=r.mul(W,V),V=r.add(C,q),W=r.sub(W,V),V=r.add(m,w);let Z=r.add(S,I);return V=r.mul(V,Z),Z=r.add(C,j),V=r.sub(V,Z),Z=r.add(g,w),O=r.add(A,I),Z=r.mul(Z,O),O=r.add(q,j),Z=r.sub(Z,O),L=r.mul(U,V),O=r.mul(k,j),L=r.add(O,L),O=r.sub(q,L),L=r.add(q,L),T=r.mul(O,L),q=r.add(C,C),q=r.add(q,C),j=r.mul(U,j),V=r.mul(k,V),q=r.add(q,j),j=r.sub(C,j),j=r.mul(U,j),V=r.add(V,j),C=r.mul(q,V),T=r.add(T,C),C=r.mul(Z,V),O=r.mul(W,O),O=r.sub(O,C),C=r.mul(W,q),L=r.mul(Z,L),L=r.add(L,C),new $(O,T,L)}subtract(y){return this.add(y.negate())}is0(){return this.equals($.ZERO)}multiply(y){const{endo:m}=e;if(!i.isValidNot0(y))throw new Error("invalid scalar: out of range");let g,w;const S=A=>M.cached(this,A,I=>nu($,I));if(m){const{k1neg:A,k1:I,k2neg:O,k2:T}=P(y),{p:L,f:U}=S(I),{p:k,f:C}=S(T);w=U.add(C),g=F(m.beta,L,k,A,O)}else{const{p:A,f:I}=S(y);g=A,w=I}return nu($,[g,w])[0]}multiplyUnsafe(y){const{endo:m}=e,g=this;if(!i.isValid(y))throw new Error("invalid scalar: out of range");if(y===In||g.is0())return $.ZERO;if(y===pi)return g;if(M.hasCache(this))return this.multiply(y);if(m){const{k1neg:w,k1:S,k2neg:A,k2:I}=P(y),{p1:O,p2:T}=rx($,g,S,I);return F(m.beta,O,T,w,A)}else return M.unsafe(g,y)}multiplyAndAddUnsafe(y,m,g){const w=this.multiplyUnsafe(m).add(y.multiplyUnsafe(g));return w.is0()?void 0:w}toAffine(y){return R(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===pi?!0:y?y($,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===pi?this:y?y($,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return Do(y,"isCompressed"),this.assertValidity(),h($,this,y)}toHex(y=!0){return hi(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(y=!0){return this.toBytes(y)}_setWindowSize(y){this.precompute(y)}static normalizeZ(y){return nu($,y)}static msm(y,m){return ix($,i,y,m)}static fromPrivateKey(y){return $.BASE.multiply(gi(i,y))}}$.BASE=new $(s.Gx,s.Gy,r.ONE),$.ZERO=new $(r.ZERO,r.ONE,r.ZERO),$.Fp=r,$.Fn=i;const z=i.BITS,M=new nx($,e.endo?Math.ceil(z/2):z);return $.BASE.precompute(8),$}function xp(t){return Uint8Array.of(t?2:3)}function _p(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function lx(t,e={}){const{Fn:n}=t,r=e.randomBytes||Gd,i=Object.assign(_p(t.Fp,n),{seed:fp(n.ORDER)});function s(h){try{return!!gi(n,h)}catch{return!1}}function o(h,p){const{publicKey:b,publicKeyUncompressed:v}=i;try{const B=h.length;return p===!0&&B!==b||p===!1&&B!==v?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return G8(Cr(h,i.seed,"seed"),n.ORDER)}function c(h,p=!0){return t.BASE.multiply(gi(n,h)).toBytes(p)}function u(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:b,publicKeyUncompressed:v}=i;if(n.allowedLengths||p===b)return;const B=gt("key",h).length;return B===b||B===v}function f(h,p,b=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const v=gi(n,h);return t.fromHex(p).multiply(v).toBytes(b)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>gi(n,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:i})}function fx(t,e,n={}){zd(e),eu(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Gd,i=n.hmac||((m,...g)=>pp(e,m,Zn(...g))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=lx(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},b="compact";function v(m){const g=a>>pi;return m>g}function B(m,g){if(!o.isValidNot0(g))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return g}function D(m,g){ou(g);const w=h.signature,S=g==="compact"?w:g==="recovered"?w+1:void 0;return Cr(m,S,`${g} signature`)}class _{constructor(g,w,S){this.r=B("r",g),this.s=B("s",w),S!=null&&(this.recovery=S),Object.freeze(this)}static fromBytes(g,w=b){D(g,w);let S;if(w==="der"){const{r:T,s:L}=Sn.toSig(Cr(g));return new _(T,L)}w==="recovered"&&(S=g[0],w="compact",g=g.subarray(1));const A=o.BYTES,I=g.subarray(0,A),O=g.subarray(A,A*2);return new _(o.fromBytes(I),o.fromBytes(O),S)}static fromHex(g,w){return this.fromBytes(Oo(g),w)}addRecoveryBit(g){return new _(this.r,this.s,g)}recoverPublicKey(g){const w=s.ORDER,{r:S,s:A,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*Ep<w&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const T=I===2||I===3?S+a:S;if(!s.isValid(T))throw new Error("recovery id 2 or 3 invalid");const L=s.toBytes(T),U=t.fromBytes(Zn(xp((I&1)===0),L)),k=o.inv(T),C=P(gt("msgHash",g)),q=o.create(-C*k),j=o.create(A*k),W=t.BASE.multiplyUnsafe(q).add(U.multiplyUnsafe(j));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return v(this.s)}toBytes(g=b){if(ou(g),g==="der")return Oo(Sn.hexFromSig(this));const w=o.toBytes(this.r),S=o.toBytes(this.s);if(g==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Zn(Uint8Array.of(this.recovery),w,S)}return Zn(w,S)}toHex(g){return hi(this.toBytes(g))}assertValidity(){}static fromCompact(g){return _.fromBytes(gt("sig",g),"compact")}static fromDER(g){return _.fromBytes(gt("sig",g),"der")}normalizeS(){return this.hasHighS()?new _(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return hi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return hi(this.toBytes("compact"))}}const x=n.bits2int||function(g){if(g.length>8192)throw new Error("input is too large");const w=Po(g),S=g.length*8-c;return S>0?w>>BigInt(S):w},P=n.bits2int_modN||function(g){return o.create(x(g))},R=Ji(c);function N(m){return F8("num < 2^"+c,m,In,R),o.toBytes(m)}function F(m,g){return Cr(m,void 0,"message"),g?Cr(e(m),void 0,"prehashed message"):m}function $(m,g,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:S,prehash:A,extraEntropy:I}=au(w,p);m=F(m,A);const O=P(m),T=gi(o,g),L=[N(T),N(O)];if(I!=null&&I!==!1){const q=I===!0?r(h.secretKey):I;L.push(gt("extraEntropy",q))}const U=Zn(...L),k=O;function C(q){const j=x(q);if(!o.isValidNot0(j))return;const W=o.inv(j),V=t.BASE.multiply(j).toAffine(),Z=o.create(V.x);if(Z===In)return;const Q=o.create(W*o.create(k+Z*T));if(Q===In)return;let ee=(V.x===Z?0:2)|Number(V.y&pi),ie=Q;return S&&v(Q)&&(ie=o.neg(Q),ee^=1),new _(Z,ie,ee)}return{seed:U,k2sig:C}}function z(m,g,w={}){m=gt("message",m);const{seed:S,k2sig:A}=$(m,g,w);return L8(e.outputLen,o.BYTES,i)(S,A)}function M(m){let g;const w=typeof m=="string"||Io(m),S=!w&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!w&&!S)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(S)g=new _(m.r,m.s);else if(w){try{g=_.fromBytes(gt("sig",m),"der")}catch(A){if(!(A instanceof Sn.Err))throw A}if(!g)try{g=_.fromBytes(gt("sig",m),"compact")}catch{return!1}}return g||!1}function E(m,g,w,S={}){const{lowS:A,prehash:I,format:O}=au(S,p);if(w=gt("publicKey",w),g=F(gt("message",g),I),"strict"in S)throw new Error("options.strict was renamed to lowS");const T=O===void 0?M(m):_.fromBytes(gt("sig",m),O);if(T===!1)return!1;try{const L=t.fromBytes(w);if(A&&T.hasHighS())return!1;const{r:U,s:k}=T,C=P(g),q=o.inv(k),j=o.create(C*q),W=o.create(U*q),V=t.BASE.multiplyUnsafe(j).add(L.multiplyUnsafe(W));return V.is0()?!1:o.create(V.x)===U}catch{return!1}}function y(m,g,w={}){const{prehash:S}=au(w,p);return g=F(g,S),_.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:z,verify:E,recoverPublicKey:y,Signature:_,hash:e})}function hx(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},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=Qi(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,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 dx(t){const{CURVE:e,curveOpts:n}=hx(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function px(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,up(n.Fn.ORDER,n.Fn.BITS))})}function gx(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=dx(t),s=ux(e,n),o=fx(s,r,i);return px(t,o)}function yx(t,e){const n=r=>gx({...t,hash:r});return{...n(e),create:n}}Wc("HashToScalar-");const cu={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},bx={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Sp=BigInt(2);function wx(t){const e=cu.p,n=BigInt(3),r=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=Tt(l,n,e)*l%e,d=Tt(f,n,e)*l%e,h=Tt(d,Sp,e)*u%e,p=Tt(h,i,e)*h%e,b=Tt(p,s,e)*p%e,v=Tt(b,a,e)*b%e,B=Tt(v,c,e)*v%e,D=Tt(B,a,e)*b%e,_=Tt(D,n,e)*l%e,x=Tt(_,o,e)*p%e,P=Tt(x,r,e)*u%e,R=Tt(P,Sp,e);if(!uu.eql(uu.sqr(R),t))throw new Error("Cannot find square root");return R}const uu=Qi(cu.p,{sqrt:wx});yx({...cu,Fp:uu,lowS:!0,endo:bx},hp);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function yi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function lu(t,...e){if(!yi(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 Ip(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function fu(t){if(typeof t!="function")throw new Error("function expected");return!0}function Jn(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function bi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function No(t){if(!Array.isArray(t))throw new Error("array expected")}function Co(t,e){if(!Ip(!0,e))throw new Error(`${t}: array of strings expected`)}function hu(t,e){if(!Ip(!1,e))throw new Error(`${t}: array of numbers expected`)}function bt(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function St(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Co("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(No(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(No(i),i.map(s=>{Jn("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function It(t=""){return Jn("join",t),{encode:e=>(Co("join.decode",e),e.join(t)),decode:e=>(Jn("join.decode",e),e.split(t))}}function Uo(t,e="="){return bi(t),Jn("padding",e),{encode(n){for(Co("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Co("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function Ap(t){return fu(t),{encode:e=>e,decode:e=>t(e)}}function Bp(t,e,n){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(No(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(bi(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=r;u<o;u++){const l=s[u],f=e*a,d=f+l;if(!Number.isSafeInteger(d)||f/e!==a||d-l!==f)throw new Error("convertRadix: carry overflow");const h=d/n;a=d%n;const p=Math.floor(h);if(s[u]=p,!Number.isSafeInteger(p)||p*n+a!==d)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:r=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 Op=(t,e)=>e===0?t:Op(e,t%e),Fo=(t,e)=>t+(e-Op(t,e)),Lo=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function du(t,e,n,r){if(No(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Fo(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Fo(e,n)}`);let i=0,s=0;const o=Lo[e],a=Lo[n]-1,c=[];for(const u of t){if(bi(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>=n;s-=n)c.push((i>>s-n&a)>>>0);const l=Lo[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function mx(t){bi(t);const e=2**8;return{encode:n=>{if(!yi(n))throw new Error("radix.encode input should be Uint8Array");return Bp(Array.from(n),e,t)},decode:n=>(hu("radix.decode",n),Uint8Array.from(Bp(n,t,e)))}}function Rt(t,e=!1){if(bi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Fo(8,t)>32||Fo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!yi(n))throw new Error("radix2.encode input should be Uint8Array");return du(Array.from(n),8,t,!e)},decode:n=>(hu("radix2.decode",n),Uint8Array.from(du(n,t,8,e)))}}function Dp(t){return fu(t),function(...e){try{return t.apply(null,e)}catch{}}}function vx(t,e){return bi(t),fu(e),{encode(n){if(!yi(n))throw new Error("checksum.encode: input should be Uint8Array");const r=e(n).slice(0,t),i=new Uint8Array(n.length+t);return i.set(n),i.set(r,n.length),i},decode(n){if(!yi(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-t),i=n.slice(-t),s=e(r).slice(0,t);for(let o=0;o<t;o++)if(s[o]!==i[o])throw new Error("Invalid checksum");return r}}}bt(Rt(4),St("0123456789ABCDEF"),It(""));const Ex=bt(Rt(5),St("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Uo(5),It(""));bt(Rt(5),St("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),It("")),bt(Rt(5),St("0123456789ABCDEFGHIJKLMNOPQRSTUV"),Uo(5),It("")),bt(Rt(5),St("0123456789ABCDEFGHIJKLMNOPQRSTUV"),It("")),bt(Rt(5),St("0123456789ABCDEFGHJKMNPQRSTVWXYZ"),It(""),Ap(t=>t.toUpperCase().replace(/O/g,"0").replace(/[IL]/g,"1")));const $p=(()=>typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function")(),Pp=(t,e)=>{Jn("base64",t);const n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})};$p||bt(Rt(6),St("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),Uo(6),It("")),bt(Rt(6),St("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"),It("")),$p||bt(Rt(6),St("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),Uo(6),It("")),bt(Rt(6),St("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"),It(""));const pu=t=>bt(mx(58),St(t),It("")),xx=pu("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");pu("123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"),pu("rpshnaf39wBUDNEGHJKLM4PQRST7VWXYZ2bcdeCg65jkm8oFqi1tuvAxyz");const _x=t=>bt(vx(4,e=>t(t(e))),xx),gu=bt(St("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),It("")),Tp=[996825010,642813549,513874426,1027748829,705979059];function es(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Tp.length;r++)(e>>r&1)===1&&(n^=Tp[r]);return n}function Rp(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=es(i)^o>>5}i=es(i);for(let s=0;s<r;s++)i=es(i)^t.charCodeAt(s)&31;for(let s of e)i=es(i)^s;for(let s=0;s<6;s++)i=es(i);return i^=n,gu.encode(du([i%Lo[30]],30,5,!1))}function Np(t){const e=t==="bech32"?1:734539939,n=Rt(5),r=n.decode,i=n.encode,s=Dp(r);function o(f,d,h=90){Jn("bech32.encode prefix",f),yi(d)&&(d=Array.from(d)),hu("bech32.encode",d);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const b=p+7+d.length;if(h!==!1&&b>h)throw new TypeError(`Length ${b} exceeds limit ${h}`);const v=f.toLowerCase(),B=Rp(v,d,e);return`${v}1${gu.encode(d)}${B}`}function a(f,d=90){Jn("bech32.decode input",f);const h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);const p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const b=p.lastIndexOf("1");if(b===0||b===-1)throw new Error('Letter "1" must be present between prefix and data only');const v=p.slice(0,b),B=p.slice(b+1);if(B.length<6)throw new Error("Data must be at least 6 characters long");const D=gu.decode(B).slice(0,-6),_=Rp(v,D,e);if(!B.endsWith(_))throw new Error(`Invalid checksum in ${f}: expected "${_}"`);return{prefix:v,words:D}}const c=Dp(a);function u(f){const{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:r(h)}}function l(f,d){return o(f,i(d))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}Np("bech32"),Np("bech32m");const Sx=(()=>typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function")(),Ix={encode(t){return lu(t),t.toHex()},decode(t){return Jn("hex",t),Uint8Array.fromHex(t)}};Sx||bt(Rt(4),St("0123456789abcdef"),It(""),Ap(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()})),_x(hp),Wc("Bitcoin seed");function Ax(t){return LE(Bx(t))}function Bx(t){const{payload:e,signature:n}=t,{r,s:i,yParity:s}=n,a=new g8.Signature(BigInt(r),BigInt(i)).addRecoveryBit(s).recoverPublicKey(Ic(e).substring(2));return DE(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Cp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ko(t,...e){if(!Cp(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 qo(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 Up(t,e){ko(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ts(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function yu(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ox(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Dx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ns(t){if(typeof t=="string")t=Dx(t);else if(Cp(t))t=Fp(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Fp(t){return Uint8Array.from(t)}const An=16,bu=new Uint8Array(16),nn=ts(bu),$x=225,Px=(t,e,n,r)=>{const i=r&1;return{s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^$x<<24&-(i&1)}},Nt=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255|0;function Tx(t){t.reverse();const e=t[15]&1;let n=0;for(let r=0;r<t.length;r++){const i=t[r];t[r]=i>>>1|n,n=(i&1)<<7}return t[0]^=-e&225,t}const Rx=t=>t>64*1024?8:t>1024?4:2;class Lp{constructor(e,n){this.blockLen=An,this.outputLen=An,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,e=ns(e),ko(e,16);const r=Ox(e);let i=r.getUint32(0,!1),s=r.getUint32(4,!1),o=r.getUint32(8,!1),a=r.getUint32(12,!1);const c=[];for(let p=0;p<128;p++)c.push({s0:Nt(i),s1:Nt(s),s2:Nt(o),s3:Nt(a)}),{s0:i,s1:s,s2:o,s3:a}=Px(i,s,o,a);const u=Rx(n||1024);if(![1,2,4,8].includes(u))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=u;const f=128/u,d=this.windowSize=2**u,h=[];for(let p=0;p<f;p++)for(let b=0;b<d;b++){let v=0,B=0,D=0,_=0;for(let x=0;x<u;x++){if(!(b>>>u-x-1&1))continue;const{s0:R,s1:N,s2:F,s3:$}=c[u*p+x];v^=R,B^=N,D^=F,_^=$}h.push({s0:v,s1:B,s2:D,s3:_})}this.t=h}_updateBlock(e,n,r,i){e^=this.s0,n^=this.s1,r^=this.s2,i^=this.s3;const{W:s,t:o,windowSize:a}=this;let c=0,u=0,l=0,f=0;const d=(1<<s)-1;let h=0;for(const p of[e,n,r,i])for(let b=0;b<4;b++){const v=p>>>8*b&255;for(let B=8/s-1;B>=0;B--){const D=v>>>s*B&d,{s0:_,s1:x,s2:P,s3:R}=o[h*a+D];c^=_,u^=x,l^=P,f^=R,h+=1}}this.s0=c,this.s1=u,this.s2=l,this.s3=f}update(e){qo(this),e=ns(e),ko(e);const n=ts(e),r=Math.floor(e.length/An),i=e.length%An;for(let s=0;s<r;s++)this._updateBlock(n[s*4+0],n[s*4+1],n[s*4+2],n[s*4+3]);return i&&(bu.set(e.subarray(r*An)),this._updateBlock(nn[0],nn[1],nn[2],nn[3]),yu(nn)),this}destroy(){const{t:e}=this;for(const n of e)n.s0=0,n.s1=0,n.s2=0,n.s3=0}digestInto(e){qo(this),Up(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=ts(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e}digest(){const e=new Uint8Array(An);return this.digestInto(e),this.destroy(),e}}class Nx extends Lp{constructor(e,n){e=ns(e),ko(e);const r=Tx(Fp(e));super(r,n),yu(r)}update(e){e=ns(e),qo(this);const n=ts(e),r=e.length%An,i=Math.floor(e.length/An);for(let s=0;s<i;s++)this._updateBlock(Nt(n[s*4+3]),Nt(n[s*4+2]),Nt(n[s*4+1]),Nt(n[s*4+0]));return r&&(bu.set(e.subarray(i*An)),this._updateBlock(Nt(nn[3]),Nt(nn[2]),Nt(nn[1]),Nt(nn[0])),yu(nn)),this}digestInto(e){qo(this),Up(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=ts(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e.reverse()}}function kp(t){const e=(r,i)=>t(i,r.length).update(ns(r)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(r,i)=>t(r,i),e}kp((t,e)=>new Lp(t,e)),kp((t,e)=>new Nx(t,e));const qp=Vn(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Cx=qp.create(BigInt("-3")),Ux=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");mo({a:Cx,b:Ux,Fp:qp,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},uo);const Mp=Vn(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),Fx=Mp.create(BigInt("-3")),Lx=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");mo({a:Fx,b:Lx,Fp:Mp,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},Q3);const jp=Vn(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),kx=jp.create(BigInt("-3")),qx=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");mo({a:kx,b:qx,Fp:jp,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},J3);var Mx={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,f,d){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new i(l,f||c,d),p=n?n+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],l,f;if(this._eventsCount===0)return u;for(f in l=this._events)e.call(l,f)&&u.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},a.prototype.listeners=function(u){var l=n?n+u:u,f=this._events[l];if(!f)return[];if(f.fn)return[f.fn];for(var d=0,h=f.length,p=new Array(h);d<h;d++)p[d]=f[d].fn;return p},a.prototype.listenerCount=function(u){var l=n?n+u:u,f=this._events[l];return f?f.fn?1:f.length:0},a.prototype.emit=function(u,l,f,d,h,p){var b=n?n+u:u;if(!this._events[b])return!1;var v=this._events[b],B=arguments.length,D,_;if(v.fn){switch(v.once&&this.removeListener(u,v.fn,void 0,!0),B){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,l),!0;case 3:return v.fn.call(v.context,l,f),!0;case 4:return v.fn.call(v.context,l,f,d),!0;case 5:return v.fn.call(v.context,l,f,d,h),!0;case 6:return v.fn.call(v.context,l,f,d,h,p),!0}for(_=1,D=new Array(B-1);_<B;_++)D[_-1]=arguments[_];v.fn.apply(v.context,D)}else{var x=v.length,P;for(_=0;_<x;_++)switch(v[_].once&&this.removeListener(u,v[_].fn,void 0,!0),B){case 1:v[_].fn.call(v[_].context);break;case 2:v[_].fn.call(v[_].context,l);break;case 3:v[_].fn.call(v[_].context,l,f);break;case 4:v[_].fn.call(v[_].context,l,f,d);break;default:if(!D)for(P=1,D=new Array(B-1);P<B;P++)D[P-1]=arguments[P];v[_].fn.apply(v[_].context,D)}}return!0},a.prototype.on=function(u,l,f){return s(this,u,l,f,!1)},a.prototype.once=function(u,l,f){return s(this,u,l,f,!0)},a.prototype.removeListener=function(u,l,f,d){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return o(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!d||p.once)&&(!f||p.context===f)&&o(this,h);else{for(var b=0,v=[],B=p.length;b<B;b++)(p[b].fn!==l||d&&!p[b].once||f&&p[b].context!==f)&&v.push(p[b]);v.length?this._events[h]=v.length===1?v[0]:v:o(this,h)}return this},a.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&o(this,l)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a})(Mx);function jx(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 n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);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,d=0;const h=u.length;for(;d!==h&&u[d]===0;)d++,l++;const p=(h-d)*s+1>>>0,b=new Uint8Array(p);for(;d!==h;){let D=u[d],_=0;for(let x=p-1;(D!==0||_<f)&&x!==-1;x--,_++)D+=256*b[x]>>>0,b[x]=D%n>>>0,D=D/n>>>0;if(D!==0)throw new Error("Non-zero carry");f=_,d++}let v=p-f;for(;v!==p&&b[v]===0;)v++;let B=r.repeat(l);for(;v<p;++v)B+=t.charAt(b[v]);return B}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,d=0;for(;u[l]===r;)f++,l++;const h=(u.length-l)*i+1>>>0,p=new Uint8Array(h);for(;l<u.length;){const D=u.charCodeAt(l);if(D>255)return;let _=e[D];if(_===255)return;let x=0;for(let P=h-1;(_!==0||x<d)&&P!==-1;P--,x++)_+=n*p[P]>>>0,p[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");d=x,l++}let b=h-d;for(;b!==h&&p[b]===0;)b++;const v=new Uint8Array(f+(h-b));let B=f;for(;b!==h;)v[B++]=p[b++];return v}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var zx="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",rs=jx(zx);function Hx(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if(i&4294967168)if(!(i&4294965248))n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}i&4294901760?n+=4:n+=3}else{n++;continue}}return n}function Vx(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){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 Kx=new TextEncoder,Gx=50;function Wx(t,e,n){Kx.encodeInto(t,e.subarray(n))}function Zx(t,e,n){t.length>Gx?Wx(t,e,n):Vx(t,e,n)}const Yx=4096;function zp(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const a=t[r++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,l=t[r++]&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>=Yx&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Xx=new TextDecoder,Jx=200;function Qx(t,e,n){const r=t.subarray(e,e+n);return Xx.decode(r)}function e6(t,e,n){return n>Jx?Qx(t,e,n):zp(t,e,n)}class Mo{constructor(e,n){this.type=e,this.data=n}}class At extends Error{constructor(e){super(e);const n=Object.create(At.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:At.name})}}const is=4294967295;function t6(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Hp(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Vp(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function n6(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const r6=-1,i6=4294967296-1,s6=17179869184-1;function o6({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=s6)if(e===0&&t<=i6){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Hp(r,4,t),n}}function a6(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function c6(t){if(t instanceof Date){const e=a6(t);return o6(e)}else return null}function u6(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 n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=Vp(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new At(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function l6(t){const e=u6(t);return new Date(e.sec*1e3+e.nsec/1e6)}const f6={type:r6,encode:c6,decode:l6};class jo{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(f6)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new Mo(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new Mo(o,s)}}}return e instanceof Mo?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new Mo(n,e)}}jo.defaultCodec=new jo;function h6(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function wu(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):h6(t)?new Uint8Array(t):Uint8Array.from(t)}const d6=100,p6=2048;class mu{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??jo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??d6,this.initialBufferSize=e?.initialBufferSize??p6,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 mu({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,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);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,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=Hx(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Zx(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=wu(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.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 r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}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),t6(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Hp(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 g6(t,e){return new mu(e).encodeSharedRef(t)}function vu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const y6=16,b6=16;class w6{constructor(e=y6,n=b6){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=zp(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Eu="array",ss="map_key",Kp="map_value",m6=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new At("The type of key must be string or number but "+typeof t)};class v6{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Eu,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=ss,n.readCount=0,n.size=e,n.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===Eu){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===ss||e.type===Kp){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const os=-1,xu=new DataView(new ArrayBuffer(0)),E6=new Uint8Array(xu.buffer);try{xu.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 Gp=new RangeError("Insufficient data"),x6=new w6;class _u{constructor(e){this.totalPos=0,this.pos=0,this.view=xu,this.bytes=E6,this.headByte=os,this.stack=new v6,this.entered=!1,this.extensionCodec=e?.extensionCodec??jo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??is,this.maxBinLength=e?.maxBinLength??is,this.maxArrayLength=e?.maxArrayLength??is,this.maxMapLength=e?.maxMapLength??is,this.maxExtLength=e?.maxExtLength??is,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:x6,this.mapKeyConverter=e?.mapKeyConverter??m6}clone(){return new _u({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=os,this.stack.reset()}setBuffer(e){const n=wu(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===os&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=wu(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.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 n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}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 n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${vu(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,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!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 n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new At(`Unrecognized type byte: ${vu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Eu)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===ss){if(n==="__proto__")throw new At("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Kp;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=ss;continue e}}return n}}readHeadByte(){return this.headByte===os&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=os}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 At(`Unrecognized array type byte: ${vu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new At(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new At(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new At(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Gp;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=e6(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===ss:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new At(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Gp;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new At(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=n6(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Vp(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 _6(t,e){return new _u(e).decode(t)}function Su(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Wp(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Su(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function as(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Wp(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Su(n)}function S6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[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 b=0,v=0,B=0,D=p.length;B!==D&&p[B]===0;)B++,b++;for(var _=(D-B)*l+1>>>0,x=new Uint8Array(_);B!==D;){for(var P=p[B],R=0,N=_-1;(P!==0||R<v)&&N!==-1;N--,R++)P+=256*x[N]>>>0,x[N]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");v=R,B++}for(var F=_-v;F!==_&&x[F]===0;)F++;for(var $=c.repeat(b);F<_;++F)$+=t.charAt(x[F]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,B=0;p[b]===c;)v++,b++;for(var D=(p.length-b)*u+1>>>0,_=new Uint8Array(D);p[b];){var x=n[p.charCodeAt(b)];if(x===255)return;for(var P=0,R=D-1;(x!==0||P<B)&&R!==-1;R--,P++)x+=a*_[R]>>>0,_[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");B=P,b++}if(p[b]!==" "){for(var N=D-B;N!==D&&_[N]===0;)N++;for(var F=new Uint8Array(v+(D-N)),$=v;N!==D;)F[$++]=_[N++];return F}}}function h(p){var b=d(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var I6=S6,A6=I6;const Zp=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")},B6=t=>new TextEncoder().encode(t),O6=t=>new TextDecoder().decode(t);class D6{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class $6{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yp(this,e)}}class P6{constructor(e){this.decoders=e}or(e){return Yp(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yp=(t,e)=>new P6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class T6{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new D6(e,n,r),this.decoder=new $6(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const zo=({name:t,prefix:e,encode:n,decode:r})=>new T6(t,e,n,r),cs=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=A6(n,e);return zo({prefix:t,name:e,encode:r,decode:s=>Zp(i(s))})},R6=(t,e,n,r)=>{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*n/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-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},N6=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Le=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>zo({prefix:e,name:t,encode(i){return N6(i,r,n)},decode(i){return R6(i,r,n,t)}}),C6=zo({prefix:"\0",name:"identity",encode:t=>O6(t),decode:t=>B6(t)});var U6=Object.freeze({__proto__:null,identity:C6});const F6=Le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var L6=Object.freeze({__proto__:null,base2:F6});const k6=Le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var q6=Object.freeze({__proto__:null,base8:k6});const M6=cs({prefix:"9",name:"base10",alphabet:"0123456789"});var j6=Object.freeze({__proto__:null,base10:M6});const z6=Le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),H6=Le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var V6=Object.freeze({__proto__:null,base16:z6,base16upper:H6});const K6=Le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),G6=Le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),W6=Le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Z6=Le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Y6=Le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),X6=Le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),J6=Le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Q6=Le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),e4=Le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var t4=Object.freeze({__proto__:null,base32:K6,base32upper:G6,base32pad:W6,base32padupper:Z6,base32hex:Y6,base32hexupper:X6,base32hexpad:J6,base32hexpadupper:Q6,base32z:e4});const n4=cs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),r4=cs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var i4=Object.freeze({__proto__:null,base36:n4,base36upper:r4});const s4=cs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),o4=cs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var a4=Object.freeze({__proto__:null,base58btc:s4,base58flickr:o4});const c4=Le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),u4=Le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),l4=Le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),f4=Le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var h4=Object.freeze({__proto__:null,base64:c4,base64pad:u4,base64url:l4,base64urlpad:f4});const Xp=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}"),d4=Xp.reduce((t,e,n)=>(t[n]=e,t),[]),p4=Xp.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function g4(t){return t.reduce((e,n)=>(e+=d4[n],e),"")}function y4(t){const e=[];for(const n of t){const r=p4[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const b4=zo({prefix:"\u{1F680}",name:"base256emoji",encode:g4,decode:y4});var w4=Object.freeze({__proto__:null,base256emoji:b4}),m4=Qp,Jp=128,v4=127,E4=~v4,x4=Math.pow(2,31);function Qp(t,e,n){e=e||[],n=n||0;for(var r=n;t>=x4;)e[n++]=t&255|Jp,t/=128;for(;t&E4;)e[n++]=t&255|Jp,t>>>=7;return e[n]=t|0,Qp.bytes=n-r+1,e}var _4=Iu,S4=128,e0=127;function Iu(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Iu.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&e0)<<i:(o&e0)*Math.pow(2,i),i+=7}while(o>=S4);return Iu.bytes=s-r,n}var I4=Math.pow(2,7),A4=Math.pow(2,14),B4=Math.pow(2,21),O4=Math.pow(2,28),D4=Math.pow(2,35),$4=Math.pow(2,42),P4=Math.pow(2,49),T4=Math.pow(2,56),R4=Math.pow(2,63),N4=function(t){return t<I4?1:t<A4?2:t<B4?3:t<O4?4:t<D4?5:t<$4?6:t<P4?7:t<T4?8:t<R4?9:10},C4={encode:m4,decode:_4,encodingLength:N4},t0=C4;const n0=(t,e,n=0)=>(t0.encode(t,e,n),e),r0=t=>t0.encodingLength(t),Au=(t,e)=>{const n=e.byteLength,r=r0(t),i=r+r0(n),s=new Uint8Array(i+n);return n0(t,s,0),n0(n,s,r),s.set(e,i),new U4(t,n,e,s)};class U4{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const i0=({name:t,code:e,encode:n})=>new F4(t,e,n);class F4{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Au(this.code,n):n.then(r=>Au(this.code,r))}else throw Error("Unknown type, must be binary type")}}const s0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),L4=i0({name:"sha2-256",code:18,encode:s0("SHA-256")}),k4=i0({name:"sha2-512",code:19,encode:s0("SHA-512")});var q4=Object.freeze({__proto__:null,sha256:L4,sha512:k4});const o0=0,M4="identity",a0=Zp;var j4=Object.freeze({__proto__:null,identity:{code:o0,name:M4,encode:a0,digest:t=>Au(o0,a0(t))}});new TextEncoder,new TextDecoder;const c0={...U6,...L6,...q6,...j6,...V6,...t4,...i4,...a4,...h4,...w4};({...q4,...j4});function u0(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const l0=u0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Bu=u0("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Wp(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),f0={utf8:l0,"utf-8":l0,hex:c0.base16,latin1:Bu,ascii:Bu,binary:Bu,...c0};function Ct(t,e="utf8"){const n=f0[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Su(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function wt(t,e="utf8"){const n=f0[e];if(!n)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"):n.encoder.encode(t).substring(1)}const z4={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"}},H4="Input must be an string, Buffer or Uint8Array";function V4(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(H4);return e}function K4(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Ho(t){return(4294967296+t).toString(16).substring(1)}function G4(t,e,n){let r=`
17
+ `+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=Ho(e[i]).toUpperCase(),r+=" ",r+=Ho(e[i+1]).toUpperCase();else if(n===64)r+=Ho(e[i+1]).toUpperCase(),r+=Ho(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
18
+ `+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function W4(t,e,n){let r=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-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=t(i),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var h0={normalizeInput:V4,toHex:K4,debugPrint:G4,testSpeed:W4};const Vo=h0;function Ko(t,e,n){const r=t[e]+t[n];let i=t[e+1]+t[n+1];r>=4294967296&&i++,t[e]=r,t[e+1]=i}function d0(t,e,n,r){let i=t[e]+n;n<0&&(i+=4294967296);let s=t[e+1]+r;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function p0(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function Qn(t,e,n,r,i,s){const o=us[i],a=us[i+1],c=us[s],u=us[s+1];Ko(te,t,e),d0(te,t,o,a);let l=te[r]^te[t],f=te[r+1]^te[t+1];te[r]=f,te[r+1]=l,Ko(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=l>>>24^f<<8,te[e+1]=f>>>24^l<<8,Ko(te,t,e),d0(te,t,c,u),l=te[r]^te[t],f=te[r+1]^te[t+1],te[r]=l>>>16^f<<16,te[r+1]=f>>>16^l<<16,Ko(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=f>>>31^l<<1,te[e+1]=l>>>31^f<<1}const g0=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Z4=[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],Ye=new Uint8Array(Z4.map(function(t){return t*2})),te=new Uint32Array(32),us=new Uint32Array(32);function y0(t,e){let n=0;for(n=0;n<16;n++)te[n]=t.h[n],te[n+16]=g0[n];for(te[24]=te[24]^t.t,te[25]=te[25]^t.t/4294967296,e&&(te[28]=~te[28],te[29]=~te[29]),n=0;n<32;n++)us[n]=p0(t.b,4*n);for(n=0;n<12;n++)Qn(0,8,16,24,Ye[n*16+0],Ye[n*16+1]),Qn(2,10,18,26,Ye[n*16+2],Ye[n*16+3]),Qn(4,12,20,28,Ye[n*16+4],Ye[n*16+5]),Qn(6,14,22,30,Ye[n*16+6],Ye[n*16+7]),Qn(0,10,20,30,Ye[n*16+8],Ye[n*16+9]),Qn(2,12,22,24,Ye[n*16+10],Ye[n*16+11]),Qn(4,14,16,26,Ye[n*16+12],Ye[n*16+13]),Qn(6,8,18,28,Ye[n*16+14],Ye[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^te[n]^te[n+16]}const er=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 b0(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};er.fill(0),er[0]=t,e&&(er[1]=e.length),er[2]=1,er[3]=1,n&&er.set(n,32),r&&er.set(r,48);for(let s=0;s<16;s++)i.h[s]=g0[s]^p0(er,s*4);return e&&(Ou(i,e),i.c=128),i}function Ou(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,y0(t,!1),t.c=0),t.b[t.c++]=e[n]}function w0(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;y0(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3);return e}function m0(t,e,n,r,i){n=n||64,t=Vo.normalizeInput(t),r&&(r=Vo.normalizeInput(r)),i&&(i=Vo.normalizeInput(i));const s=b0(n,e,r,i);return Ou(s,t),w0(s)}function Y4(t,e,n,r,i){const s=m0(t,e,n,r,i);return Vo.toHex(s)}var X4={blake2b:m0,blake2bHex:Y4,blake2bInit:b0,blake2bUpdate:Ou,blake2bFinal:w0};const v0=h0;function J4(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function tr(t,e,n,r,i,s){ae[t]=ae[t]+ae[e]+i,ae[r]=Go(ae[r]^ae[t],16),ae[n]=ae[n]+ae[r],ae[e]=Go(ae[e]^ae[n],12),ae[t]=ae[t]+ae[e]+s,ae[r]=Go(ae[r]^ae[t],8),ae[n]=ae[n]+ae[r],ae[e]=Go(ae[e]^ae[n],7)}function Go(t,e){return t>>>e^t<<32-e}const E0=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xe=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]),ae=new Uint32Array(16),ke=new Uint32Array(16);function x0(t,e){let n=0;for(n=0;n<8;n++)ae[n]=t.h[n],ae[n+8]=E0[n];for(ae[12]^=t.t,ae[13]^=t.t/4294967296,e&&(ae[14]=~ae[14]),n=0;n<16;n++)ke[n]=J4(t.b,4*n);for(n=0;n<10;n++)tr(0,4,8,12,ke[Xe[n*16+0]],ke[Xe[n*16+1]]),tr(1,5,9,13,ke[Xe[n*16+2]],ke[Xe[n*16+3]]),tr(2,6,10,14,ke[Xe[n*16+4]],ke[Xe[n*16+5]]),tr(3,7,11,15,ke[Xe[n*16+6]],ke[Xe[n*16+7]]),tr(0,5,10,15,ke[Xe[n*16+8]],ke[Xe[n*16+9]]),tr(1,6,11,12,ke[Xe[n*16+10]],ke[Xe[n*16+11]]),tr(2,7,8,13,ke[Xe[n*16+12]],ke[Xe[n*16+13]]),tr(3,4,9,14,ke[Xe[n*16+14]],ke[Xe[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=ae[n]^ae[n+8]}function _0(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(E0),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Du(r,e),r.c=64),r}function Du(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,x0(t,!1),t.c=0),t.b[t.c++]=e[n]}function S0(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;x0(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3)&255;return e}function I0(t,e,n){n=n||32,t=v0.normalizeInput(t);const r=_0(n,e);return Du(r,t),S0(r)}function Q4(t,e,n){const r=I0(t,e,n);return v0.toHex(r)}var e5={blake2s:I0,blake2sHex:Q4,blake2sInit:_0,blake2sUpdate:Du,blake2sFinal:S0};const ls=X4,fs=e5;var t5={blake2b:ls.blake2b,blake2bHex:ls.blake2bHex,blake2bInit:ls.blake2bInit,blake2bUpdate:ls.blake2bUpdate,blake2bFinal:ls.blake2bFinal,blake2s:fs.blake2s,blake2sHex:fs.blake2sHex,blake2sInit:fs.blake2sInit,blake2sUpdate:fs.blake2sUpdate,blake2sFinal:fs.blake2sFinal};const n5=":";function Wo(t){const[e,n]=t.split(n5);return{namespace:e,reference:n}}function A0(t,e){return t.includes(":")?[t]:e.chains||[]}var r5=Object.defineProperty,i5=Object.defineProperties,s5=Object.getOwnPropertyDescriptors,B0=Object.getOwnPropertySymbols,o5=Object.prototype.hasOwnProperty,a5=Object.prototype.propertyIsEnumerable,$u=(t,e,n)=>e in t?r5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,O0=(t,e)=>{for(var n in e||(e={}))o5.call(e,n)&&$u(t,n,e[n]);if(B0)for(var n of B0(e))a5.call(e,n)&&$u(t,n,e[n]);return t},c5=(t,e)=>i5(t,s5(e)),D0=(t,e,n)=>$u(t,typeof e!="symbol"?e+"":e,n);const u5="ReactNative",Bt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},l5="js";function Zo(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function nr(){return!Or()&&!!fc()&&navigator.product===u5}function f5(){return nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function h5(){return nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function wi(){return!Zo()&&!!fc()&&!!Or()}function hs(){return nr()?Bt.reactNative:Zo()?Bt.node:wi()?Bt.browser:Bt.unknown}function $0(){var t;try{return nr()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function d5(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function p5(t){var e,n;const r=P0();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),c5(O0(O0({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function P0(){return $h()||{name:"",description:"",url:"",icons:[""]}}function g5(){if(hs()===Bt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=Xv();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 y5(){var t;const e=hs();return e===Bt.browser?[e,((t=Dh())==null?void 0:t.host)||"unknown"].join(":"):e}function T0(t,e,n){const r=g5(),i=y5();return[[t,e].join("-"),[l5,n].join("-"),r,i].join("/")}function b5({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=T0(t,e,r),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=d5(u[1]||"",f);return u[0]+"?"+d}function Lr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function Pu(t){return Object.fromEntries(t.entries())}function Tu(t){return new Map(Object.entries(t))}function kr(t=K.FIVE_MINUTES,e){const n=K.toMiliseconds(t||K.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(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)},n),r=a,i=c})}}function rn(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function R0(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 w5(t){return R0("topic",t)}function m5(t){return R0("id",t)}function N0(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function De(t,e){return K.fromMiliseconds((e||Date.now())+K.toMiliseconds(t))}function rr(t){return Date.now()>=K.toMiliseconds(t)}function le(t,e){return`${t}${e?`:${e}`:""}`}function qr(t=[],e=[]){return[...new Set([...t,...e])]}async function v5({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=E5(s,t,e),a=hs();if(a===Bt.browser){if(!((r=Or())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}x5(o)}else a===Bt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function E5(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;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}${A5(r,!0)}`}else i=`${i}/wc?${r}`;return i}function x5(t){let e="_self";I5()?e="_top":(S5()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function _5(t,e){let n="";try{if(wi()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function C0(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function U0(){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 Ru(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function S5(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function I5(){try{return window.self!==window.top}catch{return!1}}function A5(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function F0(t){return Buffer.from(t,"base64").toString("utf-8")}function B5(t){return new Promise(e=>setTimeout(e,t))}class O5{constructor({limit:e}){D0(this,"limit"),D0(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}}const Yo=BigInt(2**32-1),L0=BigInt(32);function k0(t,e=!1){return e?{h:Number(t&Yo),l:Number(t>>L0&Yo)}:{h:Number(t>>L0&Yo)|0,l:Number(t&Yo)|0}}function q0(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=k0(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const M0=(t,e,n)=>t>>>n,j0=(t,e,n)=>t<<32-n|e>>>n,ir=(t,e,n)=>t>>>n|e<<32-n,sr=(t,e,n)=>t<<32-n|e>>>n,ds=(t,e,n)=>t<<64-n|e>>>n-32,ps=(t,e,n)=>t>>>n-32|e<<64-n,D5=(t,e)=>e,$5=(t,e)=>t,P5=(t,e,n)=>t<<n|e>>>32-n,T5=(t,e,n)=>e<<n|t>>>32-n,R5=(t,e,n)=>e<<n-32|t>>>64-n,N5=(t,e,n)=>t<<n-32|e>>>64-n;function Kt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const Nu=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Cu=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,C5=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),U5=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,F5=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),L5=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,mi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Xo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Bn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Gt(t,...e){if(!Xo(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 Jo(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Bn(t.outputLen),Bn(t.blockLen)}function or(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 Uu(t,e){Gt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function gs(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ut(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Fu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function sn(t,e){return t<<32-e|t>>>e}const z0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function H0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const On=z0?t=>t:t=>H0(t);function k5(t){for(let e=0;e<t.length;e++)t[e]=H0(t[e]);return t}const ar=z0?t=>t:k5,V0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",q5=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vi(t){if(Gt(t),V0)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=q5[t[n]];return e}const Dn={_0:48,_9:57,A:65,F:70,a:97,f:102};function K0(t){if(t>=Dn._0&&t<=Dn._9)return t-Dn._0;if(t>=Dn.A&&t<=Dn.F)return t-(Dn.A-10);if(t>=Dn.a&&t<=Dn.f)return t-(Dn.a-10)}function Qo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(V0)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=K0(t.charCodeAt(s)),a=K0(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)}r[i]=o*16+a}return r}function G0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Wt(t){return typeof t=="string"&&(t=G0(t)),Gt(t),t}function cr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Gt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class ea{}function ys(t){const e=r=>t().update(Wt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function M5(t){const e=(r,i)=>t(i).update(Wt(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Mr(t=32){if(mi&&typeof mi.getRandomValues=="function")return mi.getRandomValues(new Uint8Array(t));if(mi&&typeof mi.randomBytes=="function")return Uint8Array.from(mi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const j5=BigInt(0),bs=BigInt(1),z5=BigInt(2),H5=BigInt(7),V5=BigInt(256),K5=BigInt(113),W0=[],Z0=[],Y0=[];for(let t=0,e=bs,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],W0.push(2*(5*r+n)),Z0.push((t+1)*(t+2)/2%64);let i=j5;for(let s=0;s<7;s++)e=(e<<bs^(e>>H5)*K5)%V5,e&z5&&(i^=bs<<(bs<<BigInt(s))-bs);Y0.push(i)}const X0=q0(Y0,!0),G5=X0[0],W5=X0[1],J0=(t,e,n)=>n>32?R5(t,e,n):P5(t,e,n),Q0=(t,e,n)=>n>32?N5(t,e,n):T5(t,e,n);function Z5(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[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=n[c],l=n[c+1],f=J0(u,l,1)^n[a],d=Q0(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Z0[o],c=J0(i,s,a),u=Q0(i,s,a),l=W0[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++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=G5[r],t[1]^=W5[r]}Ut(n)}class Lu extends ea{constructor(e,n,r,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=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Bn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=gs(this.state)}clone(){return this._cloneInto()}keccak(){ar(this.state32),Z5(this.state32,this.rounds),ar(this.state32),this.posOut=0,this.pos=0}update(e){or(this),e=Wt(e),Gt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,n&128&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){or(this,!1),Gt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.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 Bn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Uu(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,Ut(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new Lu(n,r,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=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Y5=(t,e,n)=>ys(()=>new Lu(e,t,n)),X5=Y5(1,136,256/8);function J5(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Q5(t,e,n){return t&e^~t&n}function e_(t,e,n){return t&e^t&n^e&n}class eg extends ea{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=Fu(this.buffer)}update(e){or(this),e=Wt(e),Gt(e);const{view:n,buffer:r,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=Fu(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){or(this),Uu(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Ut(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;J5(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Fu(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const ur=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Je=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Qe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),t_=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]),lr=new Uint32Array(64);class n_ extends eg{constructor(e=32){super(64,e,8,!1),this.A=ur[0]|0,this.B=ur[1]|0,this.C=ur[2]|0,this.D=ur[3]|0,this.E=ur[4]|0,this.F=ur[5]|0,this.G=ur[6]|0,this.H=ur[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)lr[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=lr[f-15],h=lr[f-2],p=sn(d,7)^sn(d,18)^d>>>3,b=sn(h,17)^sn(h,19)^h>>>10;lr[f]=b+lr[f-7]+p+lr[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const d=sn(a,6)^sn(a,11)^sn(a,25),h=l+d+Q5(a,c,u)+t_[f]+lr[f]|0,p=(sn(r,2)^sn(r,13)^sn(r,22))+e_(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+p|0}r=r+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(r,i,s,o,a,c,u,l)}roundClean(){Ut(lr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ut(this.buffer)}}const tg=q0(["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_=tg[0],i_=tg[1],fr=new Uint32Array(80),hr=new Uint32Array(80);class ku extends eg{constructor(e=64){super(128,e,16,!1),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}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:d,Gh:h,Gl:p,Hh:b,Hl:v}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v){this.Ah=e|0,this.Al=n|0,this.Bh=r|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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=b|0,this.Hl=v|0}process(e,n){for(let _=0;_<16;_++,n+=4)fr[_]=e.getUint32(n),hr[_]=e.getUint32(n+=4);for(let _=16;_<80;_++){const x=fr[_-15]|0,P=hr[_-15]|0,R=ir(x,P,1)^ir(x,P,8)^M0(x,P,7),N=sr(x,P,1)^sr(x,P,8)^j0(x,P,7),F=fr[_-2]|0,$=hr[_-2]|0,z=ir(F,$,19)^ds(F,$,61)^M0(F,$,6),M=sr(F,$,19)^ps(F,$,61)^j0(F,$,6),E=C5(N,M,hr[_-7],hr[_-16]),y=U5(E,R,z,fr[_-7],fr[_-16]);fr[_]=y|0,hr[_]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:b,Gl:v,Hh:B,Hl:D}=this;for(let _=0;_<80;_++){const x=ir(f,d,14)^ir(f,d,18)^ds(f,d,41),P=sr(f,d,14)^sr(f,d,18)^ps(f,d,41),R=f&h^~f&b,N=d&p^~d&v,F=F5(D,P,N,i_[_],hr[_]),$=L5(F,B,x,R,r_[_],fr[_]),z=F|0,M=ir(r,i,28)^ds(r,i,34)^ds(r,i,39),E=sr(r,i,28)^ps(r,i,34)^ps(r,i,39),y=r&s^r&a^s&a,m=i&o^i&c^o&c;B=b|0,D=v|0,b=h|0,v=p|0,h=f|0,p=d|0,{h:f,l:d}=Kt(u|0,l|0,$|0,z|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const g=Nu(z,E,m);r=Cu(g,$,M,y),i=g|0}({h:r,l:i}=Kt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Kt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Kt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Kt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=Kt(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=Kt(this.Fh|0,this.Fl|0,h|0,p|0),{h:b,l:v}=Kt(this.Gh|0,this.Gl|0,b|0,v|0),{h:B,l:D}=Kt(this.Hh|0,this.Hl|0,B|0,D|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,b,v,B,D)}roundClean(){Ut(fr,hr)}destroy(){Ut(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class s_ extends ku{constructor(){super(48),this.Ah=Je[0]|0,this.Al=Je[1]|0,this.Bh=Je[2]|0,this.Bl=Je[3]|0,this.Ch=Je[4]|0,this.Cl=Je[5]|0,this.Dh=Je[6]|0,this.Dl=Je[7]|0,this.Eh=Je[8]|0,this.El=Je[9]|0,this.Fh=Je[10]|0,this.Fl=Je[11]|0,this.Gh=Je[12]|0,this.Gl=Je[13]|0,this.Hh=Je[14]|0,this.Hl=Je[15]|0}}const et=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class o_ extends ku{constructor(){super(32),this.Ah=et[0]|0,this.Al=et[1]|0,this.Bh=et[2]|0,this.Bl=et[3]|0,this.Ch=et[4]|0,this.Cl=et[5]|0,this.Dh=et[6]|0,this.Dl=et[7]|0,this.Eh=et[8]|0,this.El=et[9]|0,this.Fh=et[10]|0,this.Fl=et[11]|0,this.Gh=et[12]|0,this.Gl=et[13]|0,this.Hh=et[14]|0,this.Hl=et[15]|0}}const ta=ys(()=>new n_),a_=ys(()=>new ku),c_=ys(()=>new s_),u_=ys(()=>new o_),l_=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]),$e=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Y=new Uint32Array(32);function dr(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],b=Y[2*r+1],v=Nu(c,l,o);u=Cu(v,u,f,a),c=v|0,{Dh:b,Dl:p}={Dh:b^u,Dl:p^c},{Dh:b,Dl:p}={Dh:D5(b,p),Dl:$5(b)},{h,l:d}=Kt(h,d,b,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:ir(f,l,24),Bl:sr(f,l,24)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=b}function pr(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],b=Y[2*r+1],v=Nu(c,l,o);u=Cu(v,u,f,a),c=v|0,{Dh:b,Dl:p}={Dh:b^u,Dl:p^c},{Dh:b,Dl:p}={Dh:ir(b,p,16),Dl:sr(b,p,16)},{h,l:d}=Kt(h,d,b,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:ds(f,l,63),Bl:ps(f,l,63)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=b}function f_(t,e={},n,r,i){if(Bn(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class h_ extends ea{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Bn(e),Bn(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=gs(this.buffer)}update(e){or(this),e=Wt(e),Gt(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(ar(i),this.compress(i,0,!1),ar(i),this.pos=0);const u=Math.min(n-this.pos,s-c),l=o+c;if(u===n&&!(l%4)&&c+u<s){const f=new Uint32Array(a,l,Math.floor((s-c)/4));ar(f);for(let d=0;c+n<s;d+=i.length,c+=n)this.length+=n,this.compress(f,d,!1);ar(f);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){or(this),Uu(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,Ut(this.buffer.subarray(n)),ar(r),this.compress(r,0,!0),ar(r);const i=gs(e);this.get().forEach((s,o)=>i[o]=On(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class d_ extends h_{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=$e[0]|0,this.v0h=$e[1]|0,this.v1l=$e[2]|0,this.v1h=$e[3]|0,this.v2l=$e[4]|0,this.v2h=$e[5]|0,this.v3l=$e[6]|0,this.v3h=$e[7]|0,this.v4l=$e[8]|0,this.v4h=$e[9]|0,this.v5l=$e[10]|0,this.v5h=$e[11]|0,this.v6l=$e[12]|0,this.v6h=$e[13]|0,this.v7l=$e[14]|0,this.v7h=$e[15]|0,f_(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Wt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Wt(s);const a=gs(s);this.v4l^=On(a[0]),this.v4h^=On(a[1]),this.v5l^=On(a[2]),this.v5h^=On(a[3])}if(i!==void 0){i=Wt(i);const a=gs(i);this.v6l^=On(a[0]),this.v6h^=On(a[1]),this.v7l^=On(a[2]),this.v7h^=On(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:f,v5h:d,v6l:h,v6h:p,v7l:b,v7h:v}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,b,v){this.v0l=e|0,this.v0h=n|0,this.v1l=r|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=d|0,this.v6l=h|0,this.v6h=p|0,this.v7l=b|0,this.v7h=v|0}compress(e,n,r){this.get().forEach((c,u)=>Y[u]=c),Y.set($e,16);let{h:i,l:s}=k0(BigInt(this.length));Y[24]=$e[8]^s,Y[25]=$e[9]^i,r&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=l_;for(let c=0;c<12;c++)dr(0,4,8,12,e,n+2*a[o++]),pr(0,4,8,12,e,n+2*a[o++]),dr(1,5,9,13,e,n+2*a[o++]),pr(1,5,9,13,e,n+2*a[o++]),dr(2,6,10,14,e,n+2*a[o++]),pr(2,6,10,14,e,n+2*a[o++]),dr(3,7,11,15,e,n+2*a[o++]),pr(3,7,11,15,e,n+2*a[o++]),dr(0,5,10,15,e,n+2*a[o++]),pr(0,5,10,15,e,n+2*a[o++]),dr(1,6,11,12,e,n+2*a[o++]),pr(1,6,11,12,e,n+2*a[o++]),dr(2,7,8,13,e,n+2*a[o++]),pr(2,7,8,13,e,n+2*a[o++]),dr(3,4,9,14,e,n+2*a[o++]),pr(3,4,9,14,e,n+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],Ut(Y)}destroy(){this.destroyed=!0,Ut(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const p_=M5(t=>new d_(t)),g_="https://rpc.walletconnect.org/v1";function ng(t){const e=`Ethereum Signed Message:
19
+ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(X5(n)).toString("hex")}async function y_(t,e,n,r,i,s){switch(n.t){case"eip191":return await b_(t,e,n.s);case"eip1271":return await w_(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function b_(t,e,n){const r=y8(n);return Ax({payload:ng(e),signature:r}).toLowerCase()===t.toLowerCase()}async function w_(t,e,n,r,i,s){const o=Wo(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),f=(e.startsWith("0x")?e:ng(e)).substring(2),d=a+f+c+l+u,h=await fetch(`${s||g_}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:m_(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:p}=await h.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function m_(){return Date.now()+Math.floor(Math.random()*1e3)}function v_(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return rs.encode(s)}function E_(t){const e=new Uint8Array(Buffer.from(t,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const i=p_(r,{dkLen:32});return rs.encode(i)}function rg(t){const e=new Uint8Array(ta(x_(t)));return rs.encode(e)}function x_(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 ig(t){const e=Buffer.from(t,"base64"),n=_6(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=g6(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=u_(s);return Ex.encode(o).replace(/=+$/,"")}function qu(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function __(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(qu(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(qu(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(qu(r.length)),i.push(r);const s=Buffer.concat(i),o=ta(s);return Buffer.from(o).toString("hex").toUpperCase()}function S_(t){var e,n;const r=[];try{if(typeof t=="string")return r.push(t),r;if(typeof t!="object")return r;t!=null&&t.id&&r.push(t.id);const i=(n=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:n.transactionHashes;i&&r.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return r}var I_=Object.defineProperty,A_=Object.defineProperties,B_=Object.getOwnPropertyDescriptors,sg=Object.getOwnPropertySymbols,O_=Object.prototype.hasOwnProperty,D_=Object.prototype.propertyIsEnumerable,og=(t,e,n)=>e in t?I_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$_=(t,e)=>{for(var n in e||(e={}))O_.call(e,n)&&og(t,n,e[n]);if(sg)for(var n of sg(e))D_.call(e,n)&&og(t,n,e[n]);return t},P_=(t,e)=>A_(t,B_(e));const ag="did:pkh:",T_={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},R_=t=>t?T_[t]||t:"",na=t=>t?.split(":"),N_=t=>{const e=t&&na(t);if(e)return t.includes(ag)?e[3]:e[1]},C_=t=>{const e=t&&na(t);if(e)return t.includes(ag)?e[2]:e[0]},Mu=t=>{const e=t&&na(t);if(e)return e[2]+":"+e[3]},ra=t=>{const e=t&&na(t);if(e)return e.pop()};async function cg(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=ug(i,i.iss),o=ra(i.iss);return await y_(o,s,r,Mu(i.iss),n)}const ug=(t,e)=>{const n=`${t.domain} wants you to sign in with your ${R_(C_(e))} account:`,r=ra(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: ${N_(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,d=t.requestId?`Request ID: ${t.requestId}`:void 0,h=t.resources?`Resources:${t.resources.map(b=>`
20
+ - ${b}`).join("")}`:void 0,p=ia(t.resources);if(p){const b=ws(p);i=H_(i,b)}return[n,r,"",i,"",s,o,a,c,u,l,f,d,h].filter(b=>b!=null).join(`
21
+ `)};function U_(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function F_(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function jr(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(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[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 L_(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:k_(e,n,r)}}}function k_(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function lg(t){return jr(t),`urn:recap:${U_(t).replace(/=/g,"")}`}function ws(t){const e=F_(t.replace("urn:recap:",""));return jr(e),e}function q_(t,e,n){const r=L_(t,e,n);return lg(r)}function M_(t){return t&&t.includes("urn:recap:")}function j_(t,e){const n=ws(t),r=ws(e),i=z_(n,r);return lg(i)}function z_(t,e){jr(t),jr(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.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;r.att[i]=P_($_({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function H_(t="",e){jr(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];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,d)=>f.action.localeCompare(d.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}'.`));r.push(l.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${t?t+" ":""}${o}`}function fg(t){var e;const n=ws(t);jr(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function hg(t){const e=ws(t);jr(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function ia(t){if(!t)return;const e=t?.[t.length-1];return M_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function dg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ju(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function zu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function mt(t,...e){if(!dg(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 pg(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 V_(t,e){mt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function gr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ei(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function K_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const G_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function W_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Hu(t){if(typeof t=="string")t=W_(t);else if(dg(t))t=Vu(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Z_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function Y_(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const X_=(t,e)=>{function n(r,...i){if(mt(r),!G_)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?mt(u):mt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&mt(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");mt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,mt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(mt(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(n,t),n};function gg(t,e,n=!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(n&&!Q_(e))throw new Error("invalid output, must be aligned");return e}function yg(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function J_(t,e,n){ju(n);const r=new Uint8Array(16),i=K_(r);return yg(i,0,BigInt(e),n),yg(i,8,BigInt(t),n),r}function Q_(t){return t.byteOffset%4===0}function Vu(t){return Uint8Array.from(t)}const bg=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),eS=bg("expand 16-byte k"),tS=bg("expand 32-byte k"),nS=gr(eS),rS=gr(tS);function ce(t,e){return t<<e|t>>>32-e}function Ku(t){return t.byteOffset%4===0}const sa=64,iS=16,wg=2**32-1,mg=new Uint32Array;function sS(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(sa),l=gr(u),f=Ku(i)&&Ku(s),d=f?gr(i):mg,h=f?gr(s):mg;for(let p=0;p<c;o++){if(t(e,n,r,l,o,a),o>=wg)throw new Error("arx: counter overflow");const b=Math.min(sa,c-p);if(f&&b===sa){const v=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let B=0,D;B<iS;B++)D=v+B,h[D]=d[D]^l[B];p+=sa;continue}for(let v=0,B;v<b;v++)B=p+v,s[B]=i[B]^u[v];p+=b}}function oS(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Z_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return zu(i),zu(o),ju(s),ju(n),(a,c,u,l,f=0)=>{mt(a),mt(c),mt(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),mt(l),zu(f),f<0||f>=wg)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let p=a.length,b,v;if(p===32)h.push(b=Vu(a)),v=rS;else if(p===16&&n)b=new Uint8Array(32),b.set(a),b.set(a,16),v=nS,h.push(b);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Ku(c)||h.push(c=Vu(c));const B=gr(b);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(v,B,gr(c.subarray(0,16)),B),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 x=new Uint8Array(12);x.set(c,s?0:12-c.length),c=x,h.push(c)}const _=gr(c);return sS(t,v,B,_,u,l,f,o),Ei(...h),l}}const qe=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class aS{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=Hu(e),mt(e,32);const n=qe(e,0),r=qe(e,2),i=qe(e,4),s=qe(e,6),o=qe(e,8),a=qe(e,10),c=qe(e,12),u=qe(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>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]=qe(e,16+2*l)}process(e,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],f=o[4],d=o[5],h=o[6],p=o[7],b=o[8],v=o[9],B=qe(e,n+0),D=qe(e,n+2),_=qe(e,n+4),x=qe(e,n+6),P=qe(e,n+8),R=qe(e,n+10),N=qe(e,n+12),F=qe(e,n+14);let $=s[0]+(B&8191),z=s[1]+((B>>>13|D<<3)&8191),M=s[2]+((D>>>10|_<<6)&8191),E=s[3]+((_>>>7|x<<9)&8191),y=s[4]+((x>>>4|P<<12)&8191),m=s[5]+(P>>>1&8191),g=s[6]+((P>>>14|R<<2)&8191),w=s[7]+((R>>>11|N<<5)&8191),S=s[8]+((N>>>8|F<<8)&8191),A=s[9]+(F>>>5|i),I=0,O=I+$*a+z*(5*v)+M*(5*b)+E*(5*p)+y*(5*h);I=O>>>13,O&=8191,O+=m*(5*d)+g*(5*f)+w*(5*l)+S*(5*u)+A*(5*c),I+=O>>>13,O&=8191;let T=I+$*c+z*a+M*(5*v)+E*(5*b)+y*(5*p);I=T>>>13,T&=8191,T+=m*(5*h)+g*(5*d)+w*(5*f)+S*(5*l)+A*(5*u),I+=T>>>13,T&=8191;let L=I+$*u+z*c+M*a+E*(5*v)+y*(5*b);I=L>>>13,L&=8191,L+=m*(5*p)+g*(5*h)+w*(5*d)+S*(5*f)+A*(5*l),I+=L>>>13,L&=8191;let U=I+$*l+z*u+M*c+E*a+y*(5*v);I=U>>>13,U&=8191,U+=m*(5*b)+g*(5*p)+w*(5*h)+S*(5*d)+A*(5*f),I+=U>>>13,U&=8191;let k=I+$*f+z*l+M*u+E*c+y*a;I=k>>>13,k&=8191,k+=m*(5*v)+g*(5*b)+w*(5*p)+S*(5*h)+A*(5*d),I+=k>>>13,k&=8191;let C=I+$*d+z*f+M*l+E*u+y*c;I=C>>>13,C&=8191,C+=m*a+g*(5*v)+w*(5*b)+S*(5*p)+A*(5*h),I+=C>>>13,C&=8191;let q=I+$*h+z*d+M*f+E*l+y*u;I=q>>>13,q&=8191,q+=m*c+g*a+w*(5*v)+S*(5*b)+A*(5*p),I+=q>>>13,q&=8191;let j=I+$*p+z*h+M*d+E*f+y*l;I=j>>>13,j&=8191,j+=m*u+g*c+w*a+S*(5*v)+A*(5*b),I+=j>>>13,j&=8191;let W=I+$*b+z*p+M*h+E*d+y*f;I=W>>>13,W&=8191,W+=m*l+g*u+w*c+S*a+A*(5*v),I+=W>>>13,W&=8191;let V=I+$*v+z*b+M*p+E*h+y*d;I=V>>>13,V&=8191,V+=m*f+g*l+w*u+S*c+A*a,I+=V>>>13,V&=8191,I=(I<<2)+I|0,I=I+O|0,O=I&8191,I=I>>>13,T+=I,s[0]=O,s[1]=T,s[2]=L,s[3]=U,s[4]=k,s[5]=C,s[6]=q,s[7]=j,s[8]=W,s[9]=V}finalize(){const{h:e,pad:n}=this,r=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,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Ei(r)}update(e){pg(this),e=Hu(e),mt(e);const{buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Ei(this.h,this.r,this.buffer,this.pad)}digestInto(e){pg(this),V_(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function cS(t){const e=(r,i)=>t(i).update(Hu(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const uS=cS(t=>new aS(t));function lS(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],d=e[2],h=e[3],p=e[4],b=e[5],v=e[6],B=e[7],D=i,_=n[0],x=n[1],P=n[2],R=o,N=a,F=c,$=u,z=l,M=f,E=d,y=h,m=p,g=b,w=v,S=B,A=D,I=_,O=x,T=P;for(let U=0;U<s;U+=2)R=R+z|0,A=ce(A^R,16),m=m+A|0,z=ce(z^m,12),R=R+z|0,A=ce(A^R,8),m=m+A|0,z=ce(z^m,7),N=N+M|0,I=ce(I^N,16),g=g+I|0,M=ce(M^g,12),N=N+M|0,I=ce(I^N,8),g=g+I|0,M=ce(M^g,7),F=F+E|0,O=ce(O^F,16),w=w+O|0,E=ce(E^w,12),F=F+E|0,O=ce(O^F,8),w=w+O|0,E=ce(E^w,7),$=$+y|0,T=ce(T^$,16),S=S+T|0,y=ce(y^S,12),$=$+y|0,T=ce(T^$,8),S=S+T|0,y=ce(y^S,7),R=R+M|0,T=ce(T^R,16),w=w+T|0,M=ce(M^w,12),R=R+M|0,T=ce(T^R,8),w=w+T|0,M=ce(M^w,7),N=N+E|0,A=ce(A^N,16),S=S+A|0,E=ce(E^S,12),N=N+E|0,A=ce(A^N,8),S=S+A|0,E=ce(E^S,7),F=F+y|0,I=ce(I^F,16),m=m+I|0,y=ce(y^m,12),F=F+y|0,I=ce(I^F,8),m=m+I|0,y=ce(y^m,7),$=$+z|0,O=ce(O^$,16),g=g+O|0,z=ce(z^g,12),$=$+z|0,O=ce(O^$,8),g=g+O|0,z=ce(z^g,7);let L=0;r[L++]=o+R|0,r[L++]=a+N|0,r[L++]=c+F|0,r[L++]=u+$|0,r[L++]=l+z|0,r[L++]=f+M|0,r[L++]=d+E|0,r[L++]=h+y|0,r[L++]=p+m|0,r[L++]=b+g|0,r[L++]=v+w|0,r[L++]=B+S|0,r[L++]=D+A|0,r[L++]=_+I|0,r[L++]=x+O|0,r[L++]=P+T|0}const fS=oS(lS,{counterRight:!1,counterLength:4,allowShortKeys:!1}),hS=new Uint8Array(16),vg=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(hS.subarray(n))},dS=new Uint8Array(32);function Eg(t,e,n,r,i){const s=t(e,n,dS),o=uS.create(s);i&&vg(o,i),vg(o,r);const a=J_(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Ei(s,a),c}const pS=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=gg(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Eg(t,e,n,a,r);return s.set(c,o),Ei(c),s},decrypt(i,s){s=gg(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Eg(t,e,n,o,r);if(!Y_(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Ei(c),s}}),xg=X_({blockSize:64,nonceLength:12,tagLength:16},pS(fS));class _g extends ea{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Jo(e);const r=Wt(n);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(r.length>i?e.create().update(r).digest():r);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),Ut(s)}update(e){return or(this),this.iHash.update(e),this}digestInto(e){or(this),Gt(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:n,iHash:r,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=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const oa=(t,e,n)=>new _g(t,e).update(n).digest();oa.create=(t,e)=>new _g(t,e);function gS(t,e,n){return Jo(t),n===void 0&&(n=new Uint8Array(t.outputLen)),oa(t,Wt(n),Wt(e))}const Gu=Uint8Array.from([0]),Sg=Uint8Array.of();function yS(t,e,n,r=32){Jo(t),Bn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=Sg);const o=new Uint8Array(s*i),a=oa.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Gu[0]=l+1,c.update(l===0?Sg:u).update(n).update(Gu).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),Ut(u,Gu),o.slice(0,r)}const bS=(t,e,n,r,i)=>yS(t,gS(t,e,n),r,i),aa=ta,Wu=BigInt(0),Zu=BigInt(1);function ca(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function zr(t,e,n=""){const r=Xo(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function ua(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Ig(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Wu:BigInt("0x"+t)}function la(t){return Ig(vi(t))}function fa(t){return Gt(t),Ig(vi(Uint8Array.from(t).reverse()))}function Yu(t,e){return Qo(t.toString(16).padStart(e*2,"0"))}function Xu(t,e){return Yu(t,e).reverse()}function tt(t,e,n){let r;if(typeof e=="string")try{r=Qo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Xo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Ju=t=>typeof t=="bigint"&&Wu<=t;function wS(t,e,n){return Ju(t)&&Ju(e)&&Ju(n)&&e<=t&&t<n}function Qu(t,e,n,r){if(!wS(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ag(t){let e;for(e=0;t>Wu;t>>=Zu,e+=1);return e}const ms=t=>(Zu<<BigInt(t))-Zu;function mS(t,e,n){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 n!="function")throw new Error("hmacFn must be a function");const r=d=>new Uint8Array(d),i=d=>Uint8Array.of(d);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...d)=>n(o,s,...d),l=(d=r(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 h=[];for(;d<e;){s=u();const p=s.slice();h.push(p),d+=s.length}return cr(...h)};return(d,h)=>{c(),l(d);let p;for(;!(p=h(f()));)l();return c(),p}}function ha(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(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])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function Bg(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const vt=BigInt(0),ut=BigInt(1),Hr=BigInt(2),Og=BigInt(3),Dg=BigInt(4),$g=BigInt(5),vS=BigInt(7),Pg=BigInt(8),ES=BigInt(9),Tg=BigInt(16);function Ot(t,e){const n=t%e;return n>=vt?n:e+n}function Zt(t,e,n){let r=t;for(;e-- >vt;)r*=r,r%=n;return r}function Rg(t,e){if(t===vt)throw new Error("invert: expected non-zero number");if(e<=vt)throw new Error("invert: expected positive modulus, got "+e);let n=Ot(t,e),r=e,i=vt,s=ut;for(;n!==vt;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==ut)throw new Error("invert: does not exist");return Ot(i,e)}function el(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ng(t,e){const n=(t.ORDER+ut)/Dg,r=t.pow(e,n);return el(t,r,e),r}function xS(t,e){const n=(t.ORDER-$g)/Pg,r=t.mul(e,Hr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Hr),i),a=t.mul(s,t.sub(o,t.ONE));return el(t,a,e),a}function _S(t){const e=yr(t),n=Cg(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+vS)/Tg;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const b=a.eql(a.sqr(l),c),v=a.cmov(u,l,b);return el(a,v,c),v}}function Cg(t){if(t<Og)throw new Error("sqrt is not defined for small field");let e=t-ut,n=0;for(;e%Hr===vt;)e/=Hr,n++;let r=Hr;const i=yr(t);for(;Fg(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ng;let s=i.pow(r,e);const o=(e+ut)/Hr;return function(a,c){if(a.is0(c))return c;if(Fg(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),f=a.pow(c,e),d=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(h++,p=a.sqr(p),h===u)throw new Error("Cannot find square root");const b=ut<<BigInt(u-h-1),v=a.pow(l,b);u=h,l=a.sqr(v),f=a.mul(f,l),d=a.mul(d,v)}return d}}function SS(t){return t%Dg===Og?Ng:t%Pg===$g?xS:t%Tg===ES?_S(t):Cg(t)}const IS=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function AS(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=IS.reduce((r,i)=>(r[i]="function",r),e);return ha(t,n),t}function BS(t,e,n){if(n<vt)throw new Error("invalid exponent, negatives unsupported");if(n===vt)return t.ONE;if(n===ut)return e;let r=t.ONE,i=e;for(;n>vt;)n&ut&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ut;return r}function Ug(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Fg(t,e){const n=(t.ORDER-ut)/Hr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Lg(t,e){e!==void 0&&Bn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function yr(t,e,n=!1,r={}){if(t<=vt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=Lg(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:ms(c),ZERO:vt,ONE:ut,allowedLengths:a,create:d=>Ot(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return vt<=d&&d<t},is0:d=>d===vt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ut)===ut,neg:d=>Ot(-d,t),eql:(d,h)=>d===h,sqr:d=>Ot(d*d,t),add:(d,h)=>Ot(d+h,t),sub:(d,h)=>Ot(d-h,t),mul:(d,h)=>Ot(d*h,t),pow:(d,h)=>BS(f,d,h),div:(d,h)=>Ot(d*Rg(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Rg(d,t),sqrt:s||(d=>(l||(l=SS(t)),l(f,d))),toBytes:d=>n?Xu(d,u):Yu(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const b=new Uint8Array(u);b.set(d,n?0:b.length-d.length),d=b}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?fa(d):la(d);if(o&&(p=Ot(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>Ug(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function kg(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 qg(t){const e=kg(t);return e+Math.ceil(e/2)}function OS(t,e,n=!1){const r=t.length,i=kg(e),s=qg(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?fa(t):la(t),a=Ot(o,e-ut)+ut;return n?Xu(a,i):Yu(a,i)}const xi=BigInt(0),Vr=BigInt(1);function da(t,e){const n=e.negate();return t?n:e}function tl(t,e){const n=Ug(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Mg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function nl(t,e){Mg(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=ms(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function jg(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=Vr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function DS(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function $S(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const rl=new WeakMap,zg=new WeakMap;function il(t){return zg.get(t)||1}function Hg(t){if(t!==xi)throw new Error("invalid wNAF")}class PS{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>xi;)n&Vr&&(r=r.add(i)),i=i.double(),n>>=Vr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=nl(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;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,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=nl(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=jg(r,a,o);r=c,l?s=s.add(da(d,n[h])):i=i.add(da(f,n[u]))}return Hg(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=nl(e,this.bits);for(let o=0;o<s.windows&&r!==xi;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=jg(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return Hg(r),i}getPrecomputes(e,n,r){let i=rl.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),rl.set(n,i))),i}cached(e,n,r){const i=il(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=il(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Mg(n,this.bits),zg.set(e,n),rl.delete(e)}hasCache(e){return il(e)!==1}}function TS(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>xi||r>xi;)n&Vr&&(s=s.add(i)),r&Vr&&(o=o.add(i)),i=i.double(),n>>=Vr,r>>=Vr;return{p1:s,p2:o}}function RS(t,e,n,r){DS(n,t),$S(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Ag(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=ms(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let b=0;b<s;b++){const v=r[b],B=Number(v>>BigInt(h)&u);l[B]=l[B].add(n[b])}let p=o;for(let b=l.length-1,v=o;b>0;b--)v=v.add(l[b]),p=p.add(v);if(d=d.add(p),h!==0)for(let b=0;b<c;b++)d=d.double()}return d}function Vg(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return AS(e),e}else return yr(t,{isLE:n})}function NS(t,e,n={},r){if(r===void 0&&(r=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>xi))throw new Error(`CURVE.${a} must be positive bigint`)}const i=Vg(e.p,n.Fp,r),s=Vg(e.n,n.Fn,r),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),G0("HashToScalar-");const vs=BigInt(0),_i=BigInt(1),pa=BigInt(2);function CS(t){return ha(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function US(t){const e=CS(t),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||Mr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?pa**BigInt(254):pa**BigInt(447),p=a?BigInt(8)*pa**BigInt(251)-_i:BigInt(4)*pa**BigInt(445)-_i,b=h+p+_i,v=E=>Ot(E,n),B=D(f);function D(E){return Xu(v(E),l)}function _(E){const y=tt("u coordinate",E,l);return a&&(y[31]&=127),v(fa(y))}function x(E){return fa(i(tt("scalar",E,l)))}function P(E,y){const m=F(_(y),x(E));if(m===vs)throw new Error("invalid private or public key received");return D(m)}function R(E){return P(E,B)}function N(E,y,m){const g=v(E*(y-m));return y=v(y-g),m=v(m+g),{x_2:y,x_3:m}}function F(E,y){Qu("u",E,vs,n),Qu("scalar",y,h,b);const m=y,g=E;let w=_i,S=vs,A=E,I=_i,O=vs;for(let L=BigInt(u-1);L>=vs;L--){const U=m>>L&_i;O^=U,{x_2:w,x_3:A}=N(O,w,A),{x_2:S,x_3:I}=N(O,S,I),O=U;const k=w+S,C=v(k*k),q=w-S,j=v(q*q),W=C-j,V=A+I,Z=A-I,Q=v(Z*k),ee=v(V*q),ie=Q+ee,he=Q-ee;A=v(ie*ie),I=v(g*v(he*he)),w=v(C*j),S=v(W*(C+v(d*W)))}({x_2:w,x_3:A}=N(O,w,A)),{x_2:S,x_3:I}=N(O,S,I);const T=s(S);return v(w*T)}const $={secretKey:l,publicKey:l,seed:l},z=(E=c(l))=>(Gt(E,$.seed),E);function M(E){const y=z(E);return{secretKey:y,publicKey:R(y)}}return{keygen:M,getSharedSecret:(E,y)=>P(E,y),getPublicKey:E=>R(E),scalarMult:P,scalarMultBase:R,utils:{randomSecretKey:z,randomPrivateKey:z},GuBytes:B.slice(),lengths:$}}const FS=BigInt(1),Kg=BigInt(2),LS=BigInt(3),kS=BigInt(5),qS=BigInt(8),Gg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),MS={p:Gg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:qS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function jS(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Gg,o=t*t%s*t%s,a=Zt(o,Kg,s)*o%s,c=Zt(a,FS,s)*t%s,u=Zt(c,kS,s)*c%s,l=Zt(u,e,s)*u%s,f=Zt(l,n,s)*l%s,d=Zt(f,r,s)*f%s,h=Zt(d,i,s)*d%s,p=Zt(h,i,s)*d%s,b=Zt(p,e,s)*u%s;return{pow_p_5_8:Zt(b,Kg,s)*t%s,b2:o}}function zS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const HS=yr(MS.p,{isLE:!0}),sl=(()=>{const t=HS.ORDER;return US({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=jS(e);return Ot(Zt(n,LS,t)*r,t)},adjustScalarBytes:zS})})(),Wg=(t,e)=>(t+(t>=0?e:-e)/Zg)/e;function VS(t,e,n){const[[r,i],[s,o]]=e,a=Wg(o*t,n),c=Wg(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<Pn,d=l<Pn;f&&(u=-u),d&&(l=-l);const h=ms(Math.ceil(Ag(n)/2))+Si;if(u<Pn||u>=h||l<Pn||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function ol(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function al(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return ca(n.lowS,"lowS"),ca(n.prehash,"prehash"),n.format!==void 0&&ol(n.format),n}class KS extends Error{constructor(e=""){super(e)}}const $n={Err:KS,_tlv:{encode:(t,e)=>{const{Err:n}=$n;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=ua(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?ua(i.length/2|128):"";return ua(t)+s+i+e},decode(t,e){const{Err:n}=$n;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=$n;if(t<Pn)throw new e("integer: negative integers are not allowed");let n=ua(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=$n;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 la(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=$n,i=tt("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=$n,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Pn=BigInt(0),Si=BigInt(1),Zg=BigInt(2),ga=BigInt(3),GS=BigInt(4);function Ii(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=tt("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function WS(t,e={}){const n=NS("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;ha(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=Xg(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,y,m){const{x:g,y:w}=y.toAffine(),S=r.toBytes(g);if(ca(m,"isCompressed"),m){l();const A=!r.isOdd(w);return cr(Yg(A),S)}else return cr(Uint8Array.of(4),S,r.toBytes(w))}function d(E){zr(E,void 0,"Point");const{publicKey:y,publicKeyUncompressed:m}=u,g=E.length,w=E[0],S=E.subarray(1);if(g===y&&(w===2||w===3)){const A=r.fromBytes(S);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const I=b(A);let O;try{O=r.sqrt(I)}catch(L){const U=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+U)}l();const T=r.isOdd(O);return(w&1)===1!==T&&(O=r.neg(O)),{x:A,y:O}}else if(g===m&&w===4){const A=r.BYTES,I=r.fromBytes(S.subarray(0,A)),O=r.fromBytes(S.subarray(A,A*2));if(!v(I,O))throw new Error("bad point: is not on curve");return{x:I,y:O}}else throw new Error(`bad point: got length ${g}, expected compressed=${y} or uncompressed=${m}`)}const h=e.toBytes||f,p=e.fromBytes||d;function b(E){const y=r.sqr(E),m=r.mul(y,E);return r.add(r.add(m,r.mul(E,s.a)),s.b)}function v(E,y){const m=r.sqr(y),g=b(E);return r.eql(m,g)}if(!v(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,ga),GS),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,D)))throw new Error("bad curve params: a or b");function _(E,y,m=!1){if(!r.isValid(y)||m&&r.is0(y))throw new Error(`bad point coordinate ${E}`);return y}function x(E){if(!(E instanceof $))throw new Error("ProjectivePoint expected")}function P(E){if(!c||!c.basises)throw new Error("no endo");return VS(E,c.basises,i.ORDER)}const R=Bg((E,y)=>{const{X:m,Y:g,Z:w}=E;if(r.eql(w,r.ONE))return{x:m,y:g};const S=E.is0();y==null&&(y=S?r.ONE:r.inv(w));const A=r.mul(m,y),I=r.mul(g,y),O=r.mul(w,y);if(S)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:A,y:I}}),N=Bg(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:y,y:m}=E.toAffine();if(!r.isValid(y)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!v(y,m))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function F(E,y,m,g,w){return m=new $(r.mul(m.X,E),m.Y,m.Z),y=da(g,y),m=da(w,m),y.add(m)}class ${constructor(y,m,g){this.X=_("x",y),this.Y=_("y",m,!0),this.Z=_("z",g),Object.freeze(this)}static CURVE(){return s}static fromAffine(y){const{x:m,y:g}=y||{};if(!y||!r.isValid(m)||!r.isValid(g))throw new Error("invalid affine point");if(y instanceof $)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(g)?$.ZERO:new $(m,g,r.ONE)}static fromBytes(y){const m=$.fromAffine(p(zr(y,void 0,"point")));return m.assertValidity(),m}static fromHex(y){return $.fromBytes(tt("pointHex",y))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(y=8,m=!0){return M.createCache(this,y),m||this.multiply(ga),this}assertValidity(){N(this)}hasEvenY(){const{y}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(y)}equals(y){x(y);const{X:m,Y:g,Z:w}=this,{X:S,Y:A,Z:I}=y,O=r.eql(r.mul(m,I),r.mul(S,w)),T=r.eql(r.mul(g,I),r.mul(A,w));return O&&T}negate(){return new $(this.X,r.neg(this.Y),this.Z)}double(){const{a:y,b:m}=s,g=r.mul(m,ga),{X:w,Y:S,Z:A}=this;let I=r.ZERO,O=r.ZERO,T=r.ZERO,L=r.mul(w,w),U=r.mul(S,S),k=r.mul(A,A),C=r.mul(w,S);return C=r.add(C,C),T=r.mul(w,A),T=r.add(T,T),I=r.mul(y,T),O=r.mul(g,k),O=r.add(I,O),I=r.sub(U,O),O=r.add(U,O),O=r.mul(I,O),I=r.mul(C,I),T=r.mul(g,T),k=r.mul(y,k),C=r.sub(L,k),C=r.mul(y,C),C=r.add(C,T),T=r.add(L,L),L=r.add(T,L),L=r.add(L,k),L=r.mul(L,C),O=r.add(O,L),k=r.mul(S,A),k=r.add(k,k),L=r.mul(k,C),I=r.sub(I,L),T=r.mul(k,U),T=r.add(T,T),T=r.add(T,T),new $(I,O,T)}add(y){x(y);const{X:m,Y:g,Z:w}=this,{X:S,Y:A,Z:I}=y;let O=r.ZERO,T=r.ZERO,L=r.ZERO;const U=s.a,k=r.mul(s.b,ga);let C=r.mul(m,S),q=r.mul(g,A),j=r.mul(w,I),W=r.add(m,g),V=r.add(S,A);W=r.mul(W,V),V=r.add(C,q),W=r.sub(W,V),V=r.add(m,w);let Z=r.add(S,I);return V=r.mul(V,Z),Z=r.add(C,j),V=r.sub(V,Z),Z=r.add(g,w),O=r.add(A,I),Z=r.mul(Z,O),O=r.add(q,j),Z=r.sub(Z,O),L=r.mul(U,V),O=r.mul(k,j),L=r.add(O,L),O=r.sub(q,L),L=r.add(q,L),T=r.mul(O,L),q=r.add(C,C),q=r.add(q,C),j=r.mul(U,j),V=r.mul(k,V),q=r.add(q,j),j=r.sub(C,j),j=r.mul(U,j),V=r.add(V,j),C=r.mul(q,V),T=r.add(T,C),C=r.mul(Z,V),O=r.mul(W,O),O=r.sub(O,C),C=r.mul(W,q),L=r.mul(Z,L),L=r.add(L,C),new $(O,T,L)}subtract(y){return this.add(y.negate())}is0(){return this.equals($.ZERO)}multiply(y){const{endo:m}=e;if(!i.isValidNot0(y))throw new Error("invalid scalar: out of range");let g,w;const S=A=>M.cached(this,A,I=>tl($,I));if(m){const{k1neg:A,k1:I,k2neg:O,k2:T}=P(y),{p:L,f:U}=S(I),{p:k,f:C}=S(T);w=U.add(C),g=F(m.beta,L,k,A,O)}else{const{p:A,f:I}=S(y);g=A,w=I}return tl($,[g,w])[0]}multiplyUnsafe(y){const{endo:m}=e,g=this;if(!i.isValid(y))throw new Error("invalid scalar: out of range");if(y===Pn||g.is0())return $.ZERO;if(y===Si)return g;if(M.hasCache(this))return this.multiply(y);if(m){const{k1neg:w,k1:S,k2neg:A,k2:I}=P(y),{p1:O,p2:T}=TS($,g,S,I);return F(m.beta,O,T,w,A)}else return M.unsafe(g,y)}multiplyAndAddUnsafe(y,m,g){const w=this.multiplyUnsafe(m).add(y.multiplyUnsafe(g));return w.is0()?void 0:w}toAffine(y){return R(this,y)}isTorsionFree(){const{isTorsionFree:y}=e;return o===Si?!0:y?y($,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:y}=e;return o===Si?this:y?y($,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(y=!0){return ca(y,"isCompressed"),this.assertValidity(),h($,this,y)}toHex(y=!0){return vi(this.toBytes(y))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(y=!0){return this.toBytes(y)}_setWindowSize(y){this.precompute(y)}static normalizeZ(y){return tl($,y)}static msm(y,m){return RS($,i,y,m)}static fromPrivateKey(y){return $.BASE.multiply(Ii(i,y))}}$.BASE=new $(s.Gx,s.Gy,r.ONE),$.ZERO=new $(r.ZERO,r.ONE,r.ZERO),$.Fp=r,$.Fn=i;const z=i.BITS,M=new PS($,e.endo?Math.ceil(z/2):z);return $.BASE.precompute(8),$}function Yg(t){return Uint8Array.of(t?2:3)}function Xg(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function ZS(t,e={}){const{Fn:n}=t,r=e.randomBytes||Mr,i=Object.assign(Xg(t.Fp,n),{seed:qg(n.ORDER)});function s(d){try{return!!Ii(n,d)}catch{return!1}}function o(d,h){const{publicKey:p,publicKeyUncompressed:b}=i;try{const v=d.length;return h===!0&&v!==p||h===!1&&v!==b?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=r(i.seed)){return OS(zr(d,i.seed,"seed"),n.ORDER)}function c(d,h=!0){return t.BASE.multiply(Ii(n,d)).toBytes(h)}function u(d){const h=a(d);return{secretKey:h,publicKey:c(h)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:h,publicKey:p,publicKeyUncompressed:b}=i;if(n.allowedLengths||h===p)return;const v=tt("key",d).length;return v===p||v===b}function f(d,h,p=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");const b=Ii(n,d);return t.fromHex(h).multiply(b).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:d=>Ii(n,d),precompute(d=8,h=t.BASE){return h.precompute(d,!1)}},lengths:i})}function YS(t,e,n={}){Jo(e),ha(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Mr,i=n.hmac||((m,...g)=>oa(e,m,cr(...g))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=ZS(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},b="compact";function v(m){const g=a>>Si;return m>g}function B(m,g){if(!o.isValidNot0(g))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return g}function D(m,g){ol(g);const w=h.signature,S=g==="compact"?w:g==="recovered"?w+1:void 0;return zr(m,S,`${g} signature`)}class _{constructor(g,w,S){this.r=B("r",g),this.s=B("s",w),S!=null&&(this.recovery=S),Object.freeze(this)}static fromBytes(g,w=b){D(g,w);let S;if(w==="der"){const{r:T,s:L}=$n.toSig(zr(g));return new _(T,L)}w==="recovered"&&(S=g[0],w="compact",g=g.subarray(1));const A=o.BYTES,I=g.subarray(0,A),O=g.subarray(A,A*2);return new _(o.fromBytes(I),o.fromBytes(O),S)}static fromHex(g,w){return this.fromBytes(Qo(g),w)}addRecoveryBit(g){return new _(this.r,this.s,g)}recoverPublicKey(g){const w=s.ORDER,{r:S,s:A,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*Zg<w&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const O=I===2||I===3?S+a:S;if(!s.isValid(O))throw new Error("recovery id 2 or 3 invalid");const T=s.toBytes(O),L=t.fromBytes(cr(Yg((I&1)===0),T)),U=o.inv(O),k=P(tt("msgHash",g)),C=o.create(-k*U),q=o.create(A*U),j=t.BASE.multiplyUnsafe(C).add(L.multiplyUnsafe(q));if(j.is0())throw new Error("point at infinify");return j.assertValidity(),j}hasHighS(){return v(this.s)}toBytes(g=b){if(ol(g),g==="der")return Qo($n.hexFromSig(this));const w=o.toBytes(this.r),S=o.toBytes(this.s);if(g==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return cr(Uint8Array.of(this.recovery),w,S)}return cr(w,S)}toHex(g){return vi(this.toBytes(g))}assertValidity(){}static fromCompact(g){return _.fromBytes(tt("sig",g),"compact")}static fromDER(g){return _.fromBytes(tt("sig",g),"der")}normalizeS(){return this.hasHighS()?new _(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return vi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return vi(this.toBytes("compact"))}}const x=n.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const g=la(m),w=m.length*8-c;return w>0?g>>BigInt(w):g},P=n.bits2int_modN||function(m){return o.create(x(m))},R=ms(c);function N(m){return Qu("num < 2^"+c,m,Pn,R),o.toBytes(m)}function F(m,g){return zr(m,void 0,"message"),g?zr(e(m),void 0,"prehashed message"):m}function $(m,g,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:S,prehash:A,extraEntropy:I}=al(w,p);m=F(m,A);const O=P(m),T=Ii(o,g),L=[N(T),N(O)];if(I!=null&&I!==!1){const q=I===!0?r(h.secretKey):I;L.push(tt("extraEntropy",q))}const U=cr(...L),k=O;function C(q){const j=x(q);if(!o.isValidNot0(j))return;const W=o.inv(j),V=t.BASE.multiply(j).toAffine(),Z=o.create(V.x);if(Z===Pn)return;const Q=o.create(W*o.create(k+Z*T));if(Q===Pn)return;let ee=(V.x===Z?0:2)|Number(V.y&Si),ie=Q;return S&&v(Q)&&(ie=o.neg(Q),ee^=1),new _(Z,ie,ee)}return{seed:U,k2sig:C}}function z(m,g,w={}){m=tt("message",m);const{seed:S,k2sig:A}=$(m,g,w);return mS(e.outputLen,o.BYTES,i)(S,A)}function M(m){let g;const w=typeof m=="string"||Xo(m),S=!w&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!w&&!S)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(S)g=new _(m.r,m.s);else if(w){try{g=_.fromBytes(tt("sig",m),"der")}catch(A){if(!(A instanceof $n.Err))throw A}if(!g)try{g=_.fromBytes(tt("sig",m),"compact")}catch{return!1}}return g||!1}function E(m,g,w,S={}){const{lowS:A,prehash:I,format:O}=al(S,p);if(w=tt("publicKey",w),g=F(tt("message",g),I),"strict"in S)throw new Error("options.strict was renamed to lowS");const T=O===void 0?M(m):_.fromBytes(tt("sig",m),O);if(T===!1)return!1;try{const L=t.fromBytes(w);if(A&&T.hasHighS())return!1;const{r:U,s:k}=T,C=P(g),q=o.inv(k),j=o.create(C*q),W=o.create(U*q),V=t.BASE.multiplyUnsafe(j).add(L.multiplyUnsafe(W));return V.is0()?!1:o.create(V.x)===U}catch{return!1}}function y(m,g,w={}){const{prehash:S}=al(w,p);return g=F(g,S),_.fromBytes(m,"recovered").recoverPublicKey(g).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:z,verify:E,recoverPublicKey:y,Signature:_,hash:e})}function XS(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},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=yr(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,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 JS(t){const{CURVE:e,curveOpts:n}=XS(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function QS(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Lg(n.Fn.ORDER,n.Fn.BITS))})}function eI(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=JS(t),s=WS(e,n),o=YS(s,r,i);return QS(t,o)}function cl(t,e){const n=r=>eI({...t,hash:r});return{...n(e),create:n}}const Jg={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Qg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},e1={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},tI=yr(Jg.p),nI=yr(Qg.p),rI=yr(e1.p),iI=cl({...Jg,Fp:tI,lowS:!1},ta);cl({...Qg,Fp:nI,lowS:!1},c_),cl({...e1,Fp:rI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},a_);const sI=iI,t1="base10",lt="base16",Et="base64pad",br="base64url",Es="utf8",n1=0,Tn=1,xs=2,oI=0,r1=1,_s=12,ul=32;function aI(){const t=sl.utils.randomPrivateKey(),e=sl.getPublicKey(t);return{privateKey:wt(t,lt),publicKey:wt(e,lt)}}function ll(){const t=Mr(ul);return wt(t,lt)}function cI(t,e){const n=sl.getSharedSecret(Ct(t,lt),Ct(e,lt)),r=bS(aa,n,void 0,void 0,ul);return wt(r,lt)}function ya(t){const e=aa(Ct(t,lt));return wt(e,lt)}function Ft(t){const e=aa(Ct(t,Es));return wt(e,lt)}function i1(t){return Ct(`${t}`,t1)}function Kr(t){return Number(wt(t,t1))}function s1(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function o1(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function uI(t){const e=i1(typeof t.type<"u"?t.type:n1);if(Kr(e)===Tn&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?Ct(t.senderPublicKey,lt):void 0,r=typeof t.iv<"u"?Ct(t.iv,lt):Mr(_s),i=Ct(t.symKey,lt),s=xg(i,r).encrypt(Ct(t.message,Es)),o=a1({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===br?s1(o):o}function lI(t){const e=Ct(t.symKey,lt),{sealed:n,iv:r}=Ss({encoded:t.encoded,encoding:t.encoding}),i=xg(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return wt(i,Es)}function fI(t,e){const n=i1(xs),r=Mr(_s),i=Ct(t,Es),s=a1({type:n,sealed:i,iv:r});return e===br?s1(s):s}function hI(t,e){const{sealed:n}=Ss({encoded:t,encoding:e});return wt(n,Es)}function a1(t){if(Kr(t.type)===xs)return wt(as([t.type,t.sealed]),Et);if(Kr(t.type)===Tn){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return wt(as([t.type,t.senderPublicKey,t.iv,t.sealed]),Et)}return wt(as([t.type,t.iv,t.sealed]),Et)}function Ss(t){const e=(t.encoding||Et)===br?o1(t.encoded):t.encoded,n=Ct(e,Et),r=n.slice(oI,r1),i=r1;if(Kr(r)===Tn){const c=i+ul,u=c+_s,l=n.slice(i,c),f=n.slice(c,u),d=n.slice(u);return{type:r,sealed:d,iv:f,senderPublicKey:l}}if(Kr(r)===xs){const c=n.slice(i),u=Mr(_s);return{type:r,sealed:c,iv:u}}const s=i+_s,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function dI(t,e){const n=Ss({encoded:t,encoding:e?.encoding});return c1({type:Kr(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?wt(n.senderPublicKey,lt):void 0,receiverPublicKey:e?.receiverPublicKey})}function c1(t){const e=t?.type||n1;if(e===Tn){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 u1(t){return t.type===Tn&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function l1(t){return t.type===xs}function pI(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return as([new Uint8Array([4]),e,n])}function gI(t,e){const[n,r,i]=t.split("."),s=Buffer.from(o1(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,u=aa(c),l=pI(e);if(!sI.verify(as([o,a]),u,l))throw new Error("Invalid signature");return lc(t).payload}const yI="irn";function ba(t){return t?.relay||{protocol:yI}}function Ai(t){const e=z4[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var bI=Object.defineProperty,wI=Object.defineProperties,mI=Object.getOwnPropertyDescriptors,f1=Object.getOwnPropertySymbols,vI=Object.prototype.hasOwnProperty,EI=Object.prototype.propertyIsEnumerable,h1=(t,e,n)=>e in t?bI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fl=(t,e)=>{for(var n in e||(e={}))vI.call(e,n)&&h1(t,n,e[n]);if(f1)for(var n of f1(e))EI.call(e,n)&&h1(t,n,e[n]);return t},xI=(t,e)=>wI(t,mI(e));function _I(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=t[i];n[s]=o}}),n}function d1(t){if(!t.includes("wc:")){const u=F0(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(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,n).split("@"),s=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:SI(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:_I(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function SI(t){return t.startsWith("//")?t.substring(2):t}function II(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(i=>{const s=i,o=n+e+s;t[s]&&(r[o]=t[s])}),r}function p1(t){const e=new URLSearchParams,n=fl(fl(xI(fl({},II(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(n).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!==void 0&&e.append(r,String(i))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function wa(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var AI=Object.defineProperty,BI=Object.defineProperties,OI=Object.getOwnPropertyDescriptors,g1=Object.getOwnPropertySymbols,DI=Object.prototype.hasOwnProperty,$I=Object.prototype.propertyIsEnumerable,y1=(t,e,n)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,PI=(t,e)=>{for(var n in e||(e={}))DI.call(e,n)&&y1(t,n,e[n]);if(g1)for(var n of g1(e))$I.call(e,n)&&y1(t,n,e[n]);return t},TI=(t,e)=>BI(t,OI(e));function Bi(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function RI(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Bi(n.accounts))}),e}function NI(t,e){const n=[];return Object.values(t).forEach(r=>{Bi(r.accounts).includes(e)&&n.push(...r.methods)}),n}function CI(t,e){const n=[];return Object.values(t).forEach(r=>{Bi(r.accounts).includes(e)&&n.push(...r.events)}),n}function b1(t){return t.includes(":")}function UI(t){return b1(t)?t.split(":")[0]:t}function w1(t){var e,n,r;const i={};if(!Is(t))return i;for(const[s,o]of Object.entries(t)){const a=b1(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=UI(s);i[l]=TI(PI({},i[l]),{chains:qr(a,(e=i[l])==null?void 0:e.chains),methods:qr(c,(n=i[l])==null?void 0:n.methods),events:qr(u,(r=i[l])==null?void 0:r.events)})}return i}function FI(t){const e={};return t?.forEach(n=>{var r;const[i,s]=n.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(n),(r=e[i].chains)==null||r.push(`${i}:${s}`)}),e}function m1(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=FI(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=qr(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function LI(t,e){var n,r,i,s,o,a;const c=w1(t),u=w1(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const d of f)l[d]={chains:qr((n=c[d])==null?void 0:n.chains,(r=u[d])==null?void 0:r.chains),methods:qr((i=c[d])==null?void 0:i.methods,(s=u[d])==null?void 0:s.methods),events:qr((o=c[d])==null?void 0:o.events,(a=u[d])==null?void 0:a.events)};return l}const kI={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}},qI={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 G(t,e){const{message:n,code:r}=qI[t];return{message:e?`${n} ${e}`:n,code:r}}function Ee(t,e){const{message:n,code:r}=kI[t];return{message:e?`${n} ${e}`:n,code:r}}function Oi(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Is(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Pe(t){return typeof t>"u"}function Ie(t,e){return e&&Pe(t)?!0:typeof t=="string"&&!!t.trim().length}function hl(t,e){return e&&Pe(t)?!0:typeof t=="number"&&!isNaN(t)}function MI(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return Lr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Bi(a),f=n[o];(!Lr(A0(o,f),l)||!Lr(f.methods,c)||!Lr(f.events,u))&&(s=!1)}),s):!1}function ma(t){return Ie(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function jI(t){if(Ie(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&ma(n)}}return!1}function zI(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(Ie(t,!1)){if(e(t))return!0;const n=F0(t);return e(n)}}catch{}return!1}function HI(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function VI(t){return t?.topic}function KI(t,e){let n=null;return Ie(t?.publicKey,!1)||(n=G("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function v1(t){let e=!0;return Oi(t)?t.length&&(e=t.every(n=>Ie(n,!1))):e=!1,e}function GI(t,e,n){let r=null;return Oi(e)&&e.length?e.forEach(i=>{r||ma(i)||(r=Ee("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):ma(t)||(r=Ee("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function WI(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=GI(i,A0(i,s),`${e} ${n}`);o&&(r=o)}),r}function ZI(t,e){let n=null;return Oi(t)?t.forEach(r=>{n||jI(r)||(n=Ee("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=Ee("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function YI(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=ZI(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function XI(t,e){let n=null;return v1(t?.methods)?v1(t?.events)||(n=Ee("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=Ee("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function E1(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=XI(r,`${e}, namespace`);i&&(n=i)}),n}function JI(t,e,n){let r=null;if(t&&Is(t)){const i=E1(t,e);i&&(r=i);const s=WI(t,e,n);s&&(r=s)}else r=G("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function dl(t,e){let n=null;if(t&&Is(t)){const r=E1(t,e);r&&(n=r);const i=YI(t,e);i&&(n=i)}else n=G("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function x1(t){return Ie(t.protocol,!0)}function QI(t,e){let n=!1;return e&&!t?n=!0:t&&Oi(t)&&t.length&&t.forEach(r=>{n=x1(r)}),n}function e9(t){return typeof t=="number"}function xt(t){return typeof t<"u"&&typeof t!==null}function t9(t){return!(!t||typeof t!="object"||!t.code||!hl(t.code,!1)||!t.message||!Ie(t.message,!1))}function n9(t){return!(Pe(t)||!Ie(t.method,!1))}function r9(t){return!(Pe(t)||Pe(t.result)&&Pe(t.error)||!hl(t.id,!1)||!Ie(t.jsonrpc,!1))}function i9(t){return!(Pe(t)||!Ie(t.name,!1))}function _1(t,e){return!(!ma(e)||!RI(t).includes(e))}function s9(t,e,n){return Ie(n,!1)?NI(t,e).includes(n):!1}function o9(t,e,n){return Ie(n,!1)?CI(t,e).includes(n):!1}function S1(t,e,n){let r=null;const i=a9(t),s=c9(e),o=Object.keys(i),a=Object.keys(s),c=I1(Object.keys(t)),u=I1(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
23
22
  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.
23
+ Received: ${Object.keys(e).toString()}`)),Lr(o,a)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
25
24
  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={};/*! *****************************************************************************
25
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||r)return;const d=Bi(e[f].accounts);d.includes(f)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${f}
26
+ Required: ${f}
27
+ Approved: ${d.toString()}`))}),o.forEach(f=>{r||(Lr(i[f].methods,s[f].methods)?Lr(i[f].events,s[f].events)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${f}`)):r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${f}`))}),r}function a9(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(i=>{e[i]={methods:t[n].methods,events:t[n].events}})}),e}function I1(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function c9(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:Bi(t[n].accounts)?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}),e}function u9(t,e){return hl(t,!1)&&t<=e.max&&t>=e.min}function A1(){const t=hs();return new Promise(e=>{switch(t){case Bt.browser:e(l9());break;case Bt.reactNative:e(f9());break;case Bt.node:e(h9());break;default:e(!0)}})}function l9(){return wi()&&navigator?.onLine}async function f9(){return nr()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function h9(){return!0}function d9(t){switch(hs()){case Bt.browser:p9(t);break;case Bt.reactNative:g9(t);break}}function p9(t){!nr()&&wi()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function g9(t){nr()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function y9(){var t;return wi()&&Or()?((t=Or())==null?void 0:t.visibilityState)==="visible":!0}const pl={};class As{static get(e){return pl[e]}static set(e,n){pl[e]=n}static delete(e){delete pl[e]}}function b9(t){const e=rs.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function w9({publicKey:t,signature:e,payload:n}){var r;const i=gl(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=E9(n.address),a=n.era==="00"?new Uint8Array([0]):gl(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${v9(n.tip)}`),f=_9(l),d=new Uint8Array([0,...t,o,...e,...a,...u,...f,...i]),h=x9(d.length+1);return new Uint8Array([...h,s,...d])}function m9(t){const e=gl(t),n=t5.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function gl(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function v9(t){return t.startsWith("0x")?t.slice(2):t}function E9(t){const e=rs.decode(t)[0];return e===42?0:e===60?2:1}function x9(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 _9(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 S9(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=b9(t.transaction.address),r=w9({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return m9(i)}const I9="PARSE_ERROR",A9="INVALID_REQUEST",B9="METHOD_NOT_FOUND",O9="INVALID_PARAMS",B1="INTERNAL_ERROR",yl="SERVER_ERROR",D9=[-32700,-32600,-32601,-32602,-32603],Bs={[I9]:{code:-32700,message:"Parse error"},[A9]:{code:-32600,message:"Invalid Request"},[B9]:{code:-32601,message:"Method not found"},[O9]:{code:-32602,message:"Invalid params"},[B1]:{code:-32603,message:"Internal error"},[yl]:{code:-32e3,message:"Server error"}},O1=yl;function $9(t){return D9.includes(t)}function D1(t){return Object.keys(Bs).includes(t)?Bs[t]:Bs[O1]}function P9(t){const e=Object.values(Bs).find(n=>n.code===t);return e||Bs[O1]}function T9(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var $1={};/*! *****************************************************************************
29
28
  Copyright (c) Microsoft Corporation.
30
29
 
31
30
  Permission to use, copy, modify, and/or distribute this software for any
@@ -38,5 +37,5 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Zx(r)).toStr
38
37
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
38
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
39
  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})});
40
+ ***************************************************************************** */var bl=function(t,e){return bl=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},bl(t,e)};function R9(t,e){bl(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var wl=function(){return wl=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},wl.apply(this,arguments)};function N9(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function C9(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function U9(t,e){return function(n,r){e(n,r,t)}}function F9(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function L9(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function k9(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,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(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=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 n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function q9(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function M9(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function ml(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function P1(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function j9(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(P1(arguments[e]));return t}function z9(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Os(t){return this instanceof Os?(this.v=t,this):new Os(t)}function H9(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(d){r[d]&&(i[d]=function(h){return new Promise(function(p,b){s.push([d,h,p,b])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Os?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function V9(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Os(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function K9(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof ml=="function"?ml(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[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 G9(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function W9(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function Z9(t){return t&&t.__esModule?t:{default:t}}function Y9(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function X9(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var J9=Object.freeze({__proto__:null,__extends:R9,get __assign(){return wl},__rest:N9,__decorate:C9,__param:U9,__metadata:F9,__awaiter:L9,__generator:k9,__createBinding:q9,__exportStar:M9,__values:ml,__read:P1,__spread:j9,__spreadArrays:z9,__await:Os,__asyncGenerator:H9,__asyncDelegator:V9,__asyncValues:K9,__makeTemplateObject:G9,__importStar:W9,__importDefault:Z9,__classPrivateFieldGet:Y9,__classPrivateFieldSet:X9}),Q9=Vl(J9),Rn={},T1;function e7(){if(T1)return Rn;T1=1,Object.defineProperty(Rn,"__esModule",{value:!0}),Rn.isBrowserCryptoAvailable=Rn.getSubtleCrypto=Rn.getBrowerCrypto=void 0;function t(){return Xt?.crypto||Xt?.msCrypto||{}}Rn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Rn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Rn.isBrowserCryptoAvailable=n,Rn}var Nn={},R1;function t7(){if(R1)return Nn;R1=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.isBrowser=Nn.isNode=Nn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Nn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}Nn.isNode=e;function n(){return!t()&&!e()}return Nn.isBrowser=n,Nn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Q9;e.__exportStar(e7(),t),e.__exportStar(t7(),t)})($1);function on(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function wr(t=6){return BigInt(on(t))}function Cn(t,e,n){return{id:n||on(),jsonrpc:"2.0",method:t,params:e}}function va(t,e){return{id:t,jsonrpc:"2.0",result:e}}function vl(t,e,n){return{id:t,jsonrpc:"2.0",error:n7(e,n)}}function n7(t,e){return typeof t>"u"?D1(B1):(typeof t=="string"&&(t=Object.assign(Object.assign({},D1(yl)),{message:t})),typeof e<"u"&&(t.data=e),$9(t.code)&&(t=P9(t.code)),t)}class r7{}class i7 extends r7{constructor(){super()}}class s7 extends i7{constructor(e){super()}}const o7="^wss?:";function a7(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function c7(t,e){const n=a7(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function N1(t){return c7(t,o7)}function u7(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function C1(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function El(t){return C1(t)&&"method"in t}function Ea(t){return C1(t)&&(an(t)||Lt(t))}function an(t){return"result"in t}function Lt(t){return"error"in t}class l7 extends s7{constructor(e){super(e),this.events=new Ke.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,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(Cn(e.method,e.params||[],e.id||wr().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Lt(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ea(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 f7=()=>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"),h7=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",U1=t=>t.split("?")[0],F1=10,d7=f7();class p7{constructor(e){if(this.url=e,this.events=new Ke.exports.EventEmitter,this.registering=!1,!N1(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,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ir(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!N1(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,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"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=$1.isReactNative()?void 0:{rejectUnauthorized:!u7(e)},s=new d7(e,[],i);h7()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),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 n=typeof e.data=="string"?Jr(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=vl(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return T9(e,U1(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>F1&&this.events.setMaxListeners(F1)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${U1(this.url)}`));return this.events.emit("register_error",n),n}}const L1="wc",k1=2,xa="core",cn=`${L1}@2:${xa}:`,g7={name:xa,logger:"error"},y7={database:":memory:"},b7="crypto",q1="client_ed25519_seed",w7=K.ONE_DAY,m7="keychain",v7="0.3",E7="messages",x7="0.3",_7=K.SIX_HOURS,S7="publisher",M1="irn",I7="error",j1="wss://relay.walletconnect.org",A7="relayer",Se={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"},B7="_subscription",kt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},O7=.1,xl="2.21.10",me={link_mode:"link_mode",relay:"relay"},_a={inbound:"inbound",outbound:"outbound"},D7="0.3",$7="WALLETCONNECT_CLIENT_ID",z1="WALLETCONNECT_LINK_MODE_APPS",Dt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},P7="subscription",T7="0.3",R7="pairing",N7="0.3",Ds={wc_pairingDelete:{req:{ttl:K.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:K.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:K.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:K.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:K.ONE_DAY,prompt:!1,tag:0},res:{ttl:K.ONE_DAY,prompt:!1,tag:0}}},Gr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Yt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},C7="history",U7="0.3",F7="expirer",qt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},L7="0.3",k7="verify-api",q7="https://verify.walletconnect.com",H1="https://verify.walletconnect.org",$s=H1,M7=`${$s}/v3`,j7=[q7,H1],z7="echo",H7="https://echo.walletconnect.com",un={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"},Un={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"},mr={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"},Ps={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"},Wr={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"},Ts={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"},V7=.1,K7="event-client",G7=86400,W7="https://pulse.walletconnect.org/batch";function Z7(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[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 b=0,v=0,B=0,D=p.length;B!==D&&p[B]===0;)B++,b++;for(var _=(D-B)*l+1>>>0,x=new Uint8Array(_);B!==D;){for(var P=p[B],R=0,N=_-1;(P!==0||R<v)&&N!==-1;N--,R++)P+=256*x[N]>>>0,x[N]=P%a>>>0,P=P/a>>>0;if(P!==0)throw new Error("Non-zero carry");v=R,B++}for(var F=_-v;F!==_&&x[F]===0;)F++;for(var $=c.repeat(b);F<_;++F)$+=t.charAt(x[F]);return $}function d(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var b=0;if(p[b]!==" "){for(var v=0,B=0;p[b]===c;)v++,b++;for(var D=(p.length-b)*u+1>>>0,_=new Uint8Array(D);p[b];){var x=n[p.charCodeAt(b)];if(x===255)return;for(var P=0,R=D-1;(x!==0||P<B)&&R!==-1;R--,P++)x+=a*_[R]>>>0,_[R]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");B=P,b++}if(p[b]!==" "){for(var N=D-B;N!==D&&_[N]===0;)N++;for(var F=new Uint8Array(v+(D-N)),$=v;N!==D;)F[$++]=_[N++];return F}}}function h(p){var b=d(p);if(b)return b;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var Y7=Z7,X7=Y7;const V1=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")},J7=t=>new TextEncoder().encode(t),Q7=t=>new TextDecoder().decode(t);class eA{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class tA{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return K1(this,e)}}class nA{constructor(e){this.decoders=e}or(e){return K1(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const K1=(t,e)=>new nA({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class rA{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new eA(e,n,r),this.decoder=new tA(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Sa=({name:t,prefix:e,encode:n,decode:r})=>new rA(t,e,n,r),Rs=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=X7(n,e);return Sa({prefix:t,name:e,encode:r,decode:s=>V1(i(s))})},iA=(t,e,n,r)=>{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*n/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-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},sA=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Me=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Sa({prefix:e,name:t,encode(i){return sA(i,r,n)},decode(i){return iA(i,r,n,t)}}),oA=Sa({prefix:"\0",name:"identity",encode:t=>Q7(t),decode:t=>J7(t)});var aA=Object.freeze({__proto__:null,identity:oA});const cA=Me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var uA=Object.freeze({__proto__:null,base2:cA});const lA=Me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var fA=Object.freeze({__proto__:null,base8:lA});const hA=Rs({prefix:"9",name:"base10",alphabet:"0123456789"});var dA=Object.freeze({__proto__:null,base10:hA});const pA=Me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),gA=Me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var yA=Object.freeze({__proto__:null,base16:pA,base16upper:gA});const bA=Me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),wA=Me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),mA=Me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vA=Me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),EA=Me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),xA=Me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),_A=Me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),SA=Me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),IA=Me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var AA=Object.freeze({__proto__:null,base32:bA,base32upper:wA,base32pad:mA,base32padupper:vA,base32hex:EA,base32hexupper:xA,base32hexpad:_A,base32hexpadupper:SA,base32z:IA});const BA=Rs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),OA=Rs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var DA=Object.freeze({__proto__:null,base36:BA,base36upper:OA});const $A=Rs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),PA=Rs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var TA=Object.freeze({__proto__:null,base58btc:$A,base58flickr:PA});const RA=Me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),NA=Me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),CA=Me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),UA=Me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var FA=Object.freeze({__proto__:null,base64:RA,base64pad:NA,base64url:CA,base64urlpad:UA});const G1=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}"),LA=G1.reduce((t,e,n)=>(t[n]=e,t),[]),kA=G1.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function qA(t){return t.reduce((e,n)=>(e+=LA[n],e),"")}function MA(t){const e=[];for(const n of t){const r=kA[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const jA=Sa({prefix:"\u{1F680}",name:"base256emoji",encode:qA,decode:MA});var zA=Object.freeze({__proto__:null,base256emoji:jA}),HA=Z1,W1=128,VA=127,KA=~VA,GA=Math.pow(2,31);function Z1(t,e,n){e=e||[],n=n||0;for(var r=n;t>=GA;)e[n++]=t&255|W1,t/=128;for(;t&KA;)e[n++]=t&255|W1,t>>>=7;return e[n]=t|0,Z1.bytes=n-r+1,e}var WA=_l,ZA=128,Y1=127;function _l(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw _l.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Y1)<<i:(o&Y1)*Math.pow(2,i),i+=7}while(o>=ZA);return _l.bytes=s-r,n}var YA=Math.pow(2,7),XA=Math.pow(2,14),JA=Math.pow(2,21),QA=Math.pow(2,28),eB=Math.pow(2,35),tB=Math.pow(2,42),nB=Math.pow(2,49),rB=Math.pow(2,56),iB=Math.pow(2,63),sB=function(t){return t<YA?1:t<XA?2:t<JA?3:t<QA?4:t<eB?5:t<tB?6:t<nB?7:t<rB?8:t<iB?9:10},oB={encode:HA,decode:WA,encodingLength:sB},X1=oB;const J1=(t,e,n=0)=>(X1.encode(t,e,n),e),Q1=t=>X1.encodingLength(t),Sl=(t,e)=>{const n=e.byteLength,r=Q1(t),i=r+Q1(n),s=new Uint8Array(i+n);return J1(t,s,0),J1(n,s,r),s.set(e,i),new aB(t,n,e,s)};class aB{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const ey=({name:t,code:e,encode:n})=>new cB(t,e,n);class cB{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Sl(this.code,n):n.then(r=>Sl(this.code,r))}else throw Error("Unknown type, must be binary type")}}const ty=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),uB=ey({name:"sha2-256",code:18,encode:ty("SHA-256")}),lB=ey({name:"sha2-512",code:19,encode:ty("SHA-512")});var fB=Object.freeze({__proto__:null,sha256:uB,sha512:lB});const ny=0,hB="identity",ry=V1;var dB=Object.freeze({__proto__:null,identity:{code:ny,name:hB,encode:ry,digest:t=>Sl(ny,ry(t))}});new TextEncoder,new TextDecoder;const iy={...aA,...uA,...fA,...dA,...yA,...AA,...DA,...TA,...FA,...zA};({...fB,...dB});function sy(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function pB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?sy(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function oy(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const ay=oy("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Il=oy("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=pB(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),gB={utf8:ay,"utf-8":ay,hex:iy.base16,latin1:Il,ascii:Il,binary:Il,...iy};function yB(t,e="utf8"){const n=gB[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?sy(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var bB=Object.defineProperty,wB=(t,e,n)=>e in t?bB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ln=(t,e,n)=>wB(t,typeof e!="symbol"?e+"":e,n);class mB{constructor(e,n){this.core=e,this.logger=n,ln(this,"keychain",new Map),ln(this,"name",m7),ln(this,"version",v7),ln(this,"initialized",!1),ln(this,"storagePrefix",cn),ln(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),ln(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),ln(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),ln(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=G("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),ln(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=rt(n,this.name)}get context(){return ht(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Pu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Tu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vB=Object.defineProperty,EB=(t,e,n)=>e in t?vB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,je=(t,e,n)=>EB(t,typeof e!="symbol"?e+"":e,n);class xB{constructor(e,n,r){this.core=e,this.logger=n,je(this,"name",b7),je(this,"keychain"),je(this,"randomSessionIdentifier",ll()),je(this,"initialized",!1),je(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),je(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),je(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Sh(i);return _h(s.publicKey)}),je(this,"generateKeyPair",()=>{this.isInitialized();const i=aI();return this.setPrivateKey(i.publicKey,i.privateKey)}),je(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Sh(s),a=this.randomSessionIdentifier;return await jv(a,i,w7,o)}),je(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=cI(a,s);return this.setSymKey(c,o)}),je(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ya(i);return await this.keychain.set(o,i),o}),je(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),je(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),je(this,"encode",async(i,s,o)=>{this.isInitialized();const a=c1(o),c=Ir(s);if(l1(a))return fI(c,o?.encoding);if(u1(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;i=await this.generateSharedKey(d,h)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return uI({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),je(this,"decode",async(i,s,o)=>{this.isInitialized();const a=dI(s,o);if(l1(a)){const c=hI(s,o?.encoding);return Jr(c)}if(u1(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=lI({symKey:c,encoded:s,encoding:o?.encoding});return Jr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),je(this,"getPayloadType",(i,s=Et)=>{const o=Ss({encoded:i,encoding:s});return Kr(o.type)}),je(this,"getPayloadSenderPublicKey",(i,s=Et)=>{const o=Ss({encoded:i,encoding:s});return o.senderPublicKey?wt(o.senderPublicKey,lt):void 0}),this.core=e,this.logger=rt(n,this.name),this.keychain=r||new mB(this.core,this.logger)}get context(){return ht(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(q1)}catch{e=ll(),await this.keychain.set(q1,e)}return yB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _B=Object.defineProperty,SB=Object.defineProperties,IB=Object.getOwnPropertyDescriptors,cy=Object.getOwnPropertySymbols,AB=Object.prototype.hasOwnProperty,BB=Object.prototype.propertyIsEnumerable,Al=(t,e,n)=>e in t?_B(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,OB=(t,e)=>{for(var n in e||(e={}))AB.call(e,n)&&Al(t,n,e[n]);if(cy)for(var n of cy(e))BB.call(e,n)&&Al(t,n,e[n]);return t},DB=(t,e)=>SB(t,IB(e)),$t=(t,e,n)=>Al(t,typeof e!="symbol"?e+"":e,n);class $B extends Mw{constructor(e,n){super(e,n),this.logger=e,this.core=n,$t(this,"messages",new Map),$t(this,"messagesWithoutClientAck",new Map),$t(this,"name",E7),$t(this,"version",x7),$t(this,"initialized",!1),$t(this,"storagePrefix",cn),$t(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);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(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),$t(this,"set",async(r,i,s)=>{this.isInitialized();const o=Ft(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===_a.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,DB(OB({},c),{[o]:i}))}return await this.persist(),o}),$t(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),$t(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),$t(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Ft(i);return typeof s[o]<"u"}),$t(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Ft(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),$t(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=rt(e,this.name),this.core=n}get context(){return ht(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,Pu(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Pu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Tu(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Tu(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var PB=Object.defineProperty,TB=Object.defineProperties,RB=Object.getOwnPropertyDescriptors,uy=Object.getOwnPropertySymbols,NB=Object.prototype.hasOwnProperty,CB=Object.prototype.propertyIsEnumerable,Bl=(t,e,n)=>e in t?PB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Di=(t,e)=>{for(var n in e||(e={}))NB.call(e,n)&&Bl(t,n,e[n]);if(uy)for(var n of uy(e))CB.call(e,n)&&Bl(t,n,e[n]);return t},ly=(t,e)=>TB(t,RB(e)),Mt=(t,e,n)=>Bl(t,typeof e!="symbol"?e+"":e,n);class UB extends jw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Mt(this,"events",new Ke.exports.EventEmitter),Mt(this,"name",S7),Mt(this,"queue",new Map),Mt(this,"publishTimeout",K.toMiliseconds(K.ONE_MINUTE)),Mt(this,"initialPublishTimeout",K.toMiliseconds(K.ONE_SECOND*15)),Mt(this,"needsTransportRestart",!1),Mt(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const f=s?.ttl||_7,d=s?.prompt||!1,h=s?.tag||0,p=s?.id||wr().toString(),b=Ai(ba().protocol),v={id:p,method:s?.publishMethod||b.publish,params:Di({topic:r,message:i,ttl:f,prompt:d,tag:h,attestation:s?.attestation},s?.tvf)},B=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{Pe((o=v.params)==null?void 0:o.prompt)&&((a=v.params)==null||delete a.prompt),Pe((c=v.params)==null?void 0:c.tag)&&((u=v.params)==null||delete u.tag);const D=new Promise(async _=>{const x=({id:R})=>{var N;((N=v.id)==null?void 0:N.toString())===R.toString()&&(this.removeRequestFromQueue(R),this.relayer.events.removeListener(Se.publish,x),_())};this.relayer.events.on(Se.publish,x);const P=rn(new Promise((R,N)=>{this.rpcPublish(v,s).then(R).catch(F=>{this.logger.warn(F,F?.message),N(F)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await P,this.events.removeListener(Se.publish,x)}catch(R){this.queue.set(p,{request:v,opts:s,attempt:1}),this.logger.warn(R,R?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await rn(D,this.publishTimeout,B)}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)}}),Mt(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:l={}}=r,{attestation:f,tvf:d,publishMethod:h,prompt:p,tag:b,ttl:v=K.FIVE_MINUTES}=l,B=l.id||wr().toString(),D=Ai(ba().protocol),_=h||D.publish,x={id:B,method:_,params:Di(ly(Di({},u),{ttl:v,prompt:p,tag:b,attestation:f}),d)},P=`Failed to publish custom payload, please try again. id:${B} tag:${b}`;try{Pe((i=x.params)==null?void 0:i.prompt)&&((s=x.params)==null||delete s.prompt),Pe((o=x.params)==null?void 0:o.tag)&&((a=x.params)==null||delete a.tag);const R=new Promise(async N=>{const F=({id:z})=>{var M;((M=x.id)==null?void 0:M.toString())===z.toString()&&(this.removeRequestFromQueue(z),this.relayer.events.removeListener(Se.publish,F),N())};this.relayer.events.on(Se.publish,F);const $=rn(new Promise((z,M)=>{this.rpcPublish(x,l).then(z).catch(E=>{this.logger.warn(E,E?.message),M(E)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${_} id:${B} tag:${b}`);try{await $,this.events.removeListener(Se.publish,F)}catch(z){this.queue.set(B,{request:x,opts:l,attempt:1}),this.logger.warn(z,z?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:B,payload:u,opts:l}}),await rn(R,this.publishTimeout,P)}catch(R){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(R),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw R}finally{this.queue.delete(B)}}),Mt(this,"on",(r,i)=>{this.events.on(r,i)}),Mt(this,"once",(r,i)=>{this.events.once(r,i)}),Mt(this,"off",(r,i)=>{this.events.off(r,i)}),Mt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=rt(n,this.name),this.registerEventListeners()}get context(){return ht(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(Se.publish,Di(Di({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,ly(Di({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.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(_r.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Se.connection_stalled);return}this.checkQueue()}),this.relayer.on(Se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var FB=Object.defineProperty,LB=(t,e,n)=>e in t?FB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$i=(t,e,n)=>LB(t,typeof e!="symbol"?e+"":e,n);class kB{constructor(){$i(this,"map",new Map),$i(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),$i(this,"get",e=>this.map.get(e)||[]),$i(this,"exists",(e,n)=>this.get(e).includes(n)),$i(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),$i(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var qB=Object.defineProperty,MB=Object.defineProperties,jB=Object.getOwnPropertyDescriptors,fy=Object.getOwnPropertySymbols,zB=Object.prototype.hasOwnProperty,HB=Object.prototype.propertyIsEnumerable,Ol=(t,e,n)=>e in t?qB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ns=(t,e)=>{for(var n in e||(e={}))zB.call(e,n)&&Ol(t,n,e[n]);if(fy)for(var n of fy(e))HB.call(e,n)&&Ol(t,n,e[n]);return t},Dl=(t,e)=>MB(t,jB(e)),ye=(t,e,n)=>Ol(t,typeof e!="symbol"?e+"":e,n);class VB extends Vw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,ye(this,"subscriptions",new Map),ye(this,"topicMap",new kB),ye(this,"events",new Ke.exports.EventEmitter),ye(this,"name",P7),ye(this,"version",T7),ye(this,"pending",new Map),ye(this,"cached",[]),ye(this,"initialized",!1),ye(this,"storagePrefix",cn),ye(this,"subscribeTimeout",K.toMiliseconds(K.ONE_MINUTE)),ye(this,"initialSubscribeTimeout",K.toMiliseconds(K.ONE_SECOND*15)),ye(this,"clientId"),ye(this,"batchSubscribeTopicsLimit",500),ye(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ye(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=ba(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,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:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ye(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),ye(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),ye(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ye(this,"on",(r,i)=>{this.events.on(r,i)}),ye(this,"once",(r,i)=>{this.events.once(r,i)}),ye(this,"off",(r,i)=>{this.events.off(r,i)}),ye(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),ye(this,"start",async()=>{await this.onConnect()}),ye(this,"stop",async()=>{await this.onDisconnect()}),ye(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ye(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),ye(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(_r.pulse,async()=>{await this.checkPending()}),this.events.on(Dt.created,async r=>{const i=Dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Dt.deleted,async r=>{const i=Dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=rt(n,this.name),this.clientId=""}get context(){return ht(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,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=ba(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=Ee("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===me.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Ai(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===me.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},K.toMiliseconds(K.ONE_SECOND)),o;const u=new Promise(async f=>{const d=h=>{h.topic===e&&(this.events.removeListener(Dt.created,d),f(h.id))};this.events.on(Dt.created,d);try{const h=await rn(new Promise((p,b)=>{this.relayer.request(a).catch(v=>{this.logger.warn(v,v?.message),b(v)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Dt.created,d),f(h)}catch{}}),l=await rn(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(Se.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Ai(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await rn(new Promise(i=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(Se.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Ai(n.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await rn(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(Se.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Ai(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,Dl(Ns({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Ns({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,Ns({},n)),this.topicMap.set(n.topic,e),this.events.emit(Dt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(Dt.deleted,Dl(Ns({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Dt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(Dt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}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 n=>Dl(Ns({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await B5(K.toMiliseconds(K.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=G("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 Ft(e+await this.getClientId())}}var KB=Object.defineProperty,hy=Object.getOwnPropertySymbols,GB=Object.prototype.hasOwnProperty,WB=Object.prototype.propertyIsEnumerable,$l=(t,e,n)=>e in t?KB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dy=(t,e)=>{for(var n in e||(e={}))GB.call(e,n)&&$l(t,n,e[n]);if(hy)for(var n of hy(e))WB.call(e,n)&&$l(t,n,e[n]);return t},ue=(t,e,n)=>$l(t,typeof e!="symbol"?e+"":e,n);class ZB extends zw{constructor(e){super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new Ke.exports.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",A7),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",K.toMiliseconds(K.THIRTY_SECONDS+K.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",K.toMiliseconds(K.ONE_SECOND*15)),ue(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const s=n.id||wr().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${s}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),ue(this,"resetPingTimeout",()=>{Zo()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Se.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(Se.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ue(this,"registerProviderListeners",()=>{this.provider.on(kt.payload,this.onPayloadHandler),this.provider.on(kt.connect,this.onConnectHandler),this.provider.on(kt.disconnect,this.onDisconnectHandler),this.provider.on(kt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?rt(e.logger,this.name):hn(za({level:e.logger||I7})),this.messages=new $B(this.logger,e.core),this.subscriber=new VB(this,this.logger),this.publisher=new UB(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||j1,f5()?this.packageName=$0():h5()&&(this.bundleId=$0()),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 ht(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:me.relay},_a.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.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(Dt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Dt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,dy({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await rn(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(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await A1())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 n=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const i=De(K.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(Se.message,e),await this.recordMessageEvent(e,_a.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(kt.disconnect,s),await rn(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(kt.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(kt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(kt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;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: ${n}`);break}await new Promise(r=>setTimeout(r,K.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Zo())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.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 l7(new p7(b5({sdkVersion:xl,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,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),El(e)){if(!e.method.endsWith(B7))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:me.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(dy({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ea(e)&&this.events.emit(Se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_a.inbound),this.events.emit(Se.message,e))}async acknowledgePayload(e){const n=va(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(kt.payload,this.onPayloadHandler),this.provider.off(kt.connect,this.onConnectHandler),this.provider.off(kt.disconnect,this.onDisconnectHandler),this.provider.off(kt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await A1();d9(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(_r.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&y9())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Se.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},K.toMiliseconds(O7)))))}isInitialized(){if(!this.initialized){const{message:e}=G("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 YB(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function py(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function gy(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XB="[object RegExp]",JB="[object String]",QB="[object Number]",eO="[object Boolean]",yy="[object Arguments]",tO="[object Symbol]",nO="[object Date]",rO="[object Map]",iO="[object Set]",sO="[object Array]",oO="[object Function]",aO="[object ArrayBuffer]",Pl="[object Object]",cO="[object Error]",uO="[object DataView]",lO="[object Uint8Array]",fO="[object Uint8ClampedArray]",hO="[object Uint16Array]",dO="[object Uint32Array]",pO="[object BigUint64Array]",gO="[object Int8Array]",yO="[object Int16Array]",bO="[object Int32Array]",wO="[object BigInt64Array]",mO="[object Float32Array]",vO="[object Float64Array]";function EO(){}function by(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 xO(t,e,n){return Cs(t,e,void 0,void 0,void 0,void 0,n)}function Cs(t,e,n,r,i,s,o){const a=o(t,e,n,r,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 Us(t,e,s,o)}return Us(t,e,s,o)}function Us(t,e,n,r){if(Object.is(t,e))return!0;let i=gy(t),s=gy(e);if(i===yy&&(i=Pl),s===yy&&(s=Pl),i!==s)return!1;switch(i){case JB:return t.toString()===e.toString();case QB:{const c=t.valueOf(),u=e.valueOf();return YB(c,u)}case eO:case nO:case tO:return Object.is(t.valueOf(),e.valueOf());case XB:return t.source===e.source&&t.flags===e.flags;case oO:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case rO:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Cs(u,e.get(c),c,t,e,n,r))return!1;return!0}case iO:{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],d=u.findIndex(h=>Cs(f,h,void 0,t,e,n,r));if(d===-1)return!1;u.splice(d,1)}return!0}case sO:case lO:case fO:case hO:case dO:case pO:case gO:case yO:case bO:case wO:case mO:case vO:{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(!Cs(t[c],e[c],c,t,e,n,r))return!1;return!0}case aO:return t.byteLength!==e.byteLength?!1:Us(new Uint8Array(t),new Uint8Array(e),n,r);case uO:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Us(new Uint8Array(t),new Uint8Array(e),n,r);case cO:return t.name===e.name&&t.message===e.message;case Pl:{if(!(Us(t.constructor,e.constructor,n,r)||by(t)&&by(e)))return!1;const c=[...Object.keys(t),...py(t)],u=[...Object.keys(e),...py(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],d=t[f];if(!Object.hasOwn(e,f))return!1;const h=e[f];if(!Cs(d,h,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function _O(t,e){return xO(t,e,EO)}var SO=Object.defineProperty,wy=Object.getOwnPropertySymbols,IO=Object.prototype.hasOwnProperty,AO=Object.prototype.propertyIsEnumerable,Tl=(t,e,n)=>e in t?SO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,my=(t,e)=>{for(var n in e||(e={}))IO.call(e,n)&&Tl(t,n,e[n]);if(wy)for(var n of wy(e))AO.call(e,n)&&Tl(t,n,e[n]);return t},_t=(t,e,n)=>Tl(t,typeof e!="symbol"?e+"":e,n);class Zr extends Hw{constructor(e,n,r,i=cn,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,_t(this,"map",new Map),_t(this,"version",D7),_t(this,"cached",[]),_t(this,"initialized",!1),_t(this,"getKey"),_t(this,"storagePrefix",cn),_t(this,"recentlyDeleted",[]),_t(this,"recentlyDeletedLimit",200),_t(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Pe(o)?this.map.set(this.getKey(o),o):HI(o)?this.map.set(o.id,o):VI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),_t(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())}),_t(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),_t(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>_O(a[c],o[c]))):this.values)),_t(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=my(my({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),_t(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=rt(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return ht(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 n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}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:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var BO=Object.defineProperty,OO=(t,e,n)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e,n)=>OO(t,typeof e!="symbol"?e+"":e,n);class DO{constructor(e,n){this.core=e,this.logger=n,se(this,"name",R7),se(this,"version",N7),se(this,"events",new Ke.exports),se(this,"pairings"),se(this,"initialized",!1),se(this,"storagePrefix",cn),se(this,"ignoredPayloadTypes",[Tn]),se(this,"registeredMethods",[]),se(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),se(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),se(this,"create",async r=>{this.isInitialized();const i=ll(),s=await this.core.crypto.setSymKey(i),o=De(K.FIVE_MINUTES),a={protocol:M1},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=p1({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Gr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:u}}),se(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[un.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=d1(r.uri);i.props.properties.topic=s,i.addTrace(un.pairing_uri_validation_success),i.addTrace(un.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(un.existing_pairing),l.active)throw i.setError(Un.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(un.pairing_not_expired)}const f=c||De(K.FIVE_MINUTES),d={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,d),i.addTrace(un.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Gr.create,d),i.addTrace(un.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(un.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Un.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw i.setError(Un.subscribe_pairing_topic_failure),h}return i.addTrace(un.subscribe_pairing_topic_success),d}),se(this,"activate",async({topic:r})=>{this.isInitialized();const i=De(K.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),se(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=kr();this.events.once(le("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),se(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),se(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),se(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),se(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",Ee("USER_DISCONNECTED")),await this.deletePairing(i))}),se(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return p1({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),se(this,"sendRequest",async(r,i,s)=>{const o=Cn(i,s),a=await this.core.crypto.encode(r,o),c=Ds[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),se(this,"sendResult",async(r,i,s)=>{const o=va(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ds[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"sendError",async(r,i,s)=>{const o=vl(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ds[c]?Ds[c].res:Ds.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,Ee("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),se(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>rr(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),se(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;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)}}),se(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,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)}}),se(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Gr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{an(i)?this.events.emit(le("pairing_ping",s),{}):Lt(i)&&this.events.emit(le("pairing_ping",s),{error:i.error})},500)}),se(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Gr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=Ee("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),se(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(Ee("WC_METHOD_UNSUPPORTED",r))}),se(this,"isValidPair",(r,i)=>{var s;if(!xt(r)){const{message:a}=G("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(Un.malformed_pairing_uri),new Error(a)}if(!zI(r.uri)){const{message:a}=G("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(Un.malformed_pairing_uri),new Error(a)}const o=d1(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Un.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Un.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&K.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Un.pairing_expired);const{message:a}=G("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),se(this,"isValidPing",async r=>{if(!xt(r)){const{message:s}=G("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidDisconnect",async r=>{if(!xt(r)){const{message:s}=G("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidPairingTopic",async r=>{if(!Ie(r,!1)){const{message:i}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(rr(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=G("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=rt(n,this.name),this.pairings=new Zr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return ht(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Se.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==me.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);El(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):Ea(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(qt.expired,async e=>{const{topic:n}=N0(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Gr.expire,{topic:n}))})}}var $O=Object.defineProperty,PO=(t,e,n)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ze=(t,e,n)=>PO(t,typeof e!="symbol"?e+"":e,n);class TO extends qw{constructor(e,n){super(e,n),this.core=e,this.logger=n,ze(this,"records",new Map),ze(this,"events",new Ke.exports.EventEmitter),ze(this,"name",C7),ze(this,"version",U7),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",cn),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:De(K.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Yt.created,o)}),ze(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Lt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Yt.updated,i))}),ze(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),ze(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Yt.deleted,s)}}),this.persist()}),ze(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),ze(this,"on",(r,i)=>{this.events.on(r,i)}),ze(this,"once",(r,i)=>{this.events.once(r,i)}),ze(this,"off",(r,i)=>{this.events.off(r,i)}),ze(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=rt(n,this.name)}get context(){return ht(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(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:Cn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Yt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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(Yt.created,e=>{const n=Yt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Yt.updated,e=>{const n=Yt.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Yt.deleted,e=>{const n=Yt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(_r.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{K.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(Yt.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var RO=Object.defineProperty,NO=(t,e,n)=>e in t?RO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nt=(t,e,n)=>NO(t,typeof e!="symbol"?e+"":e,n);class CO extends Kw{constructor(e,n){super(e,n),this.core=e,this.logger=n,nt(this,"expirations",new Map),nt(this,"events",new Ke.exports.EventEmitter),nt(this,"name",F7),nt(this,"version",L7),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",cn),nt(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),nt(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),nt(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(qt.created,{target:s,expiration:o})}),nt(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),nt(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(qt.deleted,{target:i,expiration:s})}}),nt(this,"on",(r,i)=>{this.events.on(r,i)}),nt(this,"once",(r,i)=>{this.events.once(r,i)}),nt(this,"off",(r,i)=>{this.events.off(r,i)}),nt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=rt(n,this.name)}get context(){return ht(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 w5(e);if(typeof e=="number")return m5(e);const{message:n}=G("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}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(qt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=G("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}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 n=this.expirations.get(e);if(!n){const{message:r}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;K.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(qt.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(_r.pulse,()=>this.checkExpirations()),this.events.on(qt.created,e=>{const n=qt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(qt.expired,e=>{const n=qt.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(qt.deleted,e=>{const n=qt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var UO=Object.defineProperty,FO=(t,e,n)=>e in t?UO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>FO(t,typeof e!="symbol"?e+"":e,n);class LO extends Gw{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Ae(this,"name",k7),Ae(this,"abortController"),Ae(this,"isDevEnv"),Ae(this,"verifyUrlV3",M7),Ae(this,"storagePrefix",cn),Ae(this,"version",k1),Ae(this,"publicKey"),Ae(this,"fetchPromise"),Ae(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&K.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ae(this,"register",async i=>{if(!wi()||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=Or(),l=this.startAbortTimer(K.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",v),u.body.removeChild(b),h("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const b=u.createElement("iframe");b.src=c,b.style.display="none",b.addEventListener("error",p,{signal:this.abortController.signal});const v=B=>{if(B.data&&typeof B.data=="string")try{const D=JSON.parse(B.data);if(D.type==="verify_attestation"){if(lc(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(b),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",v),d(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(b),window.addEventListener("message",v,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",f),f}catch(u){this.logger.warn(u)}return""}),Ae(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(lc(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)}),Ae(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(K.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}),Ae(this,"getVerifyUrl",i=>{let s=i||$s;return j7.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${$s}`),s=$s),s}),Ae(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(K.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)}}),Ae(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ae(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ae(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")}}),Ae(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ae(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}),Ae(this,"validateAttestation",(i,s)=>{const o=gI(i,s.publicKey),a={hasExpired:K.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=rt(n,this.name),this.abortController=new AbortController,this.isDevEnv=Ru(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return ht(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),K.toMiliseconds(e))}}var kO=Object.defineProperty,qO=(t,e,n)=>e in t?kO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vy=(t,e,n)=>qO(t,typeof e!="symbol"?e+"":e,n);class MO extends Ww{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,vy(this,"context",z7),vy(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${H7}/${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=rt(n,this.context)}}var jO=Object.defineProperty,Ey=Object.getOwnPropertySymbols,zO=Object.prototype.hasOwnProperty,HO=Object.prototype.propertyIsEnumerable,Rl=(t,e,n)=>e in t?jO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fs=(t,e)=>{for(var n in e||(e={}))zO.call(e,n)&&Rl(t,n,e[n]);if(Ey)for(var n of Ey(e))HO.call(e,n)&&Rl(t,n,e[n]);return t},Ce=(t,e,n)=>Rl(t,typeof e!="symbol"?e+"":e,n);class VO extends Zw{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Ce(this,"context",K7),Ce(this,"storagePrefix",cn),Ce(this,"storageVersion",V7),Ce(this,"events",new Map),Ce(this,"shouldPersist",!1),Ce(this,"init",async()=>{if(!Ru())try{const i={eventId:U0(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:T0(this.core.relayer.protocol,this.core.relayer.version,xl)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Ce(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=U0(),l=this.core.projectId||"",f=Date.now(),d=Fs({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,d),this.shouldPersist=!0),d}),Ce(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 Fs(Fs({},a),this.setMethods(a.eventId))}),Ce(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Ce(this,"setEventListeners",()=>{this.core.heartbeat.on(_r.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{K.fromMiliseconds(Date.now())-K.fromMiliseconds(i.timestamp)>G7&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Ce(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Ce(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)}),Ce(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)}),Ce(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ce(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,Fs(Fs({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Ce(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)}}),Ce(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${W7}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${xl}${s}`,{method:"POST",body:JSON.stringify(i)})}),Ce(this,"getAppDomain",()=>P0().url),this.logger=rt(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var KO=Object.defineProperty,xy=Object.getOwnPropertySymbols,GO=Object.prototype.hasOwnProperty,WO=Object.prototype.propertyIsEnumerable,Nl=(t,e,n)=>e in t?KO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_y=(t,e)=>{for(var n in e||(e={}))GO.call(e,n)&&Nl(t,n,e[n]);if(xy)for(var n of xy(e))WO.call(e,n)&&Nl(t,n,e[n]);return t},we=(t,e,n)=>Nl(t,typeof e!="symbol"?e+"":e,n);class Cl extends Uw{constructor(e){var n;super(e),we(this,"protocol",L1),we(this,"version",k1),we(this,"name",xa),we(this,"relayUrl"),we(this,"projectId"),we(this,"customStoragePrefix"),we(this,"events",new Ke.exports.EventEmitter),we(this,"logger"),we(this,"heartbeat"),we(this,"relayer"),we(this,"crypto"),we(this,"storage"),we(this,"history"),we(this,"expirer"),we(this,"pairing"),we(this,"verify"),we(this,"echoClient"),we(this,"linkModeSupportedApps"),we(this,"eventClient"),we(this,"initialized",!1),we(this,"logChunkController"),we(this,"on",(a,c)=>this.events.on(a,c)),we(this,"once",(a,c)=>this.events.once(a,c)),we(this,"off",(a,c)=>this.events.off(a,c)),we(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),we(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:me.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||j1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=za({level:typeof e?.logger=="string"&&e.logger?e.logger:g7.logger,name:xa}),{logger:s,chunkLoggerController:o}=Rw({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.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=rt(s,this.name),this.heartbeat=new Ua,this.crypto=new xB(this,this.logger,e?.keychain),this.history=new TO(this,this.logger),this.expirer=new CO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new sw(_y(_y({},y7),e?.storageOptions)),this.relayer=new ZB({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new DO(this,this.logger),this.verify=new LO(this,this.logger,this.storage),this.echoClient=new MO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new VO(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new Cl(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem($7,r),n}get context(){return ht(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(z1,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(z1)||[],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 n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const Ul=Cl,Sy="wc",Iy=2,Ay="client",Fl=`${Sy}@${Iy}:${Ay}:`,Ll={name:Ay,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},By="WALLETCONNECT_DEEPLINK_CHOICE",ZO="proposal",Oy="Proposal expired",YO="session",Pi=K.SEVEN_DAYS,XO="engine",He={wc_sessionPropose:{req:{ttl:K.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:K.ONE_DAY,prompt:!1,tag:1104},res:{ttl:K.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:K.ONE_DAY,prompt:!1,tag:1106},res:{ttl:K.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:K.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:K.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:K.ONE_DAY,prompt:!1,tag:1112},res:{ttl:K.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:K.ONE_DAY,prompt:!1,tag:1114},res:{ttl:K.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:K.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:K.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:K.FIVE_MINUTES,prompt:!1,tag:1119}}},kl={min:K.FIVE_MINUTES,max:K.SEVEN_DAYS},fn={idle:"IDLE",active:"ACTIVE"},JO={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},QO="request",eD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tD="wc",nD="auth",rD="authKeys",iD="pairingTopics",sD="requests",Ia=`${tD}@${1.5}:${nD}:`,Aa=`${Ia}:PUB_KEY`;var oD=Object.defineProperty,aD=Object.defineProperties,cD=Object.getOwnPropertyDescriptors,Dy=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,ql=(t,e,n)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fe=(t,e)=>{for(var n in e||(e={}))uD.call(e,n)&&ql(t,n,e[n]);if(Dy)for(var n of Dy(e))lD.call(e,n)&&ql(t,n,e[n]);return t},Ue=(t,e)=>aD(t,cD(e)),H=(t,e,n)=>ql(t,typeof e!="symbol"?e+"":e,n);class fD extends Qw{constructor(e){super(e),H(this,"name",XO),H(this,"events",new Ke.exports),H(this,"initialized",!1),H(this,"requestQueue",{state:fn.idle,queue:[]}),H(this,"sessionRequestQueue",{state:fn.idle,queue:[]}),H(this,"emittedSessionRequests",new O5({limit:500})),H(this,"requestQueueDelay",K.ONE_SECOND),H(this,"expectedPairingMethodMap",new Map),H(this,"recentlyDeletedMap",new Map),H(this,"recentlyDeletedLimit",200),H(this,"relayMessageCache",[]),H(this,"pendingSessions",new Map),H(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(He)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},K.toMiliseconds(this.requestQueueDelay)))}),H(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Ue(fe({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=LI(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u,authentication:l}=r;let f=i,d,h=!1;try{if(f){const N=this.client.core.pairing.pairings.get(f);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=N.active}}catch(N){throw this.client.logger.error(`connect() -> pairing.get(${f}) failed`),N}if(!f||!h){const{topic:N,uri:F}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});f=N,d=F}if(!f){const{message:N}=G("NO_MATCHING_KEY",`connect() pairing topic: ${f}`);throw new Error(N)}const p=await this.client.core.crypto.generateKeyPair(),b=He.wc_sessionPropose.req.ttl||K.FIVE_MINUTES,v=De(b),B=Ue(fe(fe({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:M1}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:v,pairingTopic:f},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:on(),requests:{authentication:l?.map(N=>Ue(fe({},N),{aud:N.uri,version:"1",iat:new Date().toISOString()}))}}),D=le("session_connect",B.id),{reject:_,resolve:x,done:P}=kr(b,Oy),R=({id:N})=>{N===B.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(B.id),this.events.emit(D,{error:{message:Oy,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(D,({error:N,session:F})=>{this.client.events.off("proposal_expire",R),N?_(N):F&&x(F)}),await this.sendProposeSession({proposal:B,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:B.id}}}),await this.setProposal(B.id,B),{uri:d,approval:P}}),H(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),H(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[mr.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(z){throw o.setError(Ps.no_internet_connection),z}try{await this.isValidProposalId(n?.id)}catch(z){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Ps.proposal_not_found),z}try{await this.isValidApprove(n)}catch(z){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Ps.session_approve_namespace_validation_failure),z}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:b,proposer:v,requiredNamespaces:B,optionalNamespaces:D}=p;let _=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:b});_||(_=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:mr.session_approve_started,properties:{topic:b,trace:[mr.session_approve_started,mr.session_namespaces_validation_success]}}));const x=await this.client.core.crypto.generateKeyPair(),P=v.publicKey,R=await this.client.core.crypto.generateSharedKey(x,P),N=Ue(fe(fe(fe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:x,metadata:this.client.metadata},expiry:De(Pi)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{authentication:h}),F=me.relay;_.addTrace(mr.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:F,internal:{skipSubscribe:!0}})}catch(z){throw _.setError(Ps.subscribe_session_topic_failure),z}_.addTrace(mr.subscribe_session_topic_success);const $=Ue(fe({},N),{topic:R,requiredNamespaces:B,optionalNamespaces:D,pairingTopic:b,acknowledged:!1,self:N.controller,peer:{publicKey:v.publicKey,metadata:v.metadata},controller:x,transportType:me.relay});await this.client.session.set(R,$),_.addTrace(mr.store_session);try{await this.sendApproveSession({sessionTopic:R,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:x},sessionSettleRequest:N,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),_.addTrace(mr.session_approve_publish_success)}catch(z){throw this.client.logger.error(z),this.client.session.delete(R,Ee("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),z}return this.client.core.eventClient.deleteEvent({eventId:_.eventId}),await this.client.core.pairing.updateMetadata({topic:b,metadata:v.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:b}),await this.setExpiry(R,De(Pi)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),H(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:He.wc_sessionPropose.reject}),await this.deleteProposal(r)}),H(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=kr(),c=on(),u=wr().toString(),l=this.client.session.get(r).namespaces;return this.events.once(le("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:l}),a(f)}),{acknowledged:s}}),H(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=on(),{done:s,resolve:o,reject:a}=kr();return this.events.once(le("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,De(Pi)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),H(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(v){throw this.client.logger.error("request() -> isValidRequest() failed"),v}const{chainId:r,request:i,topic:s,expiry:o=He.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const c=on(),u=wr().toString(),{done:l,resolve:f,reject:d}=kr(o,"Request expired. Please try again.");this.events.once(le("session_request",c),({error:v,result:B})=>{v?d(v):f(B)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:Ue(fe({},i),{expiryTimestamp:De(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(v=>d(v)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const b={request:Ue(fe({},i),{expiryTimestamp:De(o)}),chainId:r};return await Promise.all([new Promise(async v=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:b,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,b)}).catch(B=>d(B)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),v()}),new Promise(async v=>{var B;if(!((B=a.sessionConfig)!=null&&B.disableDeepLink)){const D=await _5(this.client.core.storage,By);await v5({id:c,topic:s,wcDeepLink:D})}v()}),l()]).then(v=>v[2])}),H(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:s}=i,o=this.client.session.get(r);o.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);an(i)?await this.sendResult({id:s,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Lt(i)&&await this.sendError({id:s,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(n)}),H(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=on(),s=wr().toString(),{done:o,resolve:a,reject:c}=kr();this.events.once(le("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),H(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=wr().toString(),a=on();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),H(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:Ee("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=G("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),H(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>MI(r,n)))),H(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),H(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?me.link_mode:me.relay;o===me.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:d,exp:h,nbf:p,methods:b=[],expiry:v}=n,B=[...n.resources||[]],{topic:D,uri:_}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:_}});const x=await this.client.core.crypto.generateKeyPair(),P=ya(x);if(await Promise.all([this.client.auth.authKeys.set(Aa,{responseTopic:P,publicKey:x}),this.client.auth.pairingTopics.set(P,{topic:P,pairingTopic:D})]),await this.client.core.relayer.subscribe(P,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),b.length>0){const{namespace:I}=Wo(a[0]);let O=q_(I,"request",b);ia(B)&&(O=j_(O,B.pop())),B.push(O)}const R=v&&v>He.wc_sessionAuthenticate.req.ttl?v:He.wc_sessionAuthenticate.req.ttl,N={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:B},requester:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:De(R)},F={eip155:{chains:a,methods:[...new Set(["personal_sign",...b])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:F,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:x,metadata:this.client.metadata},expiryTimestamp:De(He.wc_sessionPropose.req.ttl),id:on()},{done:z,resolve:M,reject:E}=kr(R,"Request expired"),y=on(),m=le("session_connect",$.id),g=le("session_request",y),w=async({error:I,session:O})=>{this.events.off(g,S),I?E(I):O&&M({session:O})},S=async I=>{var O,T,L;if(await this.deletePendingAuthRequest(y,{message:"fulfilled",code:0}),I.error){const V=Ee("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return I.error.code===V.code?void 0:(this.events.off(m,w),E(I.error.message))}await this.deleteProposal($.id),this.events.off(m,w);const{cacaos:U,responder:k}=I.result,C=[],q=[];for(const V of U){await cg({cacao:V,projectId:this.client.core.projectId})||(this.client.logger.error(V,"Signature verification failed"),E(Ee("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Z}=V,Q=ia(Z.resources),ee=[Mu(Z.iss)],ie=ra(Z.iss);if(Q){const he=fg(Q),ve=hg(Q);C.push(...he),ee.push(...ve)}for(const he of ee)q.push(`${he}:${ie}`)}const j=await this.client.core.crypto.generateSharedKey(x,k.publicKey);let W;C.length>0&&(W={topic:j,acknowledged:!0,self:{publicKey:x,metadata:this.client.metadata},peer:k,controller:k.publicKey,expiry:De(Pi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:m1([...new Set(C)],[...new Set(q)]),transportType:o},await this.client.core.relayer.subscribe(j,{transportType:o}),await this.client.session.set(j,W),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:k.metadata}),W=this.client.session.get(j)),(O=this.client.metadata.redirect)!=null&&O.linkMode&&(T=k.metadata.redirect)!=null&&T.linkMode&&(L=k.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(k.metadata.redirect.universal),this.client.session.update(j,{transportType:me.link_mode})),M({auths:U,session:W})};this.events.once(m,w),this.events.once(g,S);let A;try{if(s){const I=Cn("wc_sessionAuthenticate",N,y);this.client.core.history.set(D,I);const O=await this.client.core.crypto.encode("",I,{type:xs,encoding:br});A=wa(r,D,O)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:N,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:y}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:$,expiry:He.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(I){throw this.events.off(m,w),this.events.off(g,S),I}return await this.setProposal($.id,$),await this.setAuthRequest(y,{request:Ue(fe({},N),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:A??_,response:z}}),H(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Wr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(v){throw s.setError(Ts.no_internet_connection),v}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Ts.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||me.relay;a===me.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ya(c),f={type:Tn,receiverPublicKey:c,senderPublicKey:u},d=[],h=[];for(const v of i){if(!await cg({cacao:v,projectId:this.client.core.projectId})){s.setError(Ts.invalid_cacao);const P=Ee("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:P,encodeOpts:f}),new Error(P.message)}s.addTrace(Wr.cacaos_verified);const{p:B}=v,D=ia(B.resources),_=[Mu(B.iss)],x=ra(B.iss);if(D){const P=fg(D),R=hg(D);d.push(...P),_.push(...R)}for(const P of _)h.push(`${P}:${x}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Wr.create_authenticated_session_topic);let b;if(d?.length>0){b={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:De(Pi),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:m1([...new Set(d)],[...new Set(h)]),transportType:a},s.addTrace(Wr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(v){throw s.setError(Ts.subscribe_authenticated_session_topic_failure),v}s.addTrace(Wr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,b),s.addTrace(Wr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Wr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(v){throw s.setError(Ts.authenticated_session_approve_publish_failure),v}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:b}}),H(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===me.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ya(o),u={type:Tn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:He.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),H(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return ug(r,i)}),H(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),H(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.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)===n.peer.metadata.url&&s.topic&&s.topic!==r.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(r){this.client.logger.error(r)}}),H(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,Ee("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(By).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,Ee("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=fn.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),H(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Ps.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,Ee("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),H(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=fn.idle,this.client.events.emit("session_request_expire",{id:n}))}),H(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),H(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),H(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,De(He.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),H(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=me.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),H(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||De(He.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),H(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:d={}}=n,h=Cn(i,s,c);let p;const b=!!l;try{const D=b?br:Et;p=await this.client.core.crypto.encode(r,h,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),D}let v;if(eD.includes(i)){const D=Ft(JSON.stringify(h)),_=Ft(p);v=await this.client.core.verify.register({id:_,decryptedId:D})}const B=fe(fe({},He[i].req),d);if(B.attestation=v,o&&(B.ttl=o),a&&(B.id=a),this.client.core.history.set(r,h),b){const D=wa(l,r,p);await global.Linking.openURL(D,this.client.name)}else B.tvf=Ue(fe({},f),{correlationId:h.id}),u?(B.internal=Ue(fe({},B.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,B)):this.client.core.relayer.publish(r,p,B).catch(D=>this.client.logger.error(D));return h.id}),H(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=Cn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:Et}),a=Ft(JSON.stringify(s)),c=Ft(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Ue(fe({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),H(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=va(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:Et}),l=Cn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:Et});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Ue(fe({},a),{publishMethod:"wc_approveSession"})})}),H(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=va(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?br:Et;l=await this.client.core.crypto.encode(i,u,Ue(fe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let d,h;try{d=await this.client.core.history.get(i,r);const p=d.request;try{h=this.getTVFParams(r,p.params,s)}catch(b){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${b?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(f){const p=wa(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,b=He[p].res;b.tvf=Ue(fe({},h),{correlationId:r}),o?(b.internal=Ue(fe({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,b)):this.client.core.relayer.publish(i,l,b).catch(v=>this.client.logger.error(v))}await this.client.core.history.resolve(u)}),H(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=vl(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?br:Et;l=await this.client.core.crypto.encode(i,u,Ue(fe({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),h}let d;try{d=await this.client.core.history.get(i,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),h}if(f){const h=wa(c,i,l);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||He[h].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),H(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;rr(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{rr(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),H(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),H(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),H(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===fn.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=fn.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=fn.idle}),H(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),H(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),H(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=G("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),H(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),H(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(Un.proposal_listener_not_found)),this.isValidConnect(fe({},i.params));const l=a.expiryTimestamp||De(He.wc_sessionPropose.req.ttl),f=fe({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:s,hash:Ft(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(un.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:He.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),H(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(an(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const 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:n,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:n})}else if(Lt(r)){await this.deleteProposal(s);const o=le("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),H(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,authentication:h}=r.params,p=[...this.pendingSessions.values()].find(B=>B.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const b=this.client.proposal.get(p.proposalId),v=Ue(fe(fe(fe({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:b.requiredNamespaces,optionalNamespaces:b.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:me.relay,authentication:h});await this.client.session.set(v.topic,v),await this.setExpiry(v.topic,v.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:v.peer.metadata}),this.client.events.emit("session_connect",{session:v}),this.events.emit(le("session_connect",p.proposalId),{session:v}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(v),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),H(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;an(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(le("session_approve",i),{})):Lt(r)&&(await this.client.session.delete(n,Ee("USER_DISCONNECTED")),this.events.emit(le("session_approve",i),{error:r.error}))}),H(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=As.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:Ee("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fe({topic:n},i));try{As.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw As.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),H(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),H(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=le("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);an(r)?this.events.emit(le("session_update",i),{}):Lt(r)&&this.events.emit(le("session_update",i),{error:r.error})}),H(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,De(Pi)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),H(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=le("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);an(r)?this.events.emit(le("session_extend",i),{}):Lt(r)&&this.events.emit(le("session_extend",i),{error:r.error})}),H(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),H(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=le("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);an(r)?this.events.emit(le("session_ping",i),{}):Lt(r)&&this.events.emit(le("session_ping",i),{error:r.error})},500)}),H(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(Se.publish,async()=>{s(await this.deleteSession({topic:n,id:i}))})}),this.sendResult({id:i,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:Ee("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),H(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:d}=a;try{await this.isValidRequest(fe({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Ft(JSON.stringify(Cn("wc_sessionRequest",d,f))),encryptedId:u,metadata:h.peer.metadata,transportType:l}),b={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(b),l===me.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=h.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(b):(this.addSessionRequestToSessionRequestQueue(b),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),H(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=le("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);an(r)?this.events.emit(le("session_request",i),{result:r.result}):Lt(r)&&this.events.emit(le("session_request",i),{error:r.error})}),H(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=As.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(fe({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),As.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),H(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),an(r)?this.events.emit(le("session_request",i),{result:r.result}):Lt(r)&&this.events.emit(le("session_request",i),{error:r.error})}),H(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,d=await this.getVerifyContext({attestationId:o,hash:Ft(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:i,transportType:c}),c===me.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:Tn,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:h,rpcOpts:He.wc_sessionAuthenticate.autoReject,appLink:d})}}),H(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),H(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=fn.idle,this.processSessionRequestQueue()},K.toMiliseconds(this.requestQueueDelay))}),H(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=le("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(le("session_request",s.request.id),{error:r})})}),H(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===fn.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),H(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=fn.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),H(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:Cn("wc_sessionPropose",Ue(fe({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),H(this,"isValidConnect",async n=>{if(!xt(n)){const{message:u}=G("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(Pe(r)||await this.isValidPairingTopic(r),!QI(c,!0)){const{message:u}=G("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Pe(i)&&Is(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(!Pe(s)&&Is(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Pe(o)||this.validateSessionProps(o,"sessionProperties"),!Pe(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)}`)}}),H(this,"validateNamespaces",(n,r)=>{const i=JI(n,"connect()",r);if(i)throw new Error(i.message)}),H(this,"isValidApprove",async n=>{if(!xt(n))throw new Error(G("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=dl(i,"approve()");if(u)throw new Error(u.message);const l=S1(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Ie(s,!0)){const{message:f}=G("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(Pe(o)||this.validateSessionProps(o,"sessionProperties"),!Pe(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),H(this,"isValidReject",async n=>{if(!xt(n)){const{message:s}=G("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!t9(i)){const{message:s}=G("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),H(this,"isValidSessionSettleRequest",n=>{if(!xt(n)){const{message:u}=G("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!x1(r)){const{message:u}=G("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=KI(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=dl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(rr(o)){const{message:u}=G("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),H(this,"isValidUpdate",async n=>{if(!xt(n)){const{message:c}=G("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=dl(i,"update()");if(o)throw new Error(o.message);const a=S1(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),H(this,"isValidExtend",async n=>{if(!xt(n)){const{message:i}=G("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),H(this,"isValidRequest",async n=>{if(!xt(n)){const{message:c}=G("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!_1(a,s)){const{message:c}=G("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!n9(i)){const{message:c}=G("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!s9(a,s,i.method)){const{message:c}=G("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!u9(o,kl)){const{message:c}=G("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${kl.min} and ${kl.max}`);throw new Error(c)}}),H(this,"isValidRespond",async n=>{var r;if(!xt(n)){const{message:o}=G("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!r9(s)){const{message:o}=G("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),H(this,"isValidPing",async n=>{if(!xt(n)){const{message:i}=G("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),H(this,"isValidEmit",async n=>{if(!xt(n)){const{message:a}=G("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!_1(o,s)){const{message:a}=G("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!i9(i)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!o9(o,s,i.name)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),H(this,"isValidDisconnect",async n=>{if(!xt(n)){const{message:i}=G("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),H(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!Ie(i,!1))throw new Error("uri is required parameter");if(!Ie(s,!1))throw new Error("domain is required parameter");if(!Ie(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Wo(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Wo(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),H(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||$s,validation:"UNKNOWN",origin:o.url||""}};try{if(a===me.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:r,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}),H(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=G("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),H(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),H(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),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)}}}),H(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),H(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,d;return!n||r!==me.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=n?.redirect)==null?void 0:l.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),H(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),H(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=C0(n,"topic")||"",i=decodeURIComponent(C0(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:me.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),H(this,"registerLinkModeListeners",async()=>{var n;if(Ru()||nr()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),H(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),H(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.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}),H(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=JO[s];if(s==="sui_signTransaction")return[E_(r.transactionBytes)];if(s==="near_signTransaction")return[rg(r)];if(s==="near_signTransactions")return r.map(c=>rg(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[S9({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Oi(r)?r.map(c=>ig(c)):[ig(r)];if(s==="cosmos_signDirect")return[__(r)];if(s==="wallet_sendCalls")return S_(r);if(typeof r=="string")return[r];const a=r[o.key];if(Oi(a))return s==="solana_signAllTransactions"?a.map(c=>v_(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,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Se.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(Aa)?this.client.auth.authKeys.get(Aa):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===me.link_mode?br:Et});El(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Ft(r)})):Ea(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(qt.expired,async e=>{const{topic:n,id:r}=N0(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,G("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,G("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Gr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Gr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Ie(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(rr(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=G("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!Ie(e,!1)){const{message:n}=G("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(rr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=G("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=G("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}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(Ie(e,!1)){const{message:n}=G("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=G("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!e9(e)){const{message:n}=G("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(rr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=G("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class hD extends Zr{constructor(e,n){super(e,n,ZO,Fl),this.core=e,this.logger=n}}class $y extends Zr{constructor(e,n){super(e,n,YO,Fl),this.core=e,this.logger=n}}class dD extends Zr{constructor(e,n){super(e,n,QO,Fl,r=>r.id),this.core=e,this.logger=n}}class pD extends Zr{constructor(e,n){super(e,n,rD,Ia,()=>Aa),this.core=e,this.logger=n}}class gD extends Zr{constructor(e,n){super(e,n,iD,Ia),this.core=e,this.logger=n}}class yD extends Zr{constructor(e,n){super(e,n,sD,Ia,r=>r.id),this.core=e,this.logger=n}}var bD=Object.defineProperty,wD=(t,e,n)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ml=(t,e,n)=>wD(t,typeof e!="symbol"?e+"":e,n);class mD{constructor(e,n){this.core=e,this.logger=n,Ml(this,"authKeys"),Ml(this,"pairingTopics"),Ml(this,"requests"),this.authKeys=new pD(this.core,this.logger),this.pairingTopics=new gD(this.core,this.logger),this.requests=new yD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var vD=Object.defineProperty,ED=(t,e,n)=>e in t?vD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>ED(t,typeof e!="symbol"?e+"":e,n);class jl extends Jw{constructor(e){super(e),oe(this,"protocol",Sy),oe(this,"version",Iy),oe(this,"name",Ll.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new Ke.exports.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ll.name,this.metadata=p5(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:hn(za({level:e?.logger||Ll.logger}));this.core=e?.core||new Ul(e),this.logger=rt(n,this.name),this.session=new $y(this.core,this.logger),this.proposal=new hD(this.core,this.logger),this.pendingRequest=new dD(this.core,this.logger),this.engine=new fD(this),this.auth=new mD(this.core,this.logger)}static async init(e){const n=new jl(e);return await n.initialize(),n}get context(){return ht(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 xD=$y,_D=jl;class SD extends Ke.exports{constructor(){super()}}class Py{constructor(e){this.opts=e}}class Ty{constructor(e){this.client=e}}var ID=Object.defineProperty,AD=Object.defineProperties,BD=Object.getOwnPropertyDescriptors,Ry=Object.getOwnPropertySymbols,OD=Object.prototype.hasOwnProperty,DD=Object.prototype.propertyIsEnumerable,Ny=(t,e,n)=>e in t?ID(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,$D=(t,e)=>{for(var n in e||(e={}))OD.call(e,n)&&Ny(t,n,e[n]);if(Ry)for(var n of Ry(e))DD.call(e,n)&&Ny(t,n,e[n]);return t},PD=(t,e)=>AD(t,BD(e));class TD extends Ty{constructor(e){super(e),this.init=async()=>{this.signClient=await _D.init({core:this.client.core,metadata:this.client.metadata,signConfig:this.client.signConfig}),this.signClient.core.eventClient.init().catch(n=>{this.client.logger.warn(n)})},this.pair=async n=>{await this.client.core.pairing.pair(n)},this.approveSession=async n=>{const{topic:r,acknowledged:i}=await this.signClient.approve(PD($D({},n),{id:n.id,namespaces:n.namespaces,sessionProperties:n.sessionProperties,sessionConfig:n.sessionConfig,proposalRequestsResponses:n?.proposalRequestsResponses}));return await i(),this.signClient.session.get(r)},this.rejectSession=async n=>await this.signClient.reject(n),this.updateSession=async n=>await this.signClient.update(n),this.extendSession=async n=>await this.signClient.extend(n),this.respondSessionRequest=async n=>await this.signClient.respond(n),this.disconnectSession=async n=>await this.signClient.disconnect(n),this.emitSessionEvent=async n=>await this.signClient.emit(n),this.getActiveSessions=()=>this.signClient.session.getAll().reduce((n,r)=>(n[r.topic]=r,n),{}),this.getPendingSessionProposals=()=>this.signClient.proposal.getAll(),this.getPendingSessionRequests=()=>this.signClient.getPendingSessionRequests(),this.approveSessionAuthenticate=async n=>await this.signClient.approveSessionAuthenticate(n),this.rejectSessionAuthenticate=async n=>await this.signClient.rejectSessionAuthenticate(n),this.formatAuthMessage=n=>this.signClient.formatAuthMessage(n),this.registerDeviceToken=n=>this.client.core.echoClient.registerDeviceToken(n),this.on=(n,r)=>(this.setEvent(n,"off"),this.setEvent(n,"on"),this.client.events.on(n,r)),this.once=(n,r)=>(this.setEvent(n,"off"),this.setEvent(n,"once"),this.client.events.once(n,r)),this.off=(n,r)=>(this.setEvent(n,"off"),this.client.events.off(n,r)),this.removeListener=(n,r)=>(this.setEvent(n,"removeListener"),this.client.events.removeListener(n,r)),this.onSessionRequest=n=>{this.client.events.emit("session_request",n)},this.onSessionProposal=n=>{this.client.events.emit("session_proposal",n)},this.onSessionDelete=n=>{this.client.events.emit("session_delete",n)},this.onProposalExpire=n=>{this.client.events.emit("proposal_expire",n)},this.onSessionRequestExpire=n=>{this.client.events.emit("session_request_expire",n)},this.onSessionRequestAuthenticate=n=>{this.client.events.emit("session_authenticate",n)},this.setEvent=(n,r)=>{switch(n){case"session_request":this.signClient.events[r]("session_request",this.onSessionRequest);break;case"session_proposal":this.signClient.events[r]("session_proposal",this.onSessionProposal);break;case"session_delete":this.signClient.events[r]("session_delete",this.onSessionDelete);break;case"proposal_expire":this.signClient.events[r]("proposal_expire",this.onProposalExpire);break;case"session_request_expire":this.signClient.events[r]("session_request_expire",this.onSessionRequestExpire);break;case"session_authenticate":this.signClient.events[r]("session_authenticate",this.onSessionRequestAuthenticate);break}},this.signClient={}}}const RD={decryptMessage:async t=>{const e={core:new Ul({storageOptions:t.storageOptions,storage:t.storage})};await e.core.crypto.init();const n=e.core.crypto.decode(t.topic,t.encryptedMessage);return e.core=null,n},getMetadata:async t=>{const e={core:new Ul({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new xD(e.core,e.core.logger),await e.sessionStore.init();const n=e.sessionStore.get(t.topic),r=n?.peer.metadata;return e.core=null,e.sessionStore=null,r}},Cy=class extends Py{constructor(t){super(t),this.events=new Ke.exports,this.on=(e,n)=>this.engine.on(e,n),this.once=(e,n)=>this.engine.once(e,n),this.off=(e,n)=>this.engine.off(e,n),this.removeListener=(e,n)=>this.engine.removeListener(e,n),this.pair=async e=>{try{return await this.engine.pair(e)}catch(n){throw this.logger.error(n.message),n}},this.approveSession=async e=>{try{return await this.engine.approveSession(e)}catch(n){throw this.logger.error(n.message),n}},this.rejectSession=async e=>{try{return await this.engine.rejectSession(e)}catch(n){throw this.logger.error(n.message),n}},this.updateSession=async e=>{try{return await this.engine.updateSession(e)}catch(n){throw this.logger.error(n.message),n}},this.extendSession=async e=>{try{return await this.engine.extendSession(e)}catch(n){throw this.logger.error(n.message),n}},this.respondSessionRequest=async e=>{try{return await this.engine.respondSessionRequest(e)}catch(n){throw this.logger.error(n.message),n}},this.disconnectSession=async e=>{try{return await this.engine.disconnectSession(e)}catch(n){throw this.logger.error(n.message),n}},this.emitSessionEvent=async e=>{try{return await this.engine.emitSessionEvent(e)}catch(n){throw this.logger.error(n.message),n}},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(n){throw this.logger.error(n.message),n}},this.approveSessionAuthenticate=e=>{try{return this.engine.approveSessionAuthenticate(e)}catch(n){throw this.logger.error(n.message),n}},this.rejectSessionAuthenticate=e=>{try{return this.engine.rejectSessionAuthenticate(e)}catch(n){throw this.logger.error(n.message),n}},this.formatAuthMessage=e=>{try{return this.engine.formatAuthMessage(e)}catch(n){throw this.logger.error(n.message),n}},this.metadata=t.metadata,this.name=t.name||Oa,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new TD(this)}static async init(t){const e=new Cy(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 zl=Cy;zl.notifications=RD;const ND=zl;Ve.CLIENT_CONTEXT=Oa,Ve.CLIENT_STORAGE_OPTIONS=Xy,Ve.CLIENT_STORAGE_PREFIX=Yy,Ve.IWalletKit=Py,Ve.IWalletKitEngine=Ty,Ve.IWalletKitEvents=SD,Ve.PROTOCOL=nf,Ve.PROTOCOL_VERSION=Zy,Ve.REQUEST_CONTEXT=Jy,Ve.WalletKit=ND,Ve.default=zl,Object.defineProperty(Ve,"__esModule",{value:!0})});
42
41
  //# sourceMappingURL=index.umd.js.map