@reown/walletkit 1.2.4 → 1.2.5

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(Fe,yt){typeof exports=="object"&&typeof module<"u"?yt(exports):typeof define=="function"&&define.amd?define(["exports"],yt):(Fe=typeof globalThis<"u"?globalThis:Fe||self,yt(Fe["@reown/walletkit"]={}))})(this,function(Fe){"use strict";var yt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ka(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 Le={exports:{}},Tr=typeof Reflect=="object"?Reflect:null,Ma=Tr&&typeof Tr.apply=="function"?Tr.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},oi;Tr&&typeof Tr.ownKeys=="function"?oi=Tr.ownKeys:Object.getOwnPropertySymbols?oi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:oi=function(e){return Object.getOwnPropertyNames(e)};function jf(t){console&&console.warn&&console.warn(t)}var ja=Number.isNaN||function(e){return e!==e};function te(){te.init.call(this)}Le.exports=te,Le.exports.once=Kf,te.EventEmitter=te,te.prototype._events=void 0,te.prototype._eventsCount=0,te.prototype._maxListeners=void 0;var qa=10;function ai(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(te,"defaultMaxListeners",{enumerable:!0,get:function(){return qa},set:function(t){if(typeof t!="number"||t<0||ja(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");qa=t}}),te.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},te.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ja(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 za(t){return t._maxListeners===void 0?te.defaultMaxListeners:t._maxListeners}te.prototype.getMaxListeners=function(){return za(this)},te.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")Ma(c,this,r);else for(var u=c.length,l=Ga(c,u),n=0;n<u;++n)Ma(l[n],this,r);return!0};function Va(t,e,r,n){var i,s,o;if(ai(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=za(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,jf(a)}return t}te.prototype.addListener=function(e,r){return Va(this,e,r,!1)},te.prototype.on=te.prototype.addListener,te.prototype.prependListener=function(e,r){return Va(this,e,r,!0)};function qf(){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 Ka(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=qf.bind(n);return i.listener=r,n.wrapFn=i,i}te.prototype.once=function(e,r){return ai(r),this.on(e,Ka(this,e,r)),this},te.prototype.prependOnceListener=function(e,r){return ai(r),this.prependListener(e,Ka(this,e,r)),this},te.prototype.removeListener=function(e,r){var n,i,s,o,a;if(ai(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():zf(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this},te.prototype.off=te.prototype.removeListener,te.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 Ha(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?Vf(i):Ga(i,i.length)}te.prototype.listeners=function(e){return Ha(this,e,!0)},te.prototype.rawListeners=function(e){return Ha(this,e,!1)},te.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Wa.call(t,e)},te.prototype.listenerCount=Wa;function Wa(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}te.prototype.eventNames=function(){return this._eventsCount>0?oi(this._events):[]};function Ga(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function zf(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Vf(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Kf(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))}Ya(t,e,s,{once:!0}),e!=="error"&&Hf(t,i,{once:!0})})}function Hf(t,e,r){typeof t.on=="function"&&Ya(t,"error",e,r)}function Ya(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 Za="wc",Wf=2,ls="WalletKit",Gf=`${Za}@2:${ls}:`,Yf={database:":memory:"},Zf="request";var L={};/*! *****************************************************************************
1
+ (function(Fe,yt){typeof exports=="object"&&typeof module<"u"?yt(exports):typeof define=="function"&&define.amd?define(["exports"],yt):(Fe=typeof globalThis<"u"?globalThis:Fe||self,yt(Fe["@reown/walletkit"]={}))})(this,function(Fe){"use strict";var yt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ka(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 Le={exports:{}},Cr=typeof Reflect=="object"?Reflect:null,Ma=Cr&&typeof Cr.apply=="function"?Cr.apply:function(e,r,n){return Function.prototype.apply.call(e,r,n)},oi;Cr&&typeof Cr.ownKeys=="function"?oi=Cr.ownKeys:Object.getOwnPropertySymbols?oi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:oi=function(e){return Object.getOwnPropertyNames(e)};function jf(t){console&&console.warn&&console.warn(t)}var ja=Number.isNaN||function(e){return e!==e};function te(){te.init.call(this)}Le.exports=te,Le.exports.once=Kf,te.EventEmitter=te,te.prototype._events=void 0,te.prototype._eventsCount=0,te.prototype._maxListeners=void 0;var qa=10;function ai(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(te,"defaultMaxListeners",{enumerable:!0,get:function(){return qa},set:function(t){if(typeof t!="number"||t<0||ja(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");qa=t}}),te.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},te.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ja(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 za(t){return t._maxListeners===void 0?te.defaultMaxListeners:t._maxListeners}te.prototype.getMaxListeners=function(){return za(this)},te.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")Ma(c,this,r);else for(var u=c.length,l=Ga(c,u),n=0;n<u;++n)Ma(l[n],this,r);return!0};function Va(t,e,r,n){var i,s,o;if(ai(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=za(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,jf(a)}return t}te.prototype.addListener=function(e,r){return Va(this,e,r,!1)},te.prototype.on=te.prototype.addListener,te.prototype.prependListener=function(e,r){return Va(this,e,r,!0)};function qf(){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 Ka(t,e,r){var n={fired:!1,wrapFn:void 0,target:t,type:e,listener:r},i=qf.bind(n);return i.listener=r,n.wrapFn=i,i}te.prototype.once=function(e,r){return ai(r),this.on(e,Ka(this,e,r)),this},te.prototype.prependOnceListener=function(e,r){return ai(r),this.prependListener(e,Ka(this,e,r)),this},te.prototype.removeListener=function(e,r){var n,i,s,o,a;if(ai(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():zf(n,s),n.length===1&&(i[e]=n[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||r)}return this},te.prototype.off=te.prototype.removeListener,te.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 Ha(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?Vf(i):Ga(i,i.length)}te.prototype.listeners=function(e){return Ha(this,e,!0)},te.prototype.rawListeners=function(e){return Ha(this,e,!1)},te.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Wa.call(t,e)},te.prototype.listenerCount=Wa;function Wa(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}te.prototype.eventNames=function(){return this._eventsCount>0?oi(this._events):[]};function Ga(t,e){for(var r=new Array(e),n=0;n<e;++n)r[n]=t[n];return r}function zf(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Vf(t){for(var e=new Array(t.length),r=0;r<e.length;++r)e[r]=t[r].listener||t[r];return e}function Kf(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))}Ya(t,e,s,{once:!0}),e!=="error"&&Hf(t,i,{once:!0})})}function Hf(t,e,r){typeof t.on=="function"&&Ya(t,"error",e,r)}function Ya(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 Za="wc",Wf=2,ls="WalletKit",Gf=`${Za}@2:${ls}:`,Yf={database:":memory:"},Zf="request";var L={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -11,19 +11,19 @@
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 hs=function(t,e){return hs=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])},hs(t,e)};function Jf(t,e){hs(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ds=function(){return ds=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},ds.apply(this,arguments)};function Xf(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 Qf(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 ep(t,e){return function(r,n){e(r,n,t)}}function tp(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function rp(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 np(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 ip(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function sp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function fs(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 Ja(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 op(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ja(arguments[e]));return t}function ap(){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 cp(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof fn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function up(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 lp(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 fs=="function"?fs(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 hp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function dp(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 fp(t){return t&&t.__esModule?t:{default:t}}function pp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function gp(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 yp=Object.freeze({__proto__:null,__extends:Jf,get __assign(){return ds},__rest:Xf,__decorate:Qf,__param:ep,__metadata:tp,__awaiter:rp,__generator:np,__createBinding:ip,__exportStar:sp,__values:fs,__read:Ja,__spread:op,__spreadArrays:ap,__await:fn,__asyncGenerator:cp,__asyncDelegator:up,__asyncValues:lp,__makeTemplateObject:hp,__importStar:dp,__importDefault:fp,__classPrivateFieldGet:pp,__classPrivateFieldSet:gp}),ci=ka(yp),ps={},pn={},Xa;function wp(){if(Xa)return pn;Xa=1,Object.defineProperty(pn,"__esModule",{value:!0}),pn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return pn.delay=t,pn}var cr={},gs={},ur={},Qa;function mp(){return Qa||(Qa=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.ONE_THOUSAND=ur.ONE_HUNDRED=void 0,ur.ONE_HUNDRED=100,ur.ONE_THOUSAND=1e3),ur}var ys={},ec;function bp(){return ec||(ec=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}(ys)),ys}var tc;function rc(){return tc||(tc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(mp(),t),e.__exportStar(bp(),t)}(gs)),gs}var nc;function vp(){if(nc)return cr;nc=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.fromMiliseconds=cr.toMiliseconds=void 0;const t=rc();function e(n){return n*t.ONE_THOUSAND}cr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return cr.fromMiliseconds=r,cr}var ic;function Ep(){return ic||(ic=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(wp(),t),e.__exportStar(vp(),t)}(ps)),ps}var Rr={},sc;function _p(){if(sc)return Rr;sc=1,Object.defineProperty(Rr,"__esModule",{value:!0}),Rr.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 Rr.Watch=t,Rr.default=t,Rr}var ws={},gn={},oc;function Sp(){if(oc)return gn;oc=1,Object.defineProperty(gn,"__esModule",{value:!0}),gn.IWatch=void 0;class t{}return gn.IWatch=t,gn}var ac;function xp(){return ac||(ac=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ci.__exportStar(Sp(),t)}(ws)),ws}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(Ep(),t),e.__exportStar(_p(),t),e.__exportStar(xp(),t),e.__exportStar(rc(),t)})(L);class lr{}class Ip extends lr{constructor(e){super()}}const cc=L.FIVE_SECONDS,Cr={pulse:"heartbeat_pulse"};class ms extends Ip{constructor(e){super(e),this.events=new Le.exports.EventEmitter,this.interval=cc,this.interval=e?.interval||cc}static async init(e){const r=new ms(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(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(Cr.pulse)}}const Dp=/"(?:_|\\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*:/,Op=/"(?: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*:/,$p=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ap(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Pp(t);return}return e}function Pp(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function ui(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(!$p.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Dp.test(t)||Op.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Ap)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}function Tp(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function be(t,...e){try{return Tp(t(...e))}catch(r){return Promise.reject(r)}}function Rp(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Cp(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function li(t){if(Rp(t))return String(t);if(Cp(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return li(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function uc(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const bs="base64:";function Np(t){if(typeof t=="string")return t;uc();const e=Buffer.from(t).toString("base64");return bs+e}function Bp(t){return typeof t!="string"||!t.startsWith(bs)?t:(uc(),Buffer.from(t.slice(bs.length),"base64"))}function Ke(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Fp(...t){return Ke(t.join(":"))}function hi(t){return t=Ke(t),t?t+":":""}function qD(t){return t}const Lp="memory",Up=()=>{const t=new Map;return{name:Lp,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 kp(t={}){const e={mounts:{"":t.driver||Up()},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=Ke(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 lc(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 d=new Map,p=f=>{let y=d.get(f.base);return y||(y={driver:f.driver,base:f.base,items:[]},d.set(f.base,y)),y};for(const f of u){const y=typeof f=="string",g=Ke(y?f:f.key),w=y?void 0:f.value,m=y||!f.options?l:{...l,...f.options},b=r(g);p(b).items.push({key:g,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(f=>h(f))).then(f=>f.flat())},c={hasItem(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return be(d.hasItem,h,l)},getItem(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return be(d.getItem,h,l).then(p=>ui(p))},getItems(u,l){return a(u,l,h=>h.driver.getItems?be(h.driver.getItems,h.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(p=>({key:Fp(h.base,p.key),value:ui(p.value)}))):Promise.all(h.items.map(d=>be(h.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:ui(p)})))))},getItemRaw(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return d.getItemRaw?be(d.getItemRaw,h,l):be(d.getItem,h,l).then(p=>Bp(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ke(u);const{relativeKey:d,driver:p}=r(u);p.setItem&&(await be(p.setItem,d,li(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return be(h.driver.setItems,h.items.map(d=>({key:d.relativeKey,value:li(d.value),options:d.options})),l);h.driver.setItem&&await Promise.all(h.items.map(d=>be(h.driver.setItem,d.relativeKey,li(d.value),d.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ke(u);const{relativeKey:d,driver:p}=r(u);if(p.setItemRaw)await be(p.setItemRaw,d,l,h);else if(p.setItem)await be(p.setItem,d,Np(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ke(u);const{relativeKey:h,driver:d}=r(u);d.removeItem&&(await be(d.removeItem,h,l),(l.removeMeta||l.removeMata)&&await be(d.removeItem,h+"$",l),d.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ke(u);const{relativeKey:h,driver:d}=r(u),p=Object.create(null);if(d.getMeta&&Object.assign(p,await be(d.getMeta,h,l)),!l.nativeOnly){const f=await be(d.getItem,h+"$",l).then(y=>ui(y));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(p,f))}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=hi(u);const h=n(u,!0);let d=[];const p=[];for(const f of h){const y=await be(f.driver.getKeys,f.relativeBase,l);for(const g of y){const w=f.mountpoint+Ke(g);d.some(m=>w.startsWith(m))||p.push(w)}d=[f.mountpoint,...d.filter(g=>!g.startsWith(f.mountpoint))]}return u?p.filter(f=>f.startsWith(u)&&f[f.length-1]!=="$"):p.filter(f=>f[f.length-1]!=="$")},async clear(u,l={}){u=hi(u),await Promise.all(n(u,!1).map(async h=>{if(h.driver.clear)return be(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const d=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(d.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>hc(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=hi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,d)=>d.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(lc(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=hi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),l&&await hc(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ke(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ke(u),n(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,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 lc(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function hc(t){typeof t.dispose=="function"&&await be(t.dispose)}function hr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function dc(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const n=hr(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}let vs;function yn(){return vs||(vs=dc("keyval-store","keyval")),vs}function fc(t,e=yn()){return e("readonly",r=>hr(r.get(t)))}function Mp(t,e,r=yn()){return r("readwrite",n=>(n.put(e,t),hr(n.transaction)))}function jp(t,e=yn()){return e("readwrite",r=>(r.delete(t),hr(r.transaction)))}function qp(t=yn()){return t("readwrite",e=>(e.clear(),hr(e.transaction)))}function zp(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},hr(t.transaction)}function Vp(t=yn()){return t("readonly",e=>{if(e.getAllKeys)return hr(e.getAllKeys());const r=[];return zp(e,n=>r.push(n.key)).then(()=>r)})}const Kp=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Hp=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 Nr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Hp(t)}catch{return t}}function dr(t){return typeof t=="string"?t:Kp(t)||""}const Wp="idb-keyval";var Gp=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=dc(t.dbName,t.storeName)),{name:Wp,options:t,async hasItem(i){return!(typeof await fc(r(i),n)>"u")},async getItem(i){return await fc(r(i),n)??null},setItem(i,s){return Mp(r(i),s,n)},removeItem(i){return jp(r(i),n)},getKeys(){return Vp(n)},clear(){return qp(n)}}};const Yp="WALLET_CONNECT_V2_INDEXED_DB",Zp="keyvaluestorage";class Jp{constructor(){this.indexedDb=kp({driver:Gp({dbName:Yp,storeName:Zp})})}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,dr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Es=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},di={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 Es<"u"&&Es.localStorage?di.exports=Es.localStorage:typeof window<"u"&&window.localStorage?di.exports=window.localStorage:di.exports=new e})();function Xp(t){var e;return[t[0],Nr((e=t[1])!=null?e:"")]}class Qp{constructor(){this.localStorage=di.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Xp)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return Nr(r)}async setItem(e,r){this.localStorage.setItem(e,dr(r))}async removeItem(e){this.localStorage.removeItem(e)}}const eg="wc_storage_version",pc=1,tg=async(t,e,r)=>{const n=eg,i=await e.getItem(n);if(i&&i>=pc){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,pc),r(e),rg(t,o)},rg=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class ng{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new Qp;this.storage=e;try{const r=new Jp;tg(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 ig(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var sg=og;function og(t,e,r){var n=r&&r.stringify||ig,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,d=t&&t.length||0,p=0;p<d;){if(t.charCodeAt(p)===37&&p+1<d){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 f=typeof e[l];if(f==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(f==="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<d&&(u+=t.slice(h)),u)}const gc=sg;var Pt=wt;const wn=yg().console||{},ag={mapHttpRequest:pi,mapHttpResponse:pi,wrapRequestSerializer:Ss,wrapResponseSerializer:Ss,wrapErrorSerializer:Ss,req:pi,res:pi,err:dg};function cg(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function wt(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||wn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=cg(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=mn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:d});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:fg(t)};c.levels=wt.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=mn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=_s());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function d(f){if(f!=="silent"&&!this.levels.values[f])throw Error("unknown level "+f);this._level=f,Br(u,c,"error","log"),Br(u,c,"fatal","error"),Br(u,c,"warn","error"),Br(u,c,"info","log"),Br(u,c,"debug","log"),Br(u,c,"trace","log")}function p(f,y){if(!f)throw new Error("missing bindings for child Pino");y=y||{},i&&f.serializers&&(y.serializers=f.serializers);const g=y.serializers;if(i&&g){var w=Object.assign({},n,g),m=t.browser.serialize===!0?Object.keys(w):i;delete f.serializers,fi([f],m,w,this._stdErrSerialize)}function b(E){this._childLevel=(E._childLevel|0)+1,this.error=Fr(E,f,"error"),this.fatal=Fr(E,f,"fatal"),this.warn=Fr(E,f,"warn"),this.info=Fr(E,f,"info"),this.debug=Fr(E,f,"debug"),this.trace=Fr(E,f,"trace"),w&&(this.serializers=w,this._serialize=m),e&&(this._logEvent=_s([].concat(E._logEvent.bindings,f)))}return b.prototype=this,new b(this)}return c}wt.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"}},wt.stdSerializers=ag,wt.stdTimeFunctions=Object.assign({},{nullTime:yc,epochTime:wc,unixTime:pg,isoTime:gg});function Br(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?mn:i[r]?i[r]:wn[r]||wn[n]||mn,ug(t,e,r)}function ug(t,e,r){!t.transmit&&e[r]===mn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===wn?wn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&fi(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,lg(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=wt.levels.values[u],h=wt.levels.values[r];if(h<l)return;hg(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:wt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function lg(t,e,r,n){t._serialize&&fi(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=wt.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?gc(i.shift(),i):void 0}else typeof s=="string"&&(s=gc(i.shift(),i));return s!==void 0&&(o.msg=s),o}function fi(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=wt.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 Fr(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 hg(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;fi(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=_s(c)}function _s(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function dg(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 fg(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?yc:wc}function pi(){return{}}function Ss(t){return t}function mn(){}function yc(){return!1}function wc(){return Date.now()}function pg(){return Math.round(Date.now()/1e3)}function gg(){return new Date(Date.now()).toISOString()}function yg(){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 wg={level:"info"},bn="custom_context",xs=1e3*1024;class mg{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 mc{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new mg(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 bc{constructor(e,r=xs){this.level=e??"error",this.levelValue=Pt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new mc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Pt.levels.values.error?console.error(e):r===Pt.levels.values.warn?console.warn(e):r===Pt.levels.values.debug?console.debug(e):r===Pt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(dr({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 mc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(dr({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class bg{constructor(e,r=xs){this.baseChunkLogger=new bc(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 vg{constructor(e,r=xs){this.baseChunkLogger=new bc(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 Eg=Object.defineProperty,_g=Object.defineProperties,Sg=Object.getOwnPropertyDescriptors,vc=Object.getOwnPropertySymbols,xg=Object.prototype.hasOwnProperty,Ig=Object.prototype.propertyIsEnumerable,Ec=(t,e,r)=>e in t?Eg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gi=(t,e)=>{for(var r in e||(e={}))xg.call(e,r)&&Ec(t,r,e[r]);if(vc)for(var r of vc(e))Ig.call(e,r)&&Ec(t,r,e[r]);return t},yi=(t,e)=>_g(t,Sg(e));function Is(t){return yi(gi({},t),{level:t?.level||wg.level})}function Dg(t,e=bn){return t[e]||""}function Og(t,e,r=bn){return t[r]=e,t}function He(t,e=bn){let r="";return typeof t.bindings>"u"?r=Dg(t,e):r=t.bindings().context||"",r}function $g(t,e,r=bn){const n=He(t,r);return n.trim()?`${n}/${e}`:e}function je(t,e,r=bn){const n=$g(t,e,r),i=t.child({context:n});return Og(i,n,r)}function Ag(t){var e,r;const n=new bg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Pt(yi(gi({},t.opts),{level:"trace",browser:yi(gi({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function Pg(t){var e;const r=new vg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Pt(yi(gi({},t.opts),{level:"trace"})),chunkLoggerController:r}}function Tg(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Ag(t):Pg(t)}var Rg=Object.defineProperty,Cg=(t,e,r)=>e in t?Rg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_c=(t,e,r)=>Cg(t,typeof e!="symbol"?e+"":e,r);class Ng extends lr{constructor(e){super(),this.opts=e,_c(this,"protocol","wc"),_c(this,"version",2)}}var Bg=Object.defineProperty,Fg=(t,e,r)=>e in t?Bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lg=(t,e,r)=>Fg(t,typeof e!="symbol"?e+"":e,r);class Ug extends lr{constructor(e,r){super(),this.core=e,this.logger=r,Lg(this,"records",new Map)}}class kg{constructor(e,r){this.logger=e,this.core=r}}class Mg extends lr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class jg extends lr{constructor(e){super()}}class qg{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}}class zg extends lr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class Vg extends lr{constructor(e,r){super(),this.core=e,this.logger=r}}class Kg{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}}class Hg{constructor(e,r){this.projectId=e,this.logger=r}}class Wg{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}}var Gg=Object.defineProperty,Yg=(t,e,r)=>e in t?Gg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sc=(t,e,r)=>Yg(t,typeof e!="symbol"?e+"":e,r);class Zg{constructor(e){this.opts=e,Sc(this,"protocol","wc"),Sc(this,"version",2)}}class Jg{constructor(e){this.client=e}}function Xg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xc(t,...e){if(!Xg(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 Ic(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 Qg(t,e){xc(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Lr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ds=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function ey(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Dc(t){return typeof t=="string"&&(t=ey(t)),xc(t),t}class ty{clone(){return this._cloneInto()}}function ry(t){const e=n=>t().update(Dc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Oc(t=32){if(Lr&&typeof Lr.getRandomValues=="function")return Lr.getRandomValues(new Uint8Array(t));if(Lr&&typeof Lr.randomBytes=="function")return Lr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function ny(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 iy extends ty{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=Ds(this.buffer)}update(e){Ic(this);const{view:r,buffer:n,blockLen:i}=this;e=Dc(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=Ds(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){Ic(this),Qg(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;ny(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Ds(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 wi=BigInt(2**32-1),Os=BigInt(32);function $c(t,e=!1){return e?{h:Number(t&wi),l:Number(t>>Os&wi)}:{h:Number(t>>Os&wi)|0,l:Number(t&wi)|0}}function sy(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}=$c(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const oy=(t,e)=>BigInt(t>>>0)<<Os|BigInt(e>>>0),ay=(t,e,r)=>t>>>r,cy=(t,e,r)=>t<<32-r|e>>>r,uy=(t,e,r)=>t>>>r|e<<32-r,ly=(t,e,r)=>t<<32-r|e>>>r,hy=(t,e,r)=>t<<64-r|e>>>r-32,dy=(t,e,r)=>t>>>r-32|e<<64-r,fy=(t,e)=>e,py=(t,e)=>t,gy=(t,e,r)=>t<<r|e>>>32-r,yy=(t,e,r)=>e<<r|t>>>32-r,wy=(t,e,r)=>e<<r-32|t>>>64-r,my=(t,e,r)=>t<<r-32|e>>>64-r;function by(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const vy=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ey=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,_y=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Sy=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,xy=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Iy=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,H={fromBig:$c,split:sy,toBig:oy,shrSH:ay,shrSL:cy,rotrSH:uy,rotrSL:ly,rotrBH:hy,rotrBL:dy,rotr32H:fy,rotr32L:py,rotlSH:gy,rotlSL:yy,rotlBH:wy,rotlBL:my,add:by,add3L:vy,add3H:Ey,add4L:_y,add4H:Sy,add5H:Iy,add5L:xy},[Dy,Oy]=(()=>H.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))))(),Ht=new Uint32Array(80),Wt=new Uint32Array(80);class $y extends iy{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:d,Gh:p,Gl:f,Hh:y,Hl:g}=this;return[e,r,n,i,s,o,a,c,u,l,h,d,p,f,y,g]}set(e,r,n,i,s,o,a,c,u,l,h,d,p,f,y,g){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=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=y|0,this.Hl=g|0}process(e,r){for(let b=0;b<16;b++,r+=4)Ht[b]=e.getUint32(r),Wt[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const E=Ht[b-15]|0,$=Wt[b-15]|0,D=H.rotrSH(E,$,1)^H.rotrSH(E,$,8)^H.shrSH(E,$,7),S=H.rotrSL(E,$,1)^H.rotrSL(E,$,8)^H.shrSL(E,$,7),A=Ht[b-2]|0,x=Wt[b-2]|0,k=H.rotrSH(A,x,19)^H.rotrBH(A,x,61)^H.shrSH(A,x,6),C=H.rotrSL(A,x,19)^H.rotrBL(A,x,61)^H.shrSL(A,x,6),B=H.add4L(S,C,Wt[b-7],Wt[b-16]),j=H.add4H(B,D,k,Ht[b-7],Ht[b-16]);Ht[b]=j|0,Wt[b]=B|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:p,Fl:f,Gh:y,Gl:g,Hh:w,Hl:m}=this;for(let b=0;b<80;b++){const E=H.rotrSH(h,d,14)^H.rotrSH(h,d,18)^H.rotrBH(h,d,41),$=H.rotrSL(h,d,14)^H.rotrSL(h,d,18)^H.rotrBL(h,d,41),D=h&p^~h&y,S=d&f^~d&g,A=H.add5L(m,$,S,Oy[b],Wt[b]),x=H.add5H(A,w,E,D,Dy[b],Ht[b]),k=A|0,C=H.rotrSH(n,i,28)^H.rotrBH(n,i,34)^H.rotrBH(n,i,39),B=H.rotrSL(n,i,28)^H.rotrBL(n,i,34)^H.rotrBL(n,i,39),j=n&s^n&a^s&a,I=i&o^i&c^o&c;w=y|0,m=g|0,y=p|0,g=f|0,p=h|0,f=d|0,{h,l:d}=H.add(u|0,l|0,x|0,k|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const _=H.add3L(k,B,I);n=H.add3H(_,x,C,j),i=_|0}({h:n,l:i}=H.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=H.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=H.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=H.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=H.add(this.Eh|0,this.El|0,h|0,d|0),{h:p,l:f}=H.add(this.Fh|0,this.Fl|0,p|0,f|0),{h:y,l:g}=H.add(this.Gh|0,this.Gl|0,y|0,g|0),{h:w,l:m}=H.add(this.Hh|0,this.Hl|0,w|0,m|0),this.set(n,i,s,o,a,c,u,l,h,d,p,f,y,g,w,m)}roundClean(){Ht.fill(0),Wt.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 Ay=ry(()=>new $y);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $s=BigInt(0),Ac=BigInt(1),Py=BigInt(2);function As(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ps(t){if(!As(t))throw new Error("Uint8Array expected")}function Ts(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Ty=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rs(t){Ps(t);let e="";for(let r=0;r<t.length;r++)e+=Ty[t[r]];return e}function Pc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?$s:BigInt("0x"+t)}const Tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tc(t){if(t>=Tt._0&&t<=Tt._9)return t-Tt._0;if(t>=Tt.A&&t<=Tt.F)return t-(Tt.A-10);if(t>=Tt.a&&t<=Tt.f)return t-(Tt.a-10)}function Rc(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=Tc(t.charCodeAt(s)),a=Tc(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 Ry(t){return Pc(Rs(t))}function mi(t){return Ps(t),Pc(Rs(Uint8Array.from(t).reverse()))}function Cc(t,e){return Rc(t.toString(16).padStart(e*2,"0"))}function Cs(t,e){return Cc(t,e).reverse()}function Rt(t,e,r){let n;if(typeof e=="string")try{n=Rc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(As(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 Nc(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Ps(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 Ns=t=>typeof t=="bigint"&&$s<=t;function Cy(t,e,r){return Ns(t)&&Ns(e)&&Ns(r)&&e<=t&&t<r}function vn(t,e,r,n){if(!Cy(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ny(t){let e;for(e=0;t>$s;t>>=Ac,e+=1);return e}const By=t=>(Py<<BigInt(t-1))-Ac,Fy={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"||As(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 Bs(t,e,r={}){const n=(i,s,o)=>{const a=Fy[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 Bc(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 ve=BigInt(0),he=BigInt(1),fr=BigInt(2),Ly=BigInt(3),Fs=BigInt(4),Fc=BigInt(5),Lc=BigInt(8);function we(t,e){const r=t%e;return r>=ve?r:e+r}function Uy(t,e,r){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(r<=ve)throw new Error("invalid modulus");if(r===he)return ve;let n=he;for(;e>ve;)e&he&&(n=n*t%r),t=t*t%r,e>>=he;return n}function mt(t,e,r){let n=t;for(;e-- >ve;)n*=n,n%=r;return n}function Uc(t,e){if(t===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let r=we(t,e),n=e,i=ve,s=he;for(;r!==ve;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==he)throw new Error("invert: does not exist");return we(i,e)}function ky(t){const e=(t-he)/fr;let r,n,i;for(r=t-he,n=0;r%fr===ve;r/=fr,n++);for(i=fr;i<t&&Uy(i,e,t)!==t-he;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+he)/Fs;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+he)/fr;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 d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,he<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function My(t){if(t%Fs===Ly){const e=(t+he)/Fs;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%Lc===Fc){const e=(t-Fc)/Lc;return function(r,n){const i=r.mul(n,fr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,fr),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 ky(t)}const jy=(t,e)=>(we(t,e)&he)===he,qy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=qy.reduce((n,i)=>(n[i]="function",n),e);return Bs(t,r)}function Vy(t,e,r){if(r<ve)throw new Error("invalid exponent, negatives unsupported");if(r===ve)return t.ONE;if(r===he)return e;let n=t.ONE,i=e;for(;r>ve;)r&he&&(n=t.mul(n,i)),i=t.sqr(i),r>>=he;return n}function Ky(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 kc(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Mc(t,e,r=!1,n={}){if(t<=ve)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=kc(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:By(i),ZERO:ve,ONE:he,create:c=>we(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<t},is0:c=>c===ve,isOdd:c=>(c&he)===he,neg:c=>we(-c,t),eql:(c,u)=>c===u,sqr:c=>we(c*c,t),add:(c,u)=>we(c+u,t),sub:(c,u)=>we(c-u,t),mul:(c,u)=>we(c*u,t),pow:(c,u)=>Vy(a,c,u),div:(c,u)=>we(c*Uc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Uc(c,t),sqrt:n.sqrt||(c=>(o||(o=My(t)),o(a,c))),invertBatch:c=>Ky(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Cs(c,s):Cc(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?mi(c):Ry(c)}});return Object.freeze(a)}const jc=BigInt(0),bi=BigInt(1);function Ls(t,e){const r=e.negate();return t?r:e}function qc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Us(t,e){qc(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Hy(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 Wy(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 ks=new WeakMap,zc=new WeakMap;function Ms(t){return zc.get(t)||1}function Gy(t,e){return{constTimeNegate:Ls,hasPrecomputes(r){return Ms(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>jc;)n&bi&&(i=i.add(s)),s=s.double(),n>>=bi;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Us(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}=Us(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=bi);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(Ls(w,n[y])):a=a.add(Ls(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Us(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===jc)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=bi),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=ks.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&ks.set(n,i(s))),s},wNAFCached(r,n,i){const s=Ms(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Ms(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){qc(n,e),zc.set(r,n),ks.delete(r)}}}function Yy(t,e,r,n){if(Hy(r,t),Wy(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Ny(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Zy(t){return zy(t.Fp),Bs(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...kc(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const ut=BigInt(0),We=BigInt(1),vi=BigInt(2),Jy=BigInt(8),Xy={zip215:!0};function Qy(t){const e=Zy(t);return Bs(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ew(t){const e=Qy(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=vi<<BigInt(a*8)-We,l=r.create,h=Mc(e.n,e.nBitLength),d=e.uvRatio||((_,v)=>{try{return{isValid:!0,value:r.sqrt(_*r.inv(v))}}catch{return{isValid:!1,value:ut}}}),p=e.adjustScalarBytes||(_=>_),f=e.domain||((_,v,O)=>{if(Ts("phflag",O),v.length||O)throw new Error("Contexts/pre-hash are not supported");return _});function y(_,v){vn("coordinate "+_,v,ut,u)}function g(_){if(!(_ instanceof b))throw new Error("ExtendedPoint expected")}const w=Bc((_,v)=>{const{ex:O,ey:T,ez:P}=_,N=_.is0();v==null&&(v=N?Jy:r.inv(P));const F=l(O*v),M=l(T*v),z=l(P*v);if(N)return{x:ut,y:We};if(z!==We)throw new Error("invZ was invalid");return{x:F,y:M}}),m=Bc(_=>{const{a:v,d:O}=e;if(_.is0())throw new Error("bad point: ZERO");const{ex:T,ey:P,ez:N,et:F}=_,M=l(T*T),z=l(P*P),q=l(N*N),V=l(q*q),K=l(M*v),ee=l(q*l(K+z)),G=l(V+l(O*l(M*z)));if(ee!==G)throw new Error("bad point: equation left != right (1)");const W=l(T*P),ye=l(N*F);if(W!==ye)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(v,O,T,P){this.ex=v,this.ey=O,this.ez=T,this.et=P,y("x",v),y("y",O),y("z",T),y("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof b)throw new Error("extended point not allowed");const{x:O,y:T}=v||{};return y("x",O),y("y",T),new b(O,T,We,l(O*T))}static normalizeZ(v){const O=r.invertBatch(v.map(T=>T.ez));return v.map((T,P)=>T.toAffine(O[P])).map(b.fromAffine)}static msm(v,O){return Yy(b,h,v,O)}_setWindowSize(v){D.setWindowSize(this,v)}assertValidity(){m(this)}equals(v){g(v);const{ex:O,ey:T,ez:P}=this,{ex:N,ey:F,ez:M}=v,z=l(O*M),q=l(N*P),V=l(T*M),K=l(F*P);return z===q&&V===K}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:v}=e,{ex:O,ey:T,ez:P}=this,N=l(O*O),F=l(T*T),M=l(vi*l(P*P)),z=l(v*N),q=O+T,V=l(l(q*q)-N-F),K=z+F,ee=K-M,G=z-F,W=l(V*ee),ye=l(K*G),ue=l(V*G),le=l(ee*K);return new b(W,ye,le,ue)}add(v){g(v);const{a:O,d:T}=e,{ex:P,ey:N,ez:F,et:M}=this,{ex:z,ey:q,ez:V,et:K}=v;if(O===BigInt(-1)){const Nf=l((N-P)*(q+z)),Bf=l((N+P)*(q-z)),Ua=l(Bf-Nf);if(Ua===ut)return this.double();const Ff=l(F*vi*K),Lf=l(M*vi*V),Uf=Lf+Ff,kf=Bf+Nf,Mf=Lf-Ff,UD=l(Uf*Ua),kD=l(kf*Mf),MD=l(Uf*Mf),jD=l(Ua*kf);return new b(UD,kD,jD,MD)}const ee=l(P*z),G=l(N*q),W=l(M*T*K),ye=l(F*V),ue=l((P+N)*(z+q)-ee-G),le=ye-W,$e=ye+W,Me=l(G-O*ee),Kt=l(ue*le),BD=l($e*Me),FD=l(ue*Me),LD=l(le*$e);return new b(Kt,BD,LD,FD)}subtract(v){return this.add(v.negate())}wNAF(v){return D.wNAFCached(this,v,b.normalizeZ)}multiply(v){const O=v;vn("scalar",O,We,n);const{p:T,f:P}=this.wNAF(O);return b.normalizeZ([T,P])[0]}multiplyUnsafe(v,O=b.ZERO){const T=v;return vn("scalar",T,ut,n),T===ut?$:this.is0()||T===We?this:D.wNAFCachedUnsafe(this,T,b.normalizeZ,O)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(v){return w(this,v)}clearCofactor(){const{h:v}=e;return v===We?this:this.multiplyUnsafe(v)}static fromHex(v,O=!1){const{d:T,a:P}=e,N=r.BYTES;v=Rt("pointHex",v,N),Ts("zip215",O);const F=v.slice(),M=v[N-1];F[N-1]=M&-129;const z=mi(F),q=O?u:r.ORDER;vn("pointHex.y",z,ut,q);const V=l(z*z),K=l(V-We),ee=l(T*V-P);let{isValid:G,value:W}=d(K,ee);if(!G)throw new Error("Point.fromHex: invalid y coordinate");const ye=(W&We)===We,ue=(M&128)!==0;if(!O&&W===ut&&ue)throw new Error("Point.fromHex: x=0 and x_0=1");return ue!==ye&&(W=l(-W)),b.fromAffine({x:W,y:z})}static fromPrivateKey(v){return x(v).point}toRawBytes(){const{x:v,y:O}=this.toAffine(),T=Cs(O,r.BYTES);return T[T.length-1]|=v&We?128:0,T}toHex(){return Rs(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,We,l(e.Gx*e.Gy)),b.ZERO=new b(ut,We,We,ut);const{BASE:E,ZERO:$}=b,D=Gy(b,a*8);function S(_){return we(_,n)}function A(_){return S(mi(_))}function x(_){const v=r.BYTES;_=Rt("private key",_,v);const O=Rt("hashed private key",s(_),2*v),T=p(O.slice(0,v)),P=O.slice(v,2*v),N=A(T),F=E.multiply(N),M=F.toRawBytes();return{head:T,prefix:P,scalar:N,point:F,pointBytes:M}}function k(_){return x(_).pointBytes}function C(_=new Uint8Array,...v){const O=Nc(...v);return A(s(f(O,Rt("context",_),!!i)))}function B(_,v,O={}){_=Rt("message",_),i&&(_=i(_));const{prefix:T,scalar:P,pointBytes:N}=x(v),F=C(O.context,T,_),M=E.multiply(F).toRawBytes(),z=C(O.context,M,N,_),q=S(F+z*P);vn("signature.s",q,ut,n);const V=Nc(M,Cs(q,r.BYTES));return Rt("result",V,r.BYTES*2)}const j=Xy;function I(_,v,O,T=j){const{context:P,zip215:N}=T,F=r.BYTES;_=Rt("signature",_,2*F),v=Rt("message",v),O=Rt("publicKey",O,F),N!==void 0&&Ts("zip215",N),i&&(v=i(v));const M=mi(_.slice(F,2*F));let z,q,V;try{z=b.fromHex(O,N),q=b.fromHex(_.slice(0,F),N),V=E.multiplyUnsafe(M)}catch{return!1}if(!N&&z.isSmallOrder())return!1;const K=C(P,q.toRawBytes(),z.toRawBytes(),v);return q.add(z.multiplyUnsafe(K)).subtract(V).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:B,verify:I,ExtendedPoint:b,utils:{getExtendedPublicKey:x,randomPrivateKey:()=>o(r.BYTES),precompute(_=8,v=b.BASE){return v._setWindowSize(_),v.multiply(BigInt(3)),v}}}}BigInt(0),BigInt(1);const js=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Vc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const tw=BigInt(1),Kc=BigInt(2);BigInt(3);const rw=BigInt(5),nw=BigInt(8);function iw(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=js,o=t*t%s*t%s,a=mt(o,Kc,s)*o%s,c=mt(a,tw,s)*t%s,u=mt(c,rw,s)*c%s,l=mt(u,e,s)*u%s,h=mt(l,r,s)*l%s,d=mt(h,n,s)*h%s,p=mt(d,i,s)*d%s,f=mt(p,i,s)*d%s,y=mt(f,e,s)*u%s;return{pow_p_5_8:mt(y,Kc,s)*t%s,b2:o}}function sw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ow(t,e){const r=js,n=we(e*e*e,r),i=we(n*n*e,r),s=iw(t*i).pow_p_5_8;let o=we(t*n*s,r);const a=we(e*o*o,r),c=o,u=we(o*Vc,r),l=a===t,h=a===we(-t,r),d=a===we(-t*Vc,r);return l&&(o=c),(h||d)&&(o=u),jy(o,r)&&(o=we(-o,r)),{isValid:l||h,value:o}}const aw=(()=>Mc(js,void 0,!0))(),cw=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:aw,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:nw,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ay,randomBytes:Oc,adjustScalarBytes:sw,uvRatio:ow}))(),Hc=(()=>ew(cw))(),uw="EdDSA",lw="JWT",Ei=".",_i="base64url",Wc="utf8",Gc="utf8",hw=":",dw="did",fw="key",Yc="base58btc",pw="z",gw="K36",yw=32;function qs(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Zc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?qs(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jc(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Zc(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return qs(r)}function ww(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var mw=ww,bw=mw;const Xc=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")},vw=t=>new TextEncoder().encode(t),Ew=t=>new TextDecoder().decode(t);class _w{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 Sw{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 Qc(this,e)}}class xw{constructor(e){this.decoders=e}or(e){return Qc(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 Qc=(t,e)=>new xw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Iw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _w(e,r,n),this.decoder=new Sw(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Si=({name:t,prefix:e,encode:r,decode:n})=>new Iw(t,e,r,n),En=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=bw(r,e);return Si({prefix:t,name:e,encode:n,decode:s=>Xc(i(s))})},Dw=(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},Ow=(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})=>Si({prefix:e,name:t,encode(i){return Ow(i,n,r)},decode(i){return Dw(i,n,r,t)}}),$w=Si({prefix:"\0",name:"identity",encode:t=>Ew(t),decode:t=>vw(t)});var Aw=Object.freeze({__proto__:null,identity:$w});const Pw=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Tw=Object.freeze({__proto__:null,base2:Pw});const Rw=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Cw=Object.freeze({__proto__:null,base8:Rw});const Nw=En({prefix:"9",name:"base10",alphabet:"0123456789"});var Bw=Object.freeze({__proto__:null,base10:Nw});const Fw=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lw=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uw=Object.freeze({__proto__:null,base16:Fw,base16upper:Lw});const kw=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mw=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jw=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qw=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zw=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vw=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kw=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Hw=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ww=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Gw=Object.freeze({__proto__:null,base32:kw,base32upper:Mw,base32pad:jw,base32padupper:qw,base32hex:zw,base32hexupper:Vw,base32hexpad:Kw,base32hexpadupper:Hw,base32z:Ww});const Yw=En({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zw=En({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Jw=Object.freeze({__proto__:null,base36:Yw,base36upper:Zw});const Xw=En({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qw=En({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var em=Object.freeze({__proto__:null,base58btc:Xw,base58flickr:Qw});const tm=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rm=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),im=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var sm=Object.freeze({__proto__:null,base64:tm,base64pad:rm,base64url:nm,base64urlpad:im});const eu=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}"),om=eu.reduce((t,e,r)=>(t[r]=e,t),[]),am=eu.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function cm(t){return t.reduce((e,r)=>(e+=om[r],e),"")}function um(t){const e=[];for(const r of t){const n=am[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lm=Si({prefix:"\u{1F680}",name:"base256emoji",encode:cm,decode:um});var hm=Object.freeze({__proto__:null,base256emoji:lm}),dm=ru,tu=128,fm=127,pm=~fm,gm=Math.pow(2,31);function ru(t,e,r){e=e||[],r=r||0;for(var n=r;t>=gm;)e[r++]=t&255|tu,t/=128;for(;t&pm;)e[r++]=t&255|tu,t>>>=7;return e[r]=t|0,ru.bytes=r-n+1,e}var ym=zs,wm=128,nu=127;function zs(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw zs.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&nu)<<i:(o&nu)*Math.pow(2,i),i+=7}while(o>=wm);return zs.bytes=s-n,r}var mm=Math.pow(2,7),bm=Math.pow(2,14),vm=Math.pow(2,21),Em=Math.pow(2,28),_m=Math.pow(2,35),Sm=Math.pow(2,42),xm=Math.pow(2,49),Im=Math.pow(2,56),Dm=Math.pow(2,63),Om=function(t){return t<mm?1:t<bm?2:t<vm?3:t<Em?4:t<_m?5:t<Sm?6:t<xm?7:t<Im?8:t<Dm?9:10},$m={encode:dm,decode:ym,encodingLength:Om},iu=$m;const su=(t,e,r=0)=>(iu.encode(t,e,r),e),ou=t=>iu.encodingLength(t),Vs=(t,e)=>{const r=e.byteLength,n=ou(t),i=n+ou(r),s=new Uint8Array(i+r);return su(t,s,0),su(r,s,n),s.set(e,i),new Am(t,r,e,s)};class Am{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const au=({name:t,code:e,encode:r})=>new Pm(t,e,r);class Pm{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?Vs(this.code,r):r.then(n=>Vs(this.code,n))}else throw Error("Unknown type, must be binary type")}}const cu=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Tm=au({name:"sha2-256",code:18,encode:cu("SHA-256")}),Rm=au({name:"sha2-512",code:19,encode:cu("SHA-512")});var Cm=Object.freeze({__proto__:null,sha256:Tm,sha512:Rm});const uu=0,Nm="identity",lu=Xc;var Bm=Object.freeze({__proto__:null,identity:{code:uu,name:Nm,encode:lu,digest:t=>Vs(uu,lu(t))}});new TextEncoder,new TextDecoder;const hu={...Aw,...Tw,...Cw,...Bw,...Uw,...Gw,...Jw,...em,...sm,...hm};({...Cm,...Bm});function du(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const fu=du("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ks=du("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=Zc(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),pu={utf8:fu,"utf-8":fu,hex:hu.base16,latin1:Ks,ascii:Ks,binary:Ks,...hu};function xi(t,e="utf8"){const r=pu[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 Ur(t,e="utf8"){const r=pu[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qs(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function gu(t){return Nr(xi(Ur(t,_i),Wc))}function Ii(t){return xi(Ur(dr(t),Wc),_i)}function yu(t){const e=Ur(gw,Yc),r=pw+xi(Jc([e,t]),Yc);return[dw,fw,r].join(hw)}function Fm(t){return xi(t,_i)}function Lm(t){return Ur(t,_i)}function Um(t){return Ur([Ii(t.header),Ii(t.payload)].join(Ei),Gc)}function km(t){return[Ii(t.header),Ii(t.payload),Fm(t.signature)].join(Ei)}function Hs(t){const e=t.split(Ei),r=gu(e[0]),n=gu(e[1]),i=Lm(e[2]),s=Ur(e.slice(0,2).join(Ei),Gc);return{header:r,payload:n,signature:i,data:s}}function wu(t=Oc(yw)){const e=Hc.getPublicKey(t);return{secretKey:Jc([t,e]),publicKey:e}}async function Mm(t,e,r,n,i=L.fromMiliseconds(Date.now())){const s={alg:uw,typ:lw},o=yu(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Um({header:s,payload:c}),l=Hc.sign(u,n.secretKey.slice(0,32));return km({header:s,payload:c,signature:l})}var mu=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))},jm=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),qm=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),zm=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}(),Vm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Km=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Hm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Wm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,bu=3,Gm=[["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",Hm]],vu=[["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 Ym(t){return t?Eu(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Km:typeof navigator<"u"?Eu(navigator.userAgent):Xm()}function Zm(t){return t!==""&&Gm.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 Eu(t){var e=Zm(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Vm;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<bu&&(i=mu(mu([],i,!0),Qm(bu-i.length),!0)):i=[];var s=i.join("."),o=Jm(t),a=Wm.exec(t);return a&&a[1]?new zm(r,s,o,a[1]):new jm(r,s,o)}function Jm(t){for(var e=0,r=vu.length;e<r;e++){var n=vu[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function Xm(){var t=typeof process<"u"&&process.version;return t?new qm(process.version.slice(1)):null}function Qm(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var se={};Object.defineProperty(se,"__esModule",{value:!0}),se.getLocalStorage=se.getLocalStorageOrThrow=se.getCrypto=se.getCryptoOrThrow=_u=se.getLocation=se.getLocationOrThrow=Ws=se.getNavigator=se.getNavigatorOrThrow=_n=se.getDocument=se.getDocumentOrThrow=se.getFromWindowOrThrow=se.getFromWindow=void 0;function pr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}se.getFromWindow=pr;function kr(t){const e=pr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}se.getFromWindowOrThrow=kr;function eb(){return kr("document")}se.getDocumentOrThrow=eb;function tb(){return pr("document")}var _n=se.getDocument=tb;function rb(){return kr("navigator")}se.getNavigatorOrThrow=rb;function nb(){return pr("navigator")}var Ws=se.getNavigator=nb;function ib(){return kr("location")}se.getLocationOrThrow=ib;function sb(){return pr("location")}var _u=se.getLocation=sb;function ob(){return kr("crypto")}se.getCryptoOrThrow=ob;function ab(){return pr("crypto")}se.getCrypto=ab;function cb(){return kr("localStorage")}se.getLocalStorageOrThrow=cb;function ub(){return pr("localStorage")}se.getLocalStorage=ub;var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});var Su=Gs.getWindowMetadata=void 0;const xu=se;function lb(){let t,e;try{t=xu.getDocumentOrThrow(),e=xu.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),d=[];for(let p=0;p<h.length;p++){const f=h[p],y=f.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const g=f.getAttribute("href");if(g)if(g.toLowerCase().indexOf("https:")===-1&&g.toLowerCase().indexOf("http:")===-1&&g.indexOf("//")!==0){let w=e.protocol+"//"+e.host;if(g.indexOf("/")===0)w+=g;else{const m=e.pathname.split("/");m.pop();const b=m.join("/");w+=b+"/"+g}d.push(w)}else if(g.indexOf("//")===0){const w=e.protocol+g;d.push(w)}else d.push(g)}}return d}function n(...h){const d=t.getElementsByTagName("meta");for(let p=0;p<d.length;p++){const f=d[p],y=["itemprop","property","name"].map(g=>f.getAttribute(g)).filter(g=>g?h.includes(g):!1);if(y.length&&y){const g=f.getAttribute("content");if(g)return g}}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}}Su=Gs.getWindowMetadata=lb;function Sn(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Iu(t){return Sn(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Du="2.23.2";let Ys={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Du}`};class gr extends Error{constructor(e,r={}){const n=(()=>r.cause instanceof gr?r.cause.details:r.cause?.message?r.cause.message:r.details)(),i=(()=>r.cause instanceof gr&&r.cause.docsPath||r.docsPath)(),s=Ys.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Ys.version?[`Version: ${Ys.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=Du}walk(e){return Ou(this,e)}}function Ou(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Ou(t.cause,e):e?null:t}class $u extends gr{constructor({size:e,targetSize:r,type:n}){super(`${n.charAt(0).toUpperCase()}${n.slice(1).toLowerCase()} size (${e}) exceeds padding size (${r}).`,{name:"SizeExceedsPaddingSizeError"})}}function Mr(t,{dir:e,size:r=32}={}){return typeof t=="string"?hb(t,{dir:e,size:r}):db(t,{dir:e,size:r})}function hb(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new $u({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function db(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new $u({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 fb extends gr{constructor({max:e,min:r,signed:n,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${n?"signed":"unsigned"} `:""}integer range ${e?`(${r} to ${e})`:`(above ${r})`}`,{name:"IntegerOutOfRangeError"})}}class pb extends gr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function jr(t,{size:e}){if(Iu(t)>e)throw new pb({givenSize:Iu(t),maxSize:e})}function Zs(t,e={}){const{signed:r}=e;e.size&&jr(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 gb(t,e={}){return Number(Zs(t,e))}const yb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Js(t,e={}){return typeof t=="number"||typeof t=="bigint"?Pu(t,e):typeof t=="string"?bb(t,e):typeof t=="boolean"?wb(t,e):Au(t,e)}function wb(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(jr(r,{size:e.size}),Mr(r,{size:e.size})):r}function Au(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=yb[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(jr(n,{size:e.size}),Mr(n,{dir:"right",size:e.size})):n}function Pu(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 fb({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?Mr(a,{size:n}):a}const mb=new TextEncoder;function bb(t,e={}){const r=mb.encode(t);return Au(r,e)}const vb=new TextEncoder;function Eb(t,e={}){return typeof t=="number"||typeof t=="bigint"?Sb(t,e):typeof t=="boolean"?_b(t,e):Sn(t)?Ru(t,e):Cu(t,e)}function _b(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(jr(r,{size:e.size}),Mr(r,{size:e.size})):r}const Ct={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(t){if(t>=Ct.zero&&t<=Ct.nine)return t-Ct.zero;if(t>=Ct.A&&t<=Ct.F)return t-(Ct.A-10);if(t>=Ct.a&&t<=Ct.f)return t-(Ct.a-10)}function Ru(t,e={}){let r=t;e.size&&(jr(r,{size:e.size}),r=Mr(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=Tu(n.charCodeAt(a++)),u=Tu(n.charCodeAt(a++));if(c===void 0||u===void 0)throw new gr(`Invalid byte sequence ("${n[a-2]}${n[a-1]}" in "${n}").`);s[o]=c*16+u}return s}function Sb(t,e){const r=Pu(t,e);return Ru(r)}function Cu(t,e={}){const r=vb.encode(t);return typeof e.size=="number"?(jr(r,{size:e.size}),Mr(r,{dir:"right",size:e.size})):r}function Di(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function xb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xn(t,...e){if(!xb(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 Ib(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Di(t.outputLen),Di(t.blockLen)}function qr(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 Nu(t,e){xn(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Oi=BigInt(2**32-1),Bu=BigInt(32);function Db(t,e=!1){return e?{h:Number(t&Oi),l:Number(t>>Bu&Oi)}:{h:Number(t>>Bu&Oi)|0,l:Number(t&Oi)|0}}function Ob(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}=Db(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const $b=(t,e,r)=>t<<r|e>>>32-r,Ab=(t,e,r)=>e<<r|t>>>32-r,Pb=(t,e,r)=>e<<r-32|t>>>64-r,Tb=(t,e,r)=>t<<r-32|e>>>64-r,zr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Rb(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Xs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function bt(t,e){return t<<32-e|t>>>e}const Fu=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Cb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Lu(t){for(let e=0;e<t.length;e++)t[e]=Cb(t[e])}function Nb(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function $i(t){return typeof t=="string"&&(t=Nb(t)),xn(t),t}function Bb(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];xn(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 Qs{clone(){return this._cloneInto()}}function Uu(t){const e=n=>t().update($i(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ku(t=32){if(zr&&typeof zr.getRandomValues=="function")return zr.getRandomValues(new Uint8Array(t));if(zr&&typeof zr.randomBytes=="function")return zr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Mu=[],ju=[],qu=[],Fb=BigInt(0),In=BigInt(1),Lb=BigInt(2),Ub=BigInt(7),kb=BigInt(256),Mb=BigInt(113);for(let t=0,e=In,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Mu.push(2*(5*n+r)),ju.push((t+1)*(t+2)/2%64);let i=Fb;for(let s=0;s<7;s++)e=(e<<In^(e>>Ub)*Mb)%kb,e&Lb&&(i^=In<<(In<<BigInt(s))-In);qu.push(i)}const[jb,qb]=Ob(qu,!0),zu=(t,e,r)=>r>32?Pb(t,e,r):$b(t,e,r),Vu=(t,e,r)=>r>32?Tb(t,e,r):Ab(t,e,r);function zb(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=zu(u,l,1)^r[a],d=Vu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ju[o],c=zu(i,s,a),u=Vu(i,s,a),l=Mu[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]^=jb[n],t[1]^=qb[n]}r.fill(0)}class eo extends Qs{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Di(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Rb(this.state)}keccak(){Fu||Lu(this.state32),zb(this.state32,this.rounds),Fu||Lu(this.state32),this.posOut=0,this.pos=0}update(e){qr(this);const{blockLen:r,state:n}=this;e=$i(e);const 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){qr(this,!1),xn(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 Di(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nu(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new eo(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 Ku=((t,e,r)=>Uu(()=>new eo(e,t,r)))(1,136,256/8);function Hu(t,e){const r=e||"hex",n=Ku(Sn(t,{strict:!1})?Eb(t):t);return r==="bytes"?n:Js(n)}class Wu 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 to=new Wu(8192);function Vb(t,e){if(to.has(`${t}.${e}`))return to.get(`${t}.${e}`);const r=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),n=Hu(Cu(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 to.set(`${t}.${e}`,s),s}function Kb(t){const e=Hu(`0x${t.substring(4)}`).substring(26);return Vb(`0x${e}`)}async function Hb({hash:t,signature:e}){const r=Sn(t)?t:Js(t),{secp256k1:n}=await Promise.resolve().then(function(){return D1});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,p=Number(d??h),f=Gu(p);return new n.Signature(Zs(u),Zs(l)).addRecoveryBit(f)}const o=Sn(e)?e:Js(e),a=gb(`0x${o.slice(130)}`),c=Gu(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Gu(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 Wb({hash:t,signature:e}){return Kb(await Hb({hash:t,signature:e}))}function Gb(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 Yb(t,e,r){return t&e^~t&r}function Zb(t,e,r){return t&e^t&r^e&r}class Jb extends Qs{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=Xs(this.buffer)}update(e){qr(this);const{view:r,buffer:n,blockLen:i}=this;e=$i(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=Xs(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){qr(this),Nu(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;Gb(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Xs(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 Xb=new Uint32Array([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]),Gt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yt=new Uint32Array(64);class Qb extends Jb{constructor(){super(64,32,8,!1),this.A=Gt[0]|0,this.B=Gt[1]|0,this.C=Gt[2]|0,this.D=Gt[3]|0,this.E=Gt[4]|0,this.F=Gt[5]|0,this.G=Gt[6]|0,this.H=Gt[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)Yt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const d=Yt[h-15],p=Yt[h-2],f=bt(d,7)^bt(d,18)^d>>>3,y=bt(p,17)^bt(p,19)^p>>>10;Yt[h]=y+Yt[h-7]+f+Yt[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 d=bt(a,6)^bt(a,11)^bt(a,25),p=l+d+Yb(a,c,u)+Xb[h]+Yt[h]|0,y=(bt(n,2)^bt(n,13)^bt(n,22))+Zb(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+y|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(){Yt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ai=Uu(()=>new Qb);new Wu(128);const e0=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Yu=new Uint8Array(new Array(16).fill(0).map((t,e)=>e)),t0=Yu.map(t=>(9*t+5)%16);let r0=[Yu],n0=[t0];for(let t=0;t<4;t++)for(let e of[r0,n0])e.push(e[t].map(r=>e0[r]));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pi=BigInt(0),Ti=BigInt(1),i0=BigInt(2);function yr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function vt(t){if(!yr(t))throw new Error("Uint8Array expected")}function Vr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const s0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Kr(t){vt(t);let e="";for(let r=0;r<t.length;r++)e+=s0[t[r]];return e}function Hr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function ro(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Pi:BigInt("0x"+t)}const Nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Zu(t){if(t>=Nt._0&&t<=Nt._9)return t-Nt._0;if(t>=Nt.A&&t<=Nt.F)return t-(Nt.A-10);if(t>=Nt.a&&t<=Nt.f)return t-(Nt.a-10)}function Wr(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=Zu(t.charCodeAt(s)),a=Zu(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 Et(t){return ro(Kr(t))}function no(t){return vt(t),ro(Kr(Uint8Array.from(t).reverse()))}function Zt(t,e){return Wr(t.toString(16).padStart(e*2,"0"))}function io(t,e){return Zt(t,e).reverse()}function o0(t){return Wr(Hr(t))}function Ue(t,e,r){let n;if(typeof e=="string")try{n=Wr(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(yr(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 Xe(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];vt(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 a0(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}function Ri(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const so=t=>typeof t=="bigint"&&Pi<=t;function Gr(t,e,r){return so(t)&&so(e)&&so(r)&&e<=t&&t<r}function Jt(t,e,r,n){if(!Gr(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ju(t){let e;for(e=0;t>Pi;t>>=Ti,e+=1);return e}function c0(t,e){return t>>BigInt(e)&Ti}function u0(t,e,r){return t|(r?Ti:Pi)<<BigInt(e)}const oo=t=>(i0<<BigInt(t-1))-Ti,ao=t=>new Uint8Array(t),Xu=t=>Uint8Array.from(t);function Qu(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=ao(t),i=ao(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...h)=>r(i,n,...h),c=(h=ao())=>{i=a(Xu([0]),h),n=a(),h.length!==0&&(i=a(Xu([1]),h),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const d=[];for(;h<e;){n=a();const p=n.slice();d.push(p),h+=n.length}return Xe(...d)};return(h,d)=>{o(),c(h);let p;for(;!(p=d(u()));)c();return o(),p}}const l0={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"||yr(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 Yr(t,e,r={}){const n=(i,s,o)=>{const a=l0[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}const h0=()=>{throw new Error("not implemented")};function co(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}}var d0=Object.freeze({__proto__:null,isBytes:yr,abytes:vt,abool:Vr,bytesToHex:Kr,numberToHexUnpadded:Hr,hexToNumber:ro,hexToBytes:Wr,bytesToNumberBE:Et,bytesToNumberLE:no,numberToBytesBE:Zt,numberToBytesLE:io,numberToVarBytesBE:o0,ensureBytes:Ue,concatBytes:Xe,equalBytes:a0,utf8ToBytes:Ri,inRange:Gr,aInRange:Jt,bitLen:Ju,bitGet:c0,bitSet:u0,bitMask:oo,createHmacDrbg:Qu,validateObject:Yr,notImplemented:h0,memoized:co});const f0="0.1.1";function p0(){return f0}class qe extends Error{constructor(e,r={}){const n=(()=>{if(r.cause instanceof qe){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause?.message?r.cause.message:r.details})(),i=(()=>r.cause instanceof qe&&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(`
14
+ ***************************************************************************** */var hs=function(t,e){return hs=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])},hs(t,e)};function Jf(t,e){hs(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ds=function(){return ds=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},ds.apply(this,arguments)};function Xf(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 Qf(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 ep(t,e){return function(r,n){e(r,n,t)}}function tp(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function rp(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 np(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 ip(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function sp(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function fs(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 Ja(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 op(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ja(arguments[e]));return t}function ap(){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 gn(t){return this instanceof gn?(this.v=t,this):new gn(t)}function cp(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof gn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function up(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:gn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function lp(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 fs=="function"?fs(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 hp(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function dp(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 fp(t){return t&&t.__esModule?t:{default:t}}function pp(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function gp(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 yp=Object.freeze({__proto__:null,__extends:Jf,get __assign(){return ds},__rest:Xf,__decorate:Qf,__param:ep,__metadata:tp,__awaiter:rp,__generator:np,__createBinding:ip,__exportStar:sp,__values:fs,__read:Ja,__spread:op,__spreadArrays:ap,__await:gn,__asyncGenerator:cp,__asyncDelegator:up,__asyncValues:lp,__makeTemplateObject:hp,__importStar:dp,__importDefault:fp,__classPrivateFieldGet:pp,__classPrivateFieldSet:gp}),ci=ka(yp),ps={},yn={},Xa;function wp(){if(Xa)return yn;Xa=1,Object.defineProperty(yn,"__esModule",{value:!0}),yn.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return yn.delay=t,yn}var cr={},gs={},ur={},Qa;function mp(){return Qa||(Qa=1,Object.defineProperty(ur,"__esModule",{value:!0}),ur.ONE_THOUSAND=ur.ONE_HUNDRED=void 0,ur.ONE_HUNDRED=100,ur.ONE_THOUSAND=1e3),ur}var ys={},ec;function bp(){return ec||(ec=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}(ys)),ys}var tc;function rc(){return tc||(tc=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(mp(),t),e.__exportStar(bp(),t)}(gs)),gs}var nc;function vp(){if(nc)return cr;nc=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.fromMiliseconds=cr.toMiliseconds=void 0;const t=rc();function e(n){return n*t.ONE_THOUSAND}cr.toMiliseconds=e;function r(n){return Math.floor(n/t.ONE_THOUSAND)}return cr.fromMiliseconds=r,cr}var ic;function Ep(){return ic||(ic=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(wp(),t),e.__exportStar(vp(),t)}(ps)),ps}var Nr={},sc;function _p(){if(sc)return Nr;sc=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.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 Nr.Watch=t,Nr.default=t,Nr}var ws={},wn={},oc;function Sp(){if(oc)return wn;oc=1,Object.defineProperty(wn,"__esModule",{value:!0}),wn.IWatch=void 0;class t{}return wn.IWatch=t,wn}var ac;function xp(){return ac||(ac=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ci.__exportStar(Sp(),t)}(ws)),ws}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ci;e.__exportStar(Ep(),t),e.__exportStar(_p(),t),e.__exportStar(xp(),t),e.__exportStar(rc(),t)})(L);class lr{}class Ip extends lr{constructor(e){super()}}const cc=L.FIVE_SECONDS,hr={pulse:"heartbeat_pulse"};class ms extends Ip{constructor(e){super(e),this.events=new Le.exports.EventEmitter,this.interval=cc,this.interval=e?.interval||cc}static async init(e){const r=new ms(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(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(hr.pulse)}}const Dp=/"(?:_|\\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*:/,Op=/"(?: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*:/,$p=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Ap(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Pp(t);return}return e}function Pp(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function ui(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(!$p.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Dp.test(t)||Op.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Ap)}return JSON.parse(t)}catch(n){if(e.strict)throw n;return t}}function Tp(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function be(t,...e){try{return Tp(t(...e))}catch(r){return Promise.reject(r)}}function Rp(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Cp(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function li(t){if(Rp(t))return String(t);if(Cp(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return li(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}function uc(){if(typeof Buffer>"u")throw new TypeError("[unstorage] Buffer is not supported!")}const bs="base64:";function Np(t){if(typeof t=="string")return t;uc();const e=Buffer.from(t).toString("base64");return bs+e}function Bp(t){return typeof t!="string"||!t.startsWith(bs)?t:(uc(),Buffer.from(t.slice(bs.length),"base64"))}function Ke(t){return t?t.split("?")[0].replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""):""}function Fp(...t){return Ke(t.join(":"))}function hi(t){return t=Ke(t),t?t+":":""}function zD(t){return t}const Lp="memory",Up=()=>{const t=new Map;return{name:Lp,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 kp(t={}){const e={mounts:{"":t.driver||Up()},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=Ke(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 lc(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 d=new Map,p=f=>{let y=d.get(f.base);return y||(y={driver:f.driver,base:f.base,items:[]},d.set(f.base,y)),y};for(const f of u){const y=typeof f=="string",g=Ke(y?f:f.key),w=y?void 0:f.value,m=y||!f.options?l:{...l,...f.options},b=r(g);p(b).items.push({key:g,value:w,relativeKey:b.relativeKey,options:m})}return Promise.all([...d.values()].map(f=>h(f))).then(f=>f.flat())},c={hasItem(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return be(d.hasItem,h,l)},getItem(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return be(d.getItem,h,l).then(p=>ui(p))},getItems(u,l){return a(u,l,h=>h.driver.getItems?be(h.driver.getItems,h.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(p=>({key:Fp(h.base,p.key),value:ui(p.value)}))):Promise.all(h.items.map(d=>be(h.driver.getItem,d.relativeKey,d.options).then(p=>({key:d.key,value:ui(p)})))))},getItemRaw(u,l={}){u=Ke(u);const{relativeKey:h,driver:d}=r(u);return d.getItemRaw?be(d.getItemRaw,h,l):be(d.getItem,h,l).then(p=>Bp(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ke(u);const{relativeKey:d,driver:p}=r(u);p.setItem&&(await be(p.setItem,d,li(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return be(h.driver.setItems,h.items.map(d=>({key:d.relativeKey,value:li(d.value),options:d.options})),l);h.driver.setItem&&await Promise.all(h.items.map(d=>be(h.driver.setItem,d.relativeKey,li(d.value),d.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ke(u);const{relativeKey:d,driver:p}=r(u);if(p.setItemRaw)await be(p.setItemRaw,d,l,h);else if(p.setItem)await be(p.setItem,d,Np(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ke(u);const{relativeKey:h,driver:d}=r(u);d.removeItem&&(await be(d.removeItem,h,l),(l.removeMeta||l.removeMata)&&await be(d.removeItem,h+"$",l),d.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ke(u);const{relativeKey:h,driver:d}=r(u),p=Object.create(null);if(d.getMeta&&Object.assign(p,await be(d.getMeta,h,l)),!l.nativeOnly){const f=await be(d.getItem,h+"$",l).then(y=>ui(y));f&&typeof f=="object"&&(typeof f.atime=="string"&&(f.atime=new Date(f.atime)),typeof f.mtime=="string"&&(f.mtime=new Date(f.mtime)),Object.assign(p,f))}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=hi(u);const h=n(u,!0);let d=[];const p=[];for(const f of h){const y=await be(f.driver.getKeys,f.relativeBase,l);for(const g of y){const w=f.mountpoint+Ke(g);d.some(m=>w.startsWith(m))||p.push(w)}d=[f.mountpoint,...d.filter(g=>!g.startsWith(f.mountpoint))]}return u?p.filter(f=>f.startsWith(u)&&f[f.length-1]!=="$"):p.filter(f=>f[f.length-1]!=="$")},async clear(u,l={}){u=hi(u),await Promise.all(n(u,!1).map(async h=>{if(h.driver.clear)return be(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const d=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(d.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>hc(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=hi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,d)=>d.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(lc(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=hi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u](),delete e.unwatch[u]),l&&await hc(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ke(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ke(u),n(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,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 lc(t,e,r){return t.watch?t.watch((n,i)=>e(n,r+i)):()=>{}}async function hc(t){typeof t.dispose=="function"&&await be(t.dispose)}function dr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function dc(t,e){const r=indexedDB.open(t);r.onupgradeneeded=()=>r.result.createObjectStore(e);const n=dr(r);return(i,s)=>n.then(o=>s(o.transaction(e,i).objectStore(e)))}let vs;function mn(){return vs||(vs=dc("keyval-store","keyval")),vs}function fc(t,e=mn()){return e("readonly",r=>dr(r.get(t)))}function Mp(t,e,r=mn()){return r("readwrite",n=>(n.put(e,t),dr(n.transaction)))}function jp(t,e=mn()){return e("readwrite",r=>(r.delete(t),dr(r.transaction)))}function qp(t=mn()){return t("readwrite",e=>(e.clear(),dr(e.transaction)))}function zp(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},dr(t.transaction)}function Vp(t=mn()){return t("readonly",e=>{if(e.getAllKeys)return dr(e.getAllKeys());const r=[];return zp(e,n=>r.push(n.key)).then(()=>r)})}const Kp=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),Hp=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 Br(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Hp(t)}catch{return t}}function fr(t){return typeof t=="string"?t:Kp(t)||""}const Wp="idb-keyval";var Gp=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=i=>e+i;let n;return t.dbName&&t.storeName&&(n=dc(t.dbName,t.storeName)),{name:Wp,options:t,async hasItem(i){return!(typeof await fc(r(i),n)>"u")},async getItem(i){return await fc(r(i),n)??null},setItem(i,s){return Mp(r(i),s,n)},removeItem(i){return jp(r(i),n)},getKeys(){return Vp(n)},clear(){return qp(n)}}};const Yp="WALLET_CONNECT_V2_INDEXED_DB",Zp="keyvaluestorage";class Jp{constructor(){this.indexedDb=kp({driver:Gp({dbName:Yp,storeName:Zp})})}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,fr(r))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Es=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},di={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 Es<"u"&&Es.localStorage?di.exports=Es.localStorage:typeof window<"u"&&window.localStorage?di.exports=window.localStorage:di.exports=new e})();function Xp(t){var e;return[t[0],Br((e=t[1])!=null?e:"")]}class Qp{constructor(){this.localStorage=di.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Xp)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return Br(r)}async setItem(e,r){this.localStorage.setItem(e,fr(r))}async removeItem(e){this.localStorage.removeItem(e)}}const eg="wc_storage_version",pc=1,tg=async(t,e,r)=>{const n=eg,i=await e.getItem(n);if(i&&i>=pc){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,pc),r(e),rg(t,o)},rg=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};class ng{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new Qp;this.storage=e;try{const r=new Jp;tg(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 ig(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var sg=og;function og(t,e,r){var n=r&&r.stringify||ig,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,d=t&&t.length||0,p=0;p<d;){if(t.charCodeAt(p)===37&&p+1<d){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 f=typeof e[l];if(f==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(f==="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<d&&(u+=t.slice(h)),u)}const gc=sg;var Pt=wt;const bn=yg().console||{},ag={mapHttpRequest:pi,mapHttpResponse:pi,wrapRequestSerializer:Ss,wrapResponseSerializer:Ss,wrapErrorSerializer:Ss,req:pi,res:pi,err:dg};function cg(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function wt(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||bn;t.browser.write&&(t.browser.asObject=!0);const n=t.serializers||{},i=cg(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=vn),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:d});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:fg(t)};c.levels=wt.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=vn,c.serializers=n,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=_s());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function d(f){if(f!=="silent"&&!this.levels.values[f])throw Error("unknown level "+f);this._level=f,Fr(u,c,"error","log"),Fr(u,c,"fatal","error"),Fr(u,c,"warn","error"),Fr(u,c,"info","log"),Fr(u,c,"debug","log"),Fr(u,c,"trace","log")}function p(f,y){if(!f)throw new Error("missing bindings for child Pino");y=y||{},i&&f.serializers&&(y.serializers=f.serializers);const g=y.serializers;if(i&&g){var w=Object.assign({},n,g),m=t.browser.serialize===!0?Object.keys(w):i;delete f.serializers,fi([f],m,w,this._stdErrSerialize)}function b(E){this._childLevel=(E._childLevel|0)+1,this.error=Lr(E,f,"error"),this.fatal=Lr(E,f,"fatal"),this.warn=Lr(E,f,"warn"),this.info=Lr(E,f,"info"),this.debug=Lr(E,f,"debug"),this.trace=Lr(E,f,"trace"),w&&(this.serializers=w,this._serialize=m),e&&(this._logEvent=_s([].concat(E._logEvent.bindings,f)))}return b.prototype=this,new b(this)}return c}wt.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"}},wt.stdSerializers=ag,wt.stdTimeFunctions=Object.assign({},{nullTime:yc,epochTime:wc,unixTime:pg,isoTime:gg});function Fr(t,e,r,n){const i=Object.getPrototypeOf(e);e[r]=e.levelVal>e.levels.values[r]?vn:i[r]?i[r]:bn[r]||bn[n]||vn,ug(t,e,r)}function ug(t,e,r){!t.transmit&&e[r]===vn||(e[r]=function(n){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===bn?bn:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&fi(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?n.call(a,lg(this,r,o,s)):n.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=wt.levels.values[u],h=wt.levels.values[r];if(h<l)return;hg(this,{ts:s,methodLevel:r,methodValue:h,transmitLevel:u,transmitValue:wt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[r]))}function lg(t,e,r,n){t._serialize&&fi(r,t._serialize,t.serializers,t._stdErrSerialize);const i=r.slice();let s=i[0];const o={};n&&(o.time=n),o.level=wt.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?gc(i.shift(),i):void 0}else typeof s=="string"&&(s=gc(i.shift(),i));return s!==void 0&&(o.msg=s),o}function fi(t,e,r,n){for(const i in t)if(n&&t[i]instanceof Error)t[i]=wt.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 Lr(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 hg(t,e,r){const n=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;fi(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=_s(c)}function _s(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function dg(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 fg(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?yc:wc}function pi(){return{}}function Ss(t){return t}function vn(){}function yc(){return!1}function wc(){return Date.now()}function pg(){return Math.round(Date.now()/1e3)}function gg(){return new Date(Date.now()).toISOString()}function yg(){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 wg={level:"info"},En="custom_context",xs=1e3*1024;class mg{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 mc{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new mg(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 bc{constructor(e,r=xs){this.level=e??"error",this.levelValue=Pt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new mc(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===Pt.levels.values.error?console.error(e):r===Pt.levels.values.warn?console.warn(e):r===Pt.levels.values.debug?console.debug(e):r===Pt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(fr({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 mc(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(fr({extraMetadata:e})),new Blob(r,{type:"application/json"})}}class bg{constructor(e,r=xs){this.baseChunkLogger=new bc(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 vg{constructor(e,r=xs){this.baseChunkLogger=new bc(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 Eg=Object.defineProperty,_g=Object.defineProperties,Sg=Object.getOwnPropertyDescriptors,vc=Object.getOwnPropertySymbols,xg=Object.prototype.hasOwnProperty,Ig=Object.prototype.propertyIsEnumerable,Ec=(t,e,r)=>e in t?Eg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,gi=(t,e)=>{for(var r in e||(e={}))xg.call(e,r)&&Ec(t,r,e[r]);if(vc)for(var r of vc(e))Ig.call(e,r)&&Ec(t,r,e[r]);return t},yi=(t,e)=>_g(t,Sg(e));function Is(t){return yi(gi({},t),{level:t?.level||wg.level})}function Dg(t,e=En){return t[e]||""}function Og(t,e,r=En){return t[r]=e,t}function He(t,e=En){let r="";return typeof t.bindings>"u"?r=Dg(t,e):r=t.bindings().context||"",r}function $g(t,e,r=En){const n=He(t,r);return n.trim()?`${n}/${e}`:e}function je(t,e,r=En){const n=$g(t,e,r),i=t.child({context:n});return Og(i,n,r)}function Ag(t){var e,r;const n=new bg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Pt(yi(gi({},t.opts),{level:"trace",browser:yi(gi({},(r=t.opts)==null?void 0:r.browser),{write:i=>n.write(i)})})),chunkLoggerController:n}}function Pg(t){var e;const r=new vg((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Pt(yi(gi({},t.opts),{level:"trace"})),chunkLoggerController:r}}function Tg(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Ag(t):Pg(t)}var Rg=Object.defineProperty,Cg=(t,e,r)=>e in t?Rg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_c=(t,e,r)=>Cg(t,typeof e!="symbol"?e+"":e,r);class Ng extends lr{constructor(e){super(),this.opts=e,_c(this,"protocol","wc"),_c(this,"version",2)}}var Bg=Object.defineProperty,Fg=(t,e,r)=>e in t?Bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lg=(t,e,r)=>Fg(t,typeof e!="symbol"?e+"":e,r);class Ug extends lr{constructor(e,r){super(),this.core=e,this.logger=r,Lg(this,"records",new Map)}}class kg{constructor(e,r){this.logger=e,this.core=r}}class Mg extends lr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class jg extends lr{constructor(e){super()}}class qg{constructor(e,r,n,i){this.core=e,this.logger=r,this.name=n}}class zg extends lr{constructor(e,r){super(),this.relayer=e,this.logger=r}}class Vg extends lr{constructor(e,r){super(),this.core=e,this.logger=r}}class Kg{constructor(e,r,n){this.core=e,this.logger=r,this.store=n}}class Hg{constructor(e,r){this.projectId=e,this.logger=r}}class Wg{constructor(e,r,n){this.core=e,this.logger=r,this.telemetryEnabled=n}}var Gg=Object.defineProperty,Yg=(t,e,r)=>e in t?Gg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Sc=(t,e,r)=>Yg(t,typeof e!="symbol"?e+"":e,r);class Zg{constructor(e){this.opts=e,Sc(this,"protocol","wc"),Sc(this,"version",2)}}class Jg{constructor(e){this.client=e}}function Xg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xc(t,...e){if(!Xg(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 Ic(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 Qg(t,e){xc(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Ur=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ds=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function ey(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Dc(t){return typeof t=="string"&&(t=ey(t)),xc(t),t}class ty{clone(){return this._cloneInto()}}function ry(t){const e=n=>t().update(Dc(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Oc(t=32){if(Ur&&typeof Ur.getRandomValues=="function")return Ur.getRandomValues(new Uint8Array(t));if(Ur&&typeof Ur.randomBytes=="function")return Ur.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function ny(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 iy extends ty{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=Ds(this.buffer)}update(e){Ic(this);const{view:r,buffer:n,blockLen:i}=this;e=Dc(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=Ds(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){Ic(this),Qg(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;ny(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Ds(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 wi=BigInt(2**32-1),Os=BigInt(32);function $c(t,e=!1){return e?{h:Number(t&wi),l:Number(t>>Os&wi)}:{h:Number(t>>Os&wi)|0,l:Number(t&wi)|0}}function sy(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}=$c(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const oy=(t,e)=>BigInt(t>>>0)<<Os|BigInt(e>>>0),ay=(t,e,r)=>t>>>r,cy=(t,e,r)=>t<<32-r|e>>>r,uy=(t,e,r)=>t>>>r|e<<32-r,ly=(t,e,r)=>t<<32-r|e>>>r,hy=(t,e,r)=>t<<64-r|e>>>r-32,dy=(t,e,r)=>t>>>r-32|e<<64-r,fy=(t,e)=>e,py=(t,e)=>t,gy=(t,e,r)=>t<<r|e>>>32-r,yy=(t,e,r)=>e<<r|t>>>32-r,wy=(t,e,r)=>e<<r-32|t>>>64-r,my=(t,e,r)=>t<<r-32|e>>>64-r;function by(t,e,r,n){const i=(e>>>0)+(n>>>0);return{h:t+r+(i/2**32|0)|0,l:i|0}}const vy=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Ey=(t,e,r,n)=>e+r+n+(t/2**32|0)|0,_y=(t,e,r,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0),Sy=(t,e,r,n,i)=>e+r+n+i+(t/2**32|0)|0,xy=(t,e,r,n,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Iy=(t,e,r,n,i,s)=>e+r+n+i+s+(t/2**32|0)|0,H={fromBig:$c,split:sy,toBig:oy,shrSH:ay,shrSL:cy,rotrSH:uy,rotrSL:ly,rotrBH:hy,rotrBL:dy,rotr32H:fy,rotr32L:py,rotlSH:gy,rotlSL:yy,rotlBH:wy,rotlBL:my,add:by,add3L:vy,add3H:Ey,add4L:_y,add4H:Sy,add5H:Iy,add5L:xy},[Dy,Oy]=(()=>H.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))))(),Ht=new Uint32Array(80),Wt=new Uint32Array(80);class $y extends iy{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:d,Gh:p,Gl:f,Hh:y,Hl:g}=this;return[e,r,n,i,s,o,a,c,u,l,h,d,p,f,y,g]}set(e,r,n,i,s,o,a,c,u,l,h,d,p,f,y,g){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=d|0,this.Gh=p|0,this.Gl=f|0,this.Hh=y|0,this.Hl=g|0}process(e,r){for(let b=0;b<16;b++,r+=4)Ht[b]=e.getUint32(r),Wt[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const E=Ht[b-15]|0,$=Wt[b-15]|0,D=H.rotrSH(E,$,1)^H.rotrSH(E,$,8)^H.shrSH(E,$,7),S=H.rotrSL(E,$,1)^H.rotrSL(E,$,8)^H.shrSL(E,$,7),A=Ht[b-2]|0,x=Wt[b-2]|0,k=H.rotrSH(A,x,19)^H.rotrBH(A,x,61)^H.shrSH(A,x,6),C=H.rotrSL(A,x,19)^H.rotrBL(A,x,61)^H.shrSL(A,x,6),B=H.add4L(S,C,Wt[b-7],Wt[b-16]),j=H.add4H(B,D,k,Ht[b-7],Ht[b-16]);Ht[b]=j|0,Wt[b]=B|0}let{Ah:n,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:d,Fh:p,Fl:f,Gh:y,Gl:g,Hh:w,Hl:m}=this;for(let b=0;b<80;b++){const E=H.rotrSH(h,d,14)^H.rotrSH(h,d,18)^H.rotrBH(h,d,41),$=H.rotrSL(h,d,14)^H.rotrSL(h,d,18)^H.rotrBL(h,d,41),D=h&p^~h&y,S=d&f^~d&g,A=H.add5L(m,$,S,Oy[b],Wt[b]),x=H.add5H(A,w,E,D,Dy[b],Ht[b]),k=A|0,C=H.rotrSH(n,i,28)^H.rotrBH(n,i,34)^H.rotrBH(n,i,39),B=H.rotrSL(n,i,28)^H.rotrBL(n,i,34)^H.rotrBL(n,i,39),j=n&s^n&a^s&a,I=i&o^i&c^o&c;w=y|0,m=g|0,y=p|0,g=f|0,p=h|0,f=d|0,{h,l:d}=H.add(u|0,l|0,x|0,k|0),u=a|0,l=c|0,a=s|0,c=o|0,s=n|0,o=i|0;const _=H.add3L(k,B,I);n=H.add3H(_,x,C,j),i=_|0}({h:n,l:i}=H.add(this.Ah|0,this.Al|0,n|0,i|0)),{h:s,l:o}=H.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=H.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=H.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:d}=H.add(this.Eh|0,this.El|0,h|0,d|0),{h:p,l:f}=H.add(this.Fh|0,this.Fl|0,p|0,f|0),{h:y,l:g}=H.add(this.Gh|0,this.Gl|0,y|0,g|0),{h:w,l:m}=H.add(this.Hh|0,this.Hl|0,w|0,m|0),this.set(n,i,s,o,a,c,u,l,h,d,p,f,y,g,w,m)}roundClean(){Ht.fill(0),Wt.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 Ay=ry(()=>new $y);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $s=BigInt(0),Ac=BigInt(1),Py=BigInt(2);function As(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ps(t){if(!As(t))throw new Error("Uint8Array expected")}function Ts(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Ty=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rs(t){Ps(t);let e="";for(let r=0;r<t.length;r++)e+=Ty[t[r]];return e}function Pc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?$s:BigInt("0x"+t)}const Tt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Tc(t){if(t>=Tt._0&&t<=Tt._9)return t-Tt._0;if(t>=Tt.A&&t<=Tt.F)return t-(Tt.A-10);if(t>=Tt.a&&t<=Tt.f)return t-(Tt.a-10)}function Rc(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=Tc(t.charCodeAt(s)),a=Tc(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 Ry(t){return Pc(Rs(t))}function mi(t){return Ps(t),Pc(Rs(Uint8Array.from(t).reverse()))}function Cc(t,e){return Rc(t.toString(16).padStart(e*2,"0"))}function Cs(t,e){return Cc(t,e).reverse()}function Rt(t,e,r){let n;if(typeof e=="string")try{n=Rc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(As(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 Nc(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Ps(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 Ns=t=>typeof t=="bigint"&&$s<=t;function Cy(t,e,r){return Ns(t)&&Ns(e)&&Ns(r)&&e<=t&&t<r}function _n(t,e,r,n){if(!Cy(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ny(t){let e;for(e=0;t>$s;t>>=Ac,e+=1);return e}const By=t=>(Py<<BigInt(t-1))-Ac,Fy={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"||As(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 Bs(t,e,r={}){const n=(i,s,o)=>{const a=Fy[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 Bc(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 ve=BigInt(0),he=BigInt(1),pr=BigInt(2),Ly=BigInt(3),Fs=BigInt(4),Fc=BigInt(5),Lc=BigInt(8);function we(t,e){const r=t%e;return r>=ve?r:e+r}function Uy(t,e,r){if(e<ve)throw new Error("invalid exponent, negatives unsupported");if(r<=ve)throw new Error("invalid modulus");if(r===he)return ve;let n=he;for(;e>ve;)e&he&&(n=n*t%r),t=t*t%r,e>>=he;return n}function mt(t,e,r){let n=t;for(;e-- >ve;)n*=n,n%=r;return n}function Uc(t,e){if(t===ve)throw new Error("invert: expected non-zero number");if(e<=ve)throw new Error("invert: expected positive modulus, got "+e);let r=we(t,e),n=e,i=ve,s=he;for(;r!==ve;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==he)throw new Error("invert: does not exist");return we(i,e)}function ky(t){const e=(t-he)/pr;let r,n,i;for(r=t-he,n=0;r%pr===ve;r/=pr,n++);for(i=pr;i<t&&Uy(i,e,t)!==t-he;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+he)/Fs;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+he)/pr;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 d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,he<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function My(t){if(t%Fs===Ly){const e=(t+he)/Fs;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%Lc===Fc){const e=(t-Fc)/Lc;return function(r,n){const i=r.mul(n,pr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,pr),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 ky(t)}const jy=(t,e)=>(we(t,e)&he)===he,qy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=qy.reduce((n,i)=>(n[i]="function",n),e);return Bs(t,r)}function Vy(t,e,r){if(r<ve)throw new Error("invalid exponent, negatives unsupported");if(r===ve)return t.ONE;if(r===he)return e;let n=t.ONE,i=e;for(;r>ve;)r&he&&(n=t.mul(n,i)),i=t.sqr(i),r>>=he;return n}function Ky(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 kc(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Mc(t,e,r=!1,n={}){if(t<=ve)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=kc(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:By(i),ZERO:ve,ONE:he,create:c=>we(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ve<=c&&c<t},is0:c=>c===ve,isOdd:c=>(c&he)===he,neg:c=>we(-c,t),eql:(c,u)=>c===u,sqr:c=>we(c*c,t),add:(c,u)=>we(c+u,t),sub:(c,u)=>we(c-u,t),mul:(c,u)=>we(c*u,t),pow:(c,u)=>Vy(a,c,u),div:(c,u)=>we(c*Uc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Uc(c,t),sqrt:n.sqrt||(c=>(o||(o=My(t)),o(a,c))),invertBatch:c=>Ky(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Cs(c,s):Cc(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?mi(c):Ry(c)}});return Object.freeze(a)}const jc=BigInt(0),bi=BigInt(1);function Ls(t,e){const r=e.negate();return t?r:e}function qc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Us(t,e){qc(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Hy(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 Wy(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 ks=new WeakMap,zc=new WeakMap;function Ms(t){return zc.get(t)||1}function Gy(t,e){return{constTimeNegate:Ls,hasPrecomputes(r){return Ms(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>jc;)n&bi&&(i=i.add(s)),s=s.double(),n>>=bi;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Us(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}=Us(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=bi);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(Ls(w,n[y])):a=a.add(Ls(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Us(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===jc)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=bi),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=ks.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&ks.set(n,i(s))),s},wNAFCached(r,n,i){const s=Ms(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Ms(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){qc(n,e),zc.set(r,n),ks.delete(r)}}}function Yy(t,e,r,n){if(Hy(r,t),Wy(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Ny(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Zy(t){return zy(t.Fp),Bs(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...kc(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const ut=BigInt(0),We=BigInt(1),vi=BigInt(2),Jy=BigInt(8),Xy={zip215:!0};function Qy(t){const e=Zy(t);return Bs(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function ew(t){const e=Qy(t),{Fp:r,n,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=vi<<BigInt(a*8)-We,l=r.create,h=Mc(e.n,e.nBitLength),d=e.uvRatio||((_,v)=>{try{return{isValid:!0,value:r.sqrt(_*r.inv(v))}}catch{return{isValid:!1,value:ut}}}),p=e.adjustScalarBytes||(_=>_),f=e.domain||((_,v,O)=>{if(Ts("phflag",O),v.length||O)throw new Error("Contexts/pre-hash are not supported");return _});function y(_,v){_n("coordinate "+_,v,ut,u)}function g(_){if(!(_ instanceof b))throw new Error("ExtendedPoint expected")}const w=Bc((_,v)=>{const{ex:O,ey:T,ez:P}=_,N=_.is0();v==null&&(v=N?Jy:r.inv(P));const F=l(O*v),M=l(T*v),z=l(P*v);if(N)return{x:ut,y:We};if(z!==We)throw new Error("invZ was invalid");return{x:F,y:M}}),m=Bc(_=>{const{a:v,d:O}=e;if(_.is0())throw new Error("bad point: ZERO");const{ex:T,ey:P,ez:N,et:F}=_,M=l(T*T),z=l(P*P),q=l(N*N),V=l(q*q),K=l(M*v),ee=l(q*l(K+z)),G=l(V+l(O*l(M*z)));if(ee!==G)throw new Error("bad point: equation left != right (1)");const W=l(T*P),ye=l(N*F);if(W!==ye)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(v,O,T,P){this.ex=v,this.ey=O,this.ez=T,this.et=P,y("x",v),y("y",O),y("z",T),y("t",P),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof b)throw new Error("extended point not allowed");const{x:O,y:T}=v||{};return y("x",O),y("y",T),new b(O,T,We,l(O*T))}static normalizeZ(v){const O=r.invertBatch(v.map(T=>T.ez));return v.map((T,P)=>T.toAffine(O[P])).map(b.fromAffine)}static msm(v,O){return Yy(b,h,v,O)}_setWindowSize(v){D.setWindowSize(this,v)}assertValidity(){m(this)}equals(v){g(v);const{ex:O,ey:T,ez:P}=this,{ex:N,ey:F,ez:M}=v,z=l(O*M),q=l(N*P),V=l(T*M),K=l(F*P);return z===q&&V===K}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:v}=e,{ex:O,ey:T,ez:P}=this,N=l(O*O),F=l(T*T),M=l(vi*l(P*P)),z=l(v*N),q=O+T,V=l(l(q*q)-N-F),K=z+F,ee=K-M,G=z-F,W=l(V*ee),ye=l(K*G),ue=l(V*G),le=l(ee*K);return new b(W,ye,le,ue)}add(v){g(v);const{a:O,d:T}=e,{ex:P,ey:N,ez:F,et:M}=this,{ex:z,ey:q,ez:V,et:K}=v;if(O===BigInt(-1)){const Nf=l((N-P)*(q+z)),Bf=l((N+P)*(q-z)),Ua=l(Bf-Nf);if(Ua===ut)return this.double();const Ff=l(F*vi*K),Lf=l(M*vi*V),Uf=Lf+Ff,kf=Bf+Nf,Mf=Lf-Ff,kD=l(Uf*Ua),MD=l(kf*Mf),jD=l(Uf*Mf),qD=l(Ua*kf);return new b(kD,MD,qD,jD)}const ee=l(P*z),G=l(N*q),W=l(M*T*K),ye=l(F*V),ue=l((P+N)*(z+q)-ee-G),le=ye-W,$e=ye+W,Me=l(G-O*ee),Kt=l(ue*le),FD=l($e*Me),LD=l(ue*Me),UD=l(le*$e);return new b(Kt,FD,UD,LD)}subtract(v){return this.add(v.negate())}wNAF(v){return D.wNAFCached(this,v,b.normalizeZ)}multiply(v){const O=v;_n("scalar",O,We,n);const{p:T,f:P}=this.wNAF(O);return b.normalizeZ([T,P])[0]}multiplyUnsafe(v,O=b.ZERO){const T=v;return _n("scalar",T,ut,n),T===ut?$:this.is0()||T===We?this:D.wNAFCachedUnsafe(this,T,b.normalizeZ,O)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return D.unsafeLadder(this,n).is0()}toAffine(v){return w(this,v)}clearCofactor(){const{h:v}=e;return v===We?this:this.multiplyUnsafe(v)}static fromHex(v,O=!1){const{d:T,a:P}=e,N=r.BYTES;v=Rt("pointHex",v,N),Ts("zip215",O);const F=v.slice(),M=v[N-1];F[N-1]=M&-129;const z=mi(F),q=O?u:r.ORDER;_n("pointHex.y",z,ut,q);const V=l(z*z),K=l(V-We),ee=l(T*V-P);let{isValid:G,value:W}=d(K,ee);if(!G)throw new Error("Point.fromHex: invalid y coordinate");const ye=(W&We)===We,ue=(M&128)!==0;if(!O&&W===ut&&ue)throw new Error("Point.fromHex: x=0 and x_0=1");return ue!==ye&&(W=l(-W)),b.fromAffine({x:W,y:z})}static fromPrivateKey(v){return x(v).point}toRawBytes(){const{x:v,y:O}=this.toAffine(),T=Cs(O,r.BYTES);return T[T.length-1]|=v&We?128:0,T}toHex(){return Rs(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,We,l(e.Gx*e.Gy)),b.ZERO=new b(ut,We,We,ut);const{BASE:E,ZERO:$}=b,D=Gy(b,a*8);function S(_){return we(_,n)}function A(_){return S(mi(_))}function x(_){const v=r.BYTES;_=Rt("private key",_,v);const O=Rt("hashed private key",s(_),2*v),T=p(O.slice(0,v)),P=O.slice(v,2*v),N=A(T),F=E.multiply(N),M=F.toRawBytes();return{head:T,prefix:P,scalar:N,point:F,pointBytes:M}}function k(_){return x(_).pointBytes}function C(_=new Uint8Array,...v){const O=Nc(...v);return A(s(f(O,Rt("context",_),!!i)))}function B(_,v,O={}){_=Rt("message",_),i&&(_=i(_));const{prefix:T,scalar:P,pointBytes:N}=x(v),F=C(O.context,T,_),M=E.multiply(F).toRawBytes(),z=C(O.context,M,N,_),q=S(F+z*P);_n("signature.s",q,ut,n);const V=Nc(M,Cs(q,r.BYTES));return Rt("result",V,r.BYTES*2)}const j=Xy;function I(_,v,O,T=j){const{context:P,zip215:N}=T,F=r.BYTES;_=Rt("signature",_,2*F),v=Rt("message",v),O=Rt("publicKey",O,F),N!==void 0&&Ts("zip215",N),i&&(v=i(v));const M=mi(_.slice(F,2*F));let z,q,V;try{z=b.fromHex(O,N),q=b.fromHex(_.slice(0,F),N),V=E.multiplyUnsafe(M)}catch{return!1}if(!N&&z.isSmallOrder())return!1;const K=C(P,q.toRawBytes(),z.toRawBytes(),v);return q.add(z.multiplyUnsafe(K)).subtract(V).clearCofactor().equals(b.ZERO)}return E._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:B,verify:I,ExtendedPoint:b,utils:{getExtendedPublicKey:x,randomPrivateKey:()=>o(r.BYTES),precompute(_=8,v=b.BASE){return v._setWindowSize(_),v.multiply(BigInt(3)),v}}}}BigInt(0),BigInt(1);const js=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Vc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const tw=BigInt(1),Kc=BigInt(2);BigInt(3);const rw=BigInt(5),nw=BigInt(8);function iw(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=js,o=t*t%s*t%s,a=mt(o,Kc,s)*o%s,c=mt(a,tw,s)*t%s,u=mt(c,rw,s)*c%s,l=mt(u,e,s)*u%s,h=mt(l,r,s)*l%s,d=mt(h,n,s)*h%s,p=mt(d,i,s)*d%s,f=mt(p,i,s)*d%s,y=mt(f,e,s)*u%s;return{pow_p_5_8:mt(y,Kc,s)*t%s,b2:o}}function sw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function ow(t,e){const r=js,n=we(e*e*e,r),i=we(n*n*e,r),s=iw(t*i).pow_p_5_8;let o=we(t*n*s,r);const a=we(e*o*o,r),c=o,u=we(o*Vc,r),l=a===t,h=a===we(-t,r),d=a===we(-t*Vc,r);return l&&(o=c),(h||d)&&(o=u),jy(o,r)&&(o=we(-o,r)),{isValid:l||h,value:o}}const aw=(()=>Mc(js,void 0,!0))(),cw=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:aw,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:nw,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Ay,randomBytes:Oc,adjustScalarBytes:sw,uvRatio:ow}))(),Hc=(()=>ew(cw))(),uw="EdDSA",lw="JWT",Ei=".",_i="base64url",Wc="utf8",Gc="utf8",hw=":",dw="did",fw="key",Yc="base58btc",pw="z",gw="K36",yw=32;function qs(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Zc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?qs(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jc(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Zc(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return qs(r)}function ww(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var mw=ww,bw=mw;const Xc=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")},vw=t=>new TextEncoder().encode(t),Ew=t=>new TextDecoder().decode(t);class _w{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 Sw{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 Qc(this,e)}}class xw{constructor(e){this.decoders=e}or(e){return Qc(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 Qc=(t,e)=>new xw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Iw{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new _w(e,r,n),this.decoder=new Sw(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Si=({name:t,prefix:e,encode:r,decode:n})=>new Iw(t,e,r,n),Sn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=bw(r,e);return Si({prefix:t,name:e,encode:n,decode:s=>Xc(i(s))})},Dw=(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},Ow=(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})=>Si({prefix:e,name:t,encode(i){return Ow(i,n,r)},decode(i){return Dw(i,n,r,t)}}),$w=Si({prefix:"\0",name:"identity",encode:t=>Ew(t),decode:t=>vw(t)});var Aw=Object.freeze({__proto__:null,identity:$w});const Pw=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Tw=Object.freeze({__proto__:null,base2:Pw});const Rw=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Cw=Object.freeze({__proto__:null,base8:Rw});const Nw=Sn({prefix:"9",name:"base10",alphabet:"0123456789"});var Bw=Object.freeze({__proto__:null,base10:Nw});const Fw=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Lw=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Uw=Object.freeze({__proto__:null,base16:Fw,base16upper:Lw});const kw=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Mw=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),jw=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),qw=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),zw=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Vw=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Kw=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Hw=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ww=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var Gw=Object.freeze({__proto__:null,base32:kw,base32upper:Mw,base32pad:jw,base32padupper:qw,base32hex:zw,base32hexupper:Vw,base32hexpad:Kw,base32hexpadupper:Hw,base32z:Ww});const Yw=Sn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Zw=Sn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Jw=Object.freeze({__proto__:null,base36:Yw,base36upper:Zw});const Xw=Sn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Qw=Sn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var em=Object.freeze({__proto__:null,base58btc:Xw,base58flickr:Qw});const tm=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),rm=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nm=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),im=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var sm=Object.freeze({__proto__:null,base64:tm,base64pad:rm,base64url:nm,base64urlpad:im});const eu=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}"),om=eu.reduce((t,e,r)=>(t[r]=e,t),[]),am=eu.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function cm(t){return t.reduce((e,r)=>(e+=om[r],e),"")}function um(t){const e=[];for(const r of t){const n=am[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const lm=Si({prefix:"\u{1F680}",name:"base256emoji",encode:cm,decode:um});var hm=Object.freeze({__proto__:null,base256emoji:lm}),dm=ru,tu=128,fm=127,pm=~fm,gm=Math.pow(2,31);function ru(t,e,r){e=e||[],r=r||0;for(var n=r;t>=gm;)e[r++]=t&255|tu,t/=128;for(;t&pm;)e[r++]=t&255|tu,t>>>=7;return e[r]=t|0,ru.bytes=r-n+1,e}var ym=zs,wm=128,nu=127;function zs(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw zs.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&nu)<<i:(o&nu)*Math.pow(2,i),i+=7}while(o>=wm);return zs.bytes=s-n,r}var mm=Math.pow(2,7),bm=Math.pow(2,14),vm=Math.pow(2,21),Em=Math.pow(2,28),_m=Math.pow(2,35),Sm=Math.pow(2,42),xm=Math.pow(2,49),Im=Math.pow(2,56),Dm=Math.pow(2,63),Om=function(t){return t<mm?1:t<bm?2:t<vm?3:t<Em?4:t<_m?5:t<Sm?6:t<xm?7:t<Im?8:t<Dm?9:10},$m={encode:dm,decode:ym,encodingLength:Om},iu=$m;const su=(t,e,r=0)=>(iu.encode(t,e,r),e),ou=t=>iu.encodingLength(t),Vs=(t,e)=>{const r=e.byteLength,n=ou(t),i=n+ou(r),s=new Uint8Array(i+r);return su(t,s,0),su(r,s,n),s.set(e,i),new Am(t,r,e,s)};class Am{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const au=({name:t,code:e,encode:r})=>new Pm(t,e,r);class Pm{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?Vs(this.code,r):r.then(n=>Vs(this.code,n))}else throw Error("Unknown type, must be binary type")}}const cu=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Tm=au({name:"sha2-256",code:18,encode:cu("SHA-256")}),Rm=au({name:"sha2-512",code:19,encode:cu("SHA-512")});var Cm=Object.freeze({__proto__:null,sha256:Tm,sha512:Rm});const uu=0,Nm="identity",lu=Xc;var Bm=Object.freeze({__proto__:null,identity:{code:uu,name:Nm,encode:lu,digest:t=>Vs(uu,lu(t))}});new TextEncoder,new TextDecoder;const hu={...Aw,...Tw,...Cw,...Bw,...Uw,...Gw,...Jw,...em,...sm,...hm};({...Cm,...Bm});function du(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const fu=du("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ks=du("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=Zc(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),pu={utf8:fu,"utf-8":fu,hex:hu.base16,latin1:Ks,ascii:Ks,binary:Ks,...hu};function xi(t,e="utf8"){const r=pu[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 kr(t,e="utf8"){const r=pu[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qs(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function gu(t){return Br(xi(kr(t,_i),Wc))}function Ii(t){return xi(kr(fr(t),Wc),_i)}function yu(t){const e=kr(gw,Yc),r=pw+xi(Jc([e,t]),Yc);return[dw,fw,r].join(hw)}function Fm(t){return xi(t,_i)}function Lm(t){return kr(t,_i)}function Um(t){return kr([Ii(t.header),Ii(t.payload)].join(Ei),Gc)}function km(t){return[Ii(t.header),Ii(t.payload),Fm(t.signature)].join(Ei)}function Hs(t){const e=t.split(Ei),r=gu(e[0]),n=gu(e[1]),i=Lm(e[2]),s=kr(e.slice(0,2).join(Ei),Gc);return{header:r,payload:n,signature:i,data:s}}function wu(t=Oc(yw)){const e=Hc.getPublicKey(t);return{secretKey:Jc([t,e]),publicKey:e}}async function Mm(t,e,r,n,i=L.fromMiliseconds(Date.now())){const s={alg:uw,typ:lw},o=yu(n.publicKey),a=i+r,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Um({header:s,payload:c}),l=Hc.sign(u,n.secretKey.slice(0,32));return km({header:s,payload:c,signature:l})}var mu=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))},jm=function(){function t(e,r,n){this.name=e,this.version=r,this.os=n,this.type="browser"}return t}(),qm=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),zm=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}(),Vm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Km=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Hm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Wm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,bu=3,Gm=[["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",Hm]],vu=[["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 Ym(t){return t?Eu(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Km:typeof navigator<"u"?Eu(navigator.userAgent):Xm()}function Zm(t){return t!==""&&Gm.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 Eu(t){var e=Zm(t);if(!e)return null;var r=e[0],n=e[1];if(r==="searchbot")return new Vm;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<bu&&(i=mu(mu([],i,!0),Qm(bu-i.length),!0)):i=[];var s=i.join("."),o=Jm(t),a=Wm.exec(t);return a&&a[1]?new zm(r,s,o,a[1]):new jm(r,s,o)}function Jm(t){for(var e=0,r=vu.length;e<r;e++){var n=vu[e],i=n[0],s=n[1],o=s.exec(t);if(o)return i}return null}function Xm(){var t=typeof process<"u"&&process.version;return t?new qm(process.version.slice(1)):null}function Qm(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var se={};Object.defineProperty(se,"__esModule",{value:!0}),se.getLocalStorage=se.getLocalStorageOrThrow=se.getCrypto=se.getCryptoOrThrow=_u=se.getLocation=se.getLocationOrThrow=Ws=se.getNavigator=se.getNavigatorOrThrow=yr=se.getDocument=se.getDocumentOrThrow=se.getFromWindowOrThrow=se.getFromWindow=void 0;function gr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}se.getFromWindow=gr;function Mr(t){const e=gr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}se.getFromWindowOrThrow=Mr;function eb(){return Mr("document")}se.getDocumentOrThrow=eb;function tb(){return gr("document")}var yr=se.getDocument=tb;function rb(){return Mr("navigator")}se.getNavigatorOrThrow=rb;function nb(){return gr("navigator")}var Ws=se.getNavigator=nb;function ib(){return Mr("location")}se.getLocationOrThrow=ib;function sb(){return gr("location")}var _u=se.getLocation=sb;function ob(){return Mr("crypto")}se.getCryptoOrThrow=ob;function ab(){return gr("crypto")}se.getCrypto=ab;function cb(){return Mr("localStorage")}se.getLocalStorageOrThrow=cb;function ub(){return gr("localStorage")}se.getLocalStorage=ub;var Gs={};Object.defineProperty(Gs,"__esModule",{value:!0});var Su=Gs.getWindowMetadata=void 0;const xu=se;function lb(){let t,e;try{t=xu.getDocumentOrThrow(),e=xu.getLocationOrThrow()}catch{return null}function r(){const h=t.getElementsByTagName("link"),d=[];for(let p=0;p<h.length;p++){const f=h[p],y=f.getAttribute("rel");if(y&&y.toLowerCase().indexOf("icon")>-1){const g=f.getAttribute("href");if(g)if(g.toLowerCase().indexOf("https:")===-1&&g.toLowerCase().indexOf("http:")===-1&&g.indexOf("//")!==0){let w=e.protocol+"//"+e.host;if(g.indexOf("/")===0)w+=g;else{const m=e.pathname.split("/");m.pop();const b=m.join("/");w+=b+"/"+g}d.push(w)}else if(g.indexOf("//")===0){const w=e.protocol+g;d.push(w)}else d.push(g)}}return d}function n(...h){const d=t.getElementsByTagName("meta");for(let p=0;p<d.length;p++){const f=d[p],y=["itemprop","property","name"].map(g=>f.getAttribute(g)).filter(g=>g?h.includes(g):!1);if(y.length&&y){const g=f.getAttribute("content");if(g)return g}}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}}Su=Gs.getWindowMetadata=lb;function xn(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function Iu(t){return xn(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const Du="2.23.2";let Ys={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:r})=>e?`${t??"https://viem.sh"}${e}${r?`#${r}`:""}`:void 0,version:`viem@${Du}`};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=Ys.getDocsUrl?.({...r,docsPath:i}),o=[e||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...n?[`Details: ${n}`]:[],...Ys.version?[`Version: ${Ys.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=Du}walk(e){return Ou(this,e)}}function Ou(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?Ou(t.cause,e):e?null:t}class $u 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 jr(t,{dir:e,size:r=32}={}){return typeof t=="string"?hb(t,{dir:e,size:r}):db(t,{dir:e,size:r})}function hb(t,{dir:e,size:r=32}={}){if(r===null)return t;const n=t.replace("0x","");if(n.length>r*2)throw new $u({size:Math.ceil(n.length/2),targetSize:r,type:"hex"});return`0x${n[e==="right"?"padEnd":"padStart"](r*2,"0")}`}function db(t,{dir:e,size:r=32}={}){if(r===null)return t;if(t.length>r)throw new $u({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 fb 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 pb extends wr{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed ${r} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function qr(t,{size:e}){if(Iu(t)>e)throw new pb({givenSize:Iu(t),maxSize:e})}function Zs(t,e={}){const{signed:r}=e;e.size&&qr(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 gb(t,e={}){return Number(Zs(t,e))}const yb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Js(t,e={}){return typeof t=="number"||typeof t=="bigint"?Pu(t,e):typeof t=="string"?bb(t,e):typeof t=="boolean"?wb(t,e):Au(t,e)}function wb(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(qr(r,{size:e.size}),jr(r,{size:e.size})):r}function Au(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=yb[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(qr(n,{size:e.size}),jr(n,{dir:"right",size:e.size})):n}function Pu(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 fb({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?jr(a,{size:n}):a}const mb=new TextEncoder;function bb(t,e={}){const r=mb.encode(t);return Au(r,e)}const vb=new TextEncoder;function Eb(t,e={}){return typeof t=="number"||typeof t=="bigint"?Sb(t,e):typeof t=="boolean"?_b(t,e):xn(t)?Ru(t,e):Cu(t,e)}function _b(t,e={}){const r=new Uint8Array(1);return r[0]=Number(t),typeof e.size=="number"?(qr(r,{size:e.size}),jr(r,{size:e.size})):r}const Ct={zero:48,nine:57,A:65,F:70,a:97,f:102};function Tu(t){if(t>=Ct.zero&&t<=Ct.nine)return t-Ct.zero;if(t>=Ct.A&&t<=Ct.F)return t-(Ct.A-10);if(t>=Ct.a&&t<=Ct.f)return t-(Ct.a-10)}function Ru(t,e={}){let r=t;e.size&&(qr(r,{size:e.size}),r=jr(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=Tu(n.charCodeAt(a++)),u=Tu(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 Sb(t,e){const r=Pu(t,e);return Ru(r)}function Cu(t,e={}){const r=vb.encode(t);return typeof e.size=="number"?(qr(r,{size:e.size}),jr(r,{dir:"right",size:e.size})):r}function Di(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function xb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function In(t,...e){if(!xb(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 Ib(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Di(t.outputLen),Di(t.blockLen)}function zr(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 Nu(t,e){In(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const Oi=BigInt(2**32-1),Bu=BigInt(32);function Db(t,e=!1){return e?{h:Number(t&Oi),l:Number(t>>Bu&Oi)}:{h:Number(t>>Bu&Oi)|0,l:Number(t&Oi)|0}}function Ob(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}=Db(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const $b=(t,e,r)=>t<<r|e>>>32-r,Ab=(t,e,r)=>e<<r|t>>>32-r,Pb=(t,e,r)=>e<<r-32|t>>>64-r,Tb=(t,e,r)=>t<<r-32|e>>>64-r,Vr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Rb(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Xs(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function bt(t,e){return t<<32-e|t>>>e}const Fu=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Cb(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Lu(t){for(let e=0;e<t.length;e++)t[e]=Cb(t[e])}function Nb(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function $i(t){return typeof t=="string"&&(t=Nb(t)),In(t),t}function Bb(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];In(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 Qs{clone(){return this._cloneInto()}}function Uu(t){const e=n=>t().update($i(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function ku(t=32){if(Vr&&typeof Vr.getRandomValues=="function")return Vr.getRandomValues(new Uint8Array(t));if(Vr&&typeof Vr.randomBytes=="function")return Vr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const Mu=[],ju=[],qu=[],Fb=BigInt(0),Dn=BigInt(1),Lb=BigInt(2),Ub=BigInt(7),kb=BigInt(256),Mb=BigInt(113);for(let t=0,e=Dn,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],Mu.push(2*(5*n+r)),ju.push((t+1)*(t+2)/2%64);let i=Fb;for(let s=0;s<7;s++)e=(e<<Dn^(e>>Ub)*Mb)%kb,e&Lb&&(i^=Dn<<(Dn<<BigInt(s))-Dn);qu.push(i)}const[jb,qb]=Ob(qu,!0),zu=(t,e,r)=>r>32?Pb(t,e,r):$b(t,e,r),Vu=(t,e,r)=>r>32?Tb(t,e,r):Ab(t,e,r);function zb(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=zu(u,l,1)^r[a],d=Vu(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ju[o],c=zu(i,s,a),u=Vu(i,s,a),l=Mu[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]^=jb[n],t[1]^=qb[n]}r.fill(0)}class eo extends Qs{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Di(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=Rb(this.state)}keccak(){Fu||Lu(this.state32),zb(this.state32,this.rounds),Fu||Lu(this.state32),this.posOut=0,this.pos=0}update(e){zr(this);const{blockLen:r,state:n}=this;e=$i(e);const 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){zr(this,!1),In(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 Di(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Nu(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new eo(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 Ku=((t,e,r)=>Uu(()=>new eo(e,t,r)))(1,136,256/8);function Hu(t,e){const r=e||"hex",n=Ku(xn(t,{strict:!1})?Eb(t):t);return r==="bytes"?n:Js(n)}class Wu 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 to=new Wu(8192);function Vb(t,e){if(to.has(`${t}.${e}`))return to.get(`${t}.${e}`);const r=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),n=Hu(Cu(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 to.set(`${t}.${e}`,s),s}function Kb(t){const e=Hu(`0x${t.substring(4)}`).substring(26);return Vb(`0x${e}`)}async function Hb({hash:t,signature:e}){const r=xn(t)?t:Js(t),{secp256k1:n}=await Promise.resolve().then(function(){return D1});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:d}=e,p=Number(d??h),f=Gu(p);return new n.Signature(Zs(u),Zs(l)).addRecoveryBit(f)}const o=xn(e)?e:Js(e),a=gb(`0x${o.slice(130)}`),c=Gu(a);return n.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(r.substring(2)).toHex(!1)}`}function Gu(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 Wb({hash:t,signature:e}){return Kb(await Hb({hash:t,signature:e}))}function Gb(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 Yb(t,e,r){return t&e^~t&r}function Zb(t,e,r){return t&e^t&r^e&r}class Jb extends Qs{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=Xs(this.buffer)}update(e){zr(this);const{view:r,buffer:n,blockLen:i}=this;e=$i(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=Xs(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){zr(this),Nu(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;Gb(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Xs(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 Xb=new Uint32Array([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]),Gt=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Yt=new Uint32Array(64);class Qb extends Jb{constructor(){super(64,32,8,!1),this.A=Gt[0]|0,this.B=Gt[1]|0,this.C=Gt[2]|0,this.D=Gt[3]|0,this.E=Gt[4]|0,this.F=Gt[5]|0,this.G=Gt[6]|0,this.H=Gt[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)Yt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const d=Yt[h-15],p=Yt[h-2],f=bt(d,7)^bt(d,18)^d>>>3,y=bt(p,17)^bt(p,19)^p>>>10;Yt[h]=y+Yt[h-7]+f+Yt[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 d=bt(a,6)^bt(a,11)^bt(a,25),p=l+d+Yb(a,c,u)+Xb[h]+Yt[h]|0,y=(bt(n,2)^bt(n,13)^bt(n,22))+Zb(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+y|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(){Yt.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const Ai=Uu(()=>new Qb);new Wu(128);const e0=new Uint8Array([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),Yu=new Uint8Array(new Array(16).fill(0).map((t,e)=>e)),t0=Yu.map(t=>(9*t+5)%16);let r0=[Yu],n0=[t0];for(let t=0;t<4;t++)for(let e of[r0,n0])e.push(e[t].map(r=>e0[r]));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Pi=BigInt(0),Ti=BigInt(1),i0=BigInt(2);function mr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function vt(t){if(!mr(t))throw new Error("Uint8Array expected")}function Kr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const s0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Hr(t){vt(t);let e="";for(let r=0;r<t.length;r++)e+=s0[t[r]];return e}function Wr(t){const e=t.toString(16);return e.length&1?"0"+e:e}function ro(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Pi:BigInt("0x"+t)}const Nt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Zu(t){if(t>=Nt._0&&t<=Nt._9)return t-Nt._0;if(t>=Nt.A&&t<=Nt.F)return t-(Nt.A-10);if(t>=Nt.a&&t<=Nt.f)return t-(Nt.a-10)}function Gr(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=Zu(t.charCodeAt(s)),a=Zu(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 Et(t){return ro(Hr(t))}function no(t){return vt(t),ro(Hr(Uint8Array.from(t).reverse()))}function Zt(t,e){return Gr(t.toString(16).padStart(e*2,"0"))}function io(t,e){return Zt(t,e).reverse()}function o0(t){return Gr(Wr(t))}function Ue(t,e,r){let n;if(typeof e=="string")try{n=Gr(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(mr(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 Xe(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];vt(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 a0(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}function Ri(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const so=t=>typeof t=="bigint"&&Pi<=t;function Yr(t,e,r){return so(t)&&so(e)&&so(r)&&e<=t&&t<r}function Jt(t,e,r,n){if(!Yr(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Ju(t){let e;for(e=0;t>Pi;t>>=Ti,e+=1);return e}function c0(t,e){return t>>BigInt(e)&Ti}function u0(t,e,r){return t|(r?Ti:Pi)<<BigInt(e)}const oo=t=>(i0<<BigInt(t-1))-Ti,ao=t=>new Uint8Array(t),Xu=t=>Uint8Array.from(t);function Qu(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=ao(t),i=ao(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...h)=>r(i,n,...h),c=(h=ao())=>{i=a(Xu([0]),h),n=a(),h.length!==0&&(i=a(Xu([1]),h),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const d=[];for(;h<e;){n=a();const p=n.slice();d.push(p),h+=n.length}return Xe(...d)};return(h,d)=>{o(),c(h);let p;for(;!(p=d(u()));)c();return o(),p}}const l0={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"||mr(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 Zr(t,e,r={}){const n=(i,s,o)=>{const a=l0[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}const h0=()=>{throw new Error("not implemented")};function co(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}}var d0=Object.freeze({__proto__:null,isBytes:mr,abytes:vt,abool:Kr,bytesToHex:Hr,numberToHexUnpadded:Wr,hexToNumber:ro,hexToBytes:Gr,bytesToNumberBE:Et,bytesToNumberLE:no,numberToBytesBE:Zt,numberToBytesLE:io,numberToVarBytesBE:o0,ensureBytes:Ue,concatBytes:Xe,equalBytes:a0,utf8ToBytes:Ri,inRange:Yr,aInRange:Jt,bitLen:Ju,bitGet:c0,bitSet:u0,bitMask:oo,createHmacDrbg:Qu,validateObject:Zr,notImplemented:h0,memoized:co});const f0="0.1.1";function p0(){return f0}class qe extends Error{constructor(e,r={}){const n=(()=>{if(r.cause instanceof qe){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause?.message?r.cause.message:r.details})(),i=(()=>r.cause instanceof qe&&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
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@${p0()}`}),this.cause=r.cause,this.details=n,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return el(this,e)}}function el(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?el(t.cause,e):e?null:t}function g0(t,e){if(nl(t)>e)throw new S0({givenSize:nl(t),maxSize:e})}const Bt={zero:48,nine:57,A:65,F:70,a:97,f:102};function tl(t){if(t>=Bt.zero&&t<=Bt.nine)return t-Bt.zero;if(t>=Bt.A&&t<=Bt.F)return t-(Bt.A-10);if(t>=Bt.a&&t<=Bt.f)return t-(Bt.a-10)}function y0(t,e={}){const{dir:r,size:n=32}=e;if(n===0)return t;if(t.length>n)throw new x0({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 uo(t,e){if(ho(t)>e)throw new T0({givenSize:ho(t),maxSize:e})}function rl(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 R0({size:Math.ceil(i.length/2),targetSize:n,type:"Hex"});return`0x${i[r==="right"?"padEnd":"padStart"](n*2,"0")}`}const w0=new TextEncoder;function m0(t){return t instanceof Uint8Array?t:typeof t=="string"?v0(t):b0(t)}function b0(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function v0(t,e={}){const{size:r}=e;let n=t;r&&(uo(t,r),n=lo(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=tl(i.charCodeAt(c++)),l=tl(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new qe(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function E0(t,e={}){const{size:r}=e,n=w0.encode(t);return typeof r=="number"?(g0(n,r),_0(n,r)):n}function _0(t,e){return y0(t,{dir:"right",size:e})}function nl(t){return t.length}class S0 extends qe{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 x0 extends qe{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 I0=new TextEncoder,D0=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function il(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function O0(t,e={}){const r=`0x${Number(t)}`;return typeof e.size=="number"?(uo(r,e.size),Ci(r,e.size)):r}function sl(t,e={}){let r="";for(let i=0;i<t.length;i++)r+=D0[t[i]];const n=`0x${r}`;return typeof e.size=="number"?(uo(n,e.size),lo(n,e.size)):n}function $0(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 P0({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?Ci(c,n):c}function A0(t,e={}){return sl(I0.encode(t),e)}function Ci(t,e){return rl(t,{dir:"left",size:e})}function lo(t,e){return rl(t,{dir:"right",size:e})}function ho(t){return Math.ceil((t.length-2)/2)}class P0 extends qe{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 T0 extends qe{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 R0 extends qe{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"})}}function C0(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,n=Ku(m0(t));return r==="Bytes"?n:sl(n)}class N0 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 fo={checksum:new N0(8192)}.checksum,B0=/^0x[a-fA-F0-9]{40}$/;function ol(t,e={}){const{strict:r=!0}=e;if(!B0.test(t))throw new al({address:t,cause:new L0});if(r){if(t.toLowerCase()===t)return;if(F0(t)!==t)throw new al({address:t,cause:new U0})}}function F0(t){if(fo.has(t))return fo.get(t);ol(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=C0(E0(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 fo.set(t,i),i}class al extends qe{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 L0 extends qe{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 U0 extends qe{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const k0=/^(.*)\[([0-9]*)\]$/,M0=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,j0=/^(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 po(t,e){if(t.length!==e.length)throw new z0({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(po.encode(i,s))}return il(...r)}(function(t){function e(r,n,i=!1){if(r==="address"){const c=n;return ol(c),Ci(c.toLowerCase(),i?32:0)}if(r==="string")return A0(n);if(r==="bytes")return n;if(r==="bool")return Ci(O0(n),i?32:1);const s=r.match(j0);if(s){const[c,u,l="256"]=s,h=Number.parseInt(l)/8;return $0(n,{size:i?32:h,signed:u==="int"})}const o=r.match(M0);if(o){const[c,u]=o;if(Number.parseInt(u)!==(n.length-2)/2)throw new q0({expectedSize:Number.parseInt(u),value:n});return lo(n,i?32:0)}const a=r.match(k0);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":il(...l)}throw new V0(r)}t.encode=e})(po||(po={}));class q0 extends qe{constructor({expectedSize:e,value:r}){super(`Size of bytes "${r}" (bytes${ho(r)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class z0 extends qe{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 V0 extends qe{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 cl extends Qs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Ib(e);const n=$i(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),s.fill(0)}update(e){return qr(this),this.iHash.update(e),this}digestInto(e){qr(this),xn(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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ul=(t,e,r)=>new cl(t,e).update(r).digest();ul.create=(t,e)=>new cl(t,e);const Ee=BigInt(0),de=BigInt(1),wr=BigInt(2),K0=BigInt(3),go=BigInt(4),ll=BigInt(5),hl=BigInt(8);function _e(t,e){const r=t%e;return r>=Ee?r:e+r}function H0(t,e,r){if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(r<=Ee)throw new Error("invalid modulus");if(r===de)return Ee;let n=de;for(;e>Ee;)e&de&&(n=n*t%r),t=t*t%r,e>>=de;return n}function it(t,e,r){let n=t;for(;e-- >Ee;)n*=n,n%=r;return n}function yo(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let r=_e(t,e),n=e,i=Ee,s=de;for(;r!==Ee;){const a=n/r,c=n%r,u=i-s*a;n=r,r=c,i=s,s=u}if(n!==de)throw new Error("invert: does not exist");return _e(i,e)}function W0(t){const e=(t-de)/wr;let r,n,i;for(r=t-de,n=0;r%wr===Ee;r/=wr,n++);for(i=wr;i<t&&H0(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)/go;return function(c,u){const l=c.pow(u,o);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}const s=(r+de)/wr;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,i),r),h=a.pow(c,s),d=a.pow(c,r);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let p=1;for(let y=a.sqr(d);p<u&&!a.eql(y,a.ONE);p++)y=a.sqr(y);const f=a.pow(l,de<<BigInt(u-p-1));l=a.sqr(f),h=a.mul(h,f),d=a.mul(d,l),u=p}return h}}function G0(t){if(t%go===K0){const e=(t+de)/go;return function(n,i){const s=n.pow(i,e);if(!n.eql(n.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%hl===ll){const e=(t-ll)/hl;return function(n,i){const s=n.mul(i,wr),o=n.pow(s,e),a=n.mul(i,o),c=n.mul(n.mul(a,wr),o),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return W0(t)}const Y0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function dl(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Y0.reduce((n,i)=>(n[i]="function",n),e);return Yr(t,r)}function Z0(t,e,r){if(r<Ee)throw new Error("invalid exponent, negatives unsupported");if(r===Ee)return t.ONE;if(r===de)return e;let n=t.ONE,i=e;for(;r>Ee;)r&de&&(n=t.mul(n,i)),i=t.sqr(i),r>>=de;return n}function J0(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 fl(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pl(t,e,r=!1,n={}){if(t<=Ee)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=fl(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:oo(i),ZERO:Ee,ONE:de,create:c=>_e(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ee<=c&&c<t},is0:c=>c===Ee,isOdd:c=>(c&de)===de,neg:c=>_e(-c,t),eql:(c,u)=>c===u,sqr:c=>_e(c*c,t),add:(c,u)=>_e(c+u,t),sub:(c,u)=>_e(c-u,t),mul:(c,u)=>_e(c*u,t),pow:(c,u)=>Z0(a,c,u),div:(c,u)=>_e(c*yo(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>yo(c,t),sqrt:n.sqrt||(c=>(o||(o=G0(t)),o(a,c))),invertBatch:c=>J0(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?io(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?no(c):Et(c)}});return Object.freeze(a)}function gl(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 yl(t){const e=gl(t);return e+Math.ceil(e/2)}function X0(t,e,r=!1){const n=t.length,i=gl(e),s=yl(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?no(t):Et(t),a=_e(o,e-de)+de;return r?io(a,i):Zt(a,i)}const wl=BigInt(0),Ni=BigInt(1);function wo(t,e){const r=e.negate();return t?r:e}function ml(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function mo(t,e){ml(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Q0(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 e1(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 bo=new WeakMap,bl=new WeakMap;function vo(t){return bl.get(t)||1}function t1(t,e){return{constTimeNegate:wo,hasPrecomputes(r){return vo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>wl;)n&Ni&&(i=i.add(s)),s=s.double(),n>>=Ni;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=mo(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}=mo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=Ni);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(wo(w,n[y])):a=a.add(wo(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=mo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===wl)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=Ni),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=bo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&bo.set(n,i(s))),s},wNAFCached(r,n,i){const s=vo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=vo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){ml(n,e),bl.set(r,n),bo.delete(r)}}}function r1(t,e,r,n){if(Q0(r,t),e1(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Ju(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function vl(t){return dl(t.Fp),Yr(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...fl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function El(t){t.lowS!==void 0&&Vr("lowS",t.lowS),t.prehash!==void 0&&Vr("prehash",t.prehash)}function n1(t){const e=vl(t);Yr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:i1,hexToBytes:s1}=d0;class o1 extends Error{constructor(e=""){super(e)}}const Ft={Err:o1,_tlv:{encode:(t,e)=>{const{Err:r}=Ft;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=Hr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Hr(i.length/2|128):"";return Hr(t)+s+i+e},decode(t,e){const{Err:r}=Ft;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}=Ft;if(t<lt)throw new e("integer: negative integers are not allowed");let r=Hr(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}=Ft;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 i1(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=Ft,i=typeof t=="string"?s1(t):t;vt(i);const{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}=Ft,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},lt=BigInt(0),re=BigInt(1),Xt=BigInt(2),Bi=BigInt(3),_l=BigInt(4);function a1(t){const e=n1(t),{Fp:r}=e,n=pl(e.n,e.nBitLength),i=e.toBytes||((y,g,w)=>{const m=g.toAffine();return Xe(Uint8Array.from([4]),r.toBytes(m.x),r.toBytes(m.y))}),s=e.fromBytes||(y=>{const g=y.subarray(1),w=r.fromBytes(g.subarray(0,r.BYTES)),m=r.fromBytes(g.subarray(r.BYTES,2*r.BYTES));return{x:w,y:m}});function o(y){const{a:g,b:w}=e,m=r.sqr(y),b=r.mul(m,y);return r.add(r.add(b,r.mul(y,g)),w)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Gr(y,re,e.n)}function c(y){const{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:m,n:b}=e;if(g&&typeof y!="bigint"){if(yr(y)&&(y=Kr(y)),typeof y!="string"||!g.includes(y.length))throw new Error("invalid private key");y=y.padStart(w*2,"0")}let E;try{E=typeof y=="bigint"?y:Et(Ue("private key",y,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof y)}return m&&(E=_e(E,b)),Jt("private key",E,re,b),E}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=co((y,g)=>{const{px:w,py:m,pz:b}=y;if(r.eql(b,r.ONE))return{x:w,y:m};const E=y.is0();g==null&&(g=E?r.ONE:r.inv(b));const $=r.mul(w,g),D=r.mul(m,g),S=r.mul(b,g);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),h=co(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:g,y:w}=y.toAffine();if(!r.isValid(g)||!r.isValid(w))throw new Error("bad point: x or y not FE");const m=r.sqr(w),b=o(g);if(!r.eql(m,b))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,w,m){if(this.px=g,this.py=w,this.pz=m,g==null||!r.isValid(g))throw new Error("x required");if(w==null||!r.isValid(w))throw new Error("y required");if(m==null||!r.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(g){const{x:w,y:m}=g||{};if(!g||!r.isValid(w)||!r.isValid(m))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");const b=E=>r.eql(E,r.ZERO);return b(w)&&b(m)?d.ZERO:new d(w,m,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){const w=r.invertBatch(g.map(m=>m.pz));return g.map((m,b)=>m.toAffine(w[b])).map(d.fromAffine)}static fromHex(g){const w=d.fromAffine(s(Ue("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return r1(d,n,g,w)}_setWindowSize(g){f.setWindowSize(this,g)}assertValidity(){h(this)}hasEvenY(){const{y:g}=this.toAffine();if(r.isOdd)return!r.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g,S=r.eql(r.mul(w,D),r.mul(E,b)),A=r.eql(r.mul(m,D),r.mul($,b));return S&&A}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:g,b:w}=e,m=r.mul(w,Bi),{px:b,py:E,pz:$}=this;let D=r.ZERO,S=r.ZERO,A=r.ZERO,x=r.mul(b,b),k=r.mul(E,E),C=r.mul($,$),B=r.mul(b,E);return B=r.add(B,B),A=r.mul(b,$),A=r.add(A,A),D=r.mul(g,A),S=r.mul(m,C),S=r.add(D,S),D=r.sub(k,S),S=r.add(k,S),S=r.mul(D,S),D=r.mul(B,D),A=r.mul(m,A),C=r.mul(g,C),B=r.sub(x,C),B=r.mul(g,B),B=r.add(B,A),A=r.add(x,x),x=r.add(A,x),x=r.add(x,C),x=r.mul(x,B),S=r.add(S,x),C=r.mul(E,$),C=r.add(C,C),x=r.mul(C,B),D=r.sub(D,x),A=r.mul(C,k),A=r.add(A,A),A=r.add(A,A),new d(D,S,A)}add(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g;let S=r.ZERO,A=r.ZERO,x=r.ZERO;const k=e.a,C=r.mul(e.b,Bi);let B=r.mul(w,E),j=r.mul(m,$),I=r.mul(b,D),_=r.add(w,m),v=r.add(E,$);_=r.mul(_,v),v=r.add(B,j),_=r.sub(_,v),v=r.add(w,b);let O=r.add(E,D);return v=r.mul(v,O),O=r.add(B,I),v=r.sub(v,O),O=r.add(m,b),S=r.add($,D),O=r.mul(O,S),S=r.add(j,I),O=r.sub(O,S),x=r.mul(k,v),S=r.mul(C,I),x=r.add(S,x),S=r.sub(j,x),x=r.add(j,x),A=r.mul(S,x),j=r.add(B,B),j=r.add(j,B),I=r.mul(k,I),v=r.mul(C,v),j=r.add(j,I),I=r.sub(B,I),I=r.mul(k,I),v=r.add(v,I),B=r.mul(j,v),A=r.add(A,B),B=r.mul(O,v),S=r.mul(_,S),S=r.sub(S,B),B=r.mul(_,j),x=r.mul(O,x),x=r.add(x,B),new d(S,A,x)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return f.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){const{endo:w,n:m}=e;Jt("scalar",g,lt,m);const b=d.ZERO;if(g===lt)return b;if(this.is0()||g===re)return this;if(!w||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:E,k1:$,k2neg:D,k2:S}=w.splitScalar(g),A=b,x=b,k=this;for(;$>lt||S>lt;)$&re&&(A=A.add(k)),S&re&&(x=x.add(k)),k=k.double(),$>>=re,S>>=re;return E&&(A=A.negate()),D&&(x=x.negate()),x=new d(r.mul(x.px,w.beta),x.py,x.pz),A.add(x)}multiply(g){const{endo:w,n:m}=e;Jt("scalar",g,re,m);let b,E;if(w){const{k1neg:$,k1:D,k2neg:S,k2:A}=w.splitScalar(g);let{p:x,f:k}=this.wNAF(D),{p:C,f:B}=this.wNAF(A);x=f.constTimeNegate($,x),C=f.constTimeNegate(S,C),C=new d(r.mul(C.px,w.beta),C.py,C.pz),b=x.add(C),E=k.add(B)}else{const{p:$,f:D}=this.wNAF(g);b=$,E=D}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(g,w,m){const b=d.BASE,E=(D,S)=>S===lt||S===re||!D.equals(b)?D.multiplyUnsafe(S):D.multiply(S),$=E(this,w).add(E(g,m));return $.is0()?void 0:$}toAffine(g){return l(this,g)}isTorsionFree(){const{h:g,isTorsionFree:w}=e;if(g===re)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:g,clearCofactor:w}=e;return g===re?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return Vr("isCompressed",g),this.assertValidity(),i(d,this,g)}toHex(g=!0){return Vr("isCompressed",g),Kr(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const p=e.nBitLength,f=t1(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function c1(t){const e=vl(t);return Yr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function u1(t){const e=c1(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(I){return _e(I,n)}function a(I){return yo(I,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=a1({...e,toBytes(I,_,v){const O=_.toAffine(),T=r.toBytes(O.x),P=Xe;return Vr("isCompressed",v),v?P(Uint8Array.from([_.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,r.toBytes(O.y))},fromBytes(I){const _=I.length,v=I[0],O=I.subarray(1);if(_===i&&(v===2||v===3)){const T=Et(O);if(!Gr(T,re,r.ORDER))throw new Error("Point is not on curve");const P=l(T);let N;try{N=r.sqrt(P)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const F=(N&re)===re;return(v&1)===1!==F&&(N=r.neg(N)),{x:T,y:N}}else if(_===s&&v===4){const T=r.fromBytes(O.subarray(0,r.BYTES)),P=r.fromBytes(O.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}}else{const T=i,P=s;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+P+", got "+_)}}}),d=I=>Kr(Zt(I,e.nByteLength));function p(I){const _=n>>re;return I>_}function f(I){return p(I)?o(-I):I}const y=(I,_,v)=>Et(I.slice(_,v));class g{constructor(_,v,O){this.r=_,this.s=v,this.recovery=O,this.assertValidity()}static fromCompact(_){const v=e.nByteLength;return _=Ue("compactSignature",_,v*2),new g(y(_,0,v),y(_,v,2*v))}static fromDER(_){const{r:v,s:O}=Ft.toSig(Ue("DER",_));return new g(v,O)}assertValidity(){Jt("r",this.r,re,n),Jt("s",this.s,re,n)}addRecoveryBit(_){return new g(this.r,this.s,_)}recoverPublicKey(_){const{r:v,s:O,recovery:T}=this,P=D(Ue("msgHash",_));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const N=T===2||T===3?v+e.n:v;if(N>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const F=T&1?"03":"02",M=c.fromHex(F+d(N)),z=a(N),q=o(-P*z),V=o(O*z),K=c.BASE.multiplyAndAddUnsafe(M,q,V);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Wr(this.toDERHex())}toDERHex(){return Ft.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Wr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const I=yl(e.n);return X0(e.randomBytes(I),e.n)},precompute(I=8,_=c.BASE){return _._setWindowSize(I),_.multiply(BigInt(3)),_}};function m(I,_=!0){return c.fromPrivateKey(I).toRawBytes(_)}function b(I){const _=yr(I),v=typeof I=="string",O=(_||v)&&I.length;return _?O===i||O===s:v?O===2*i||O===2*s:I instanceof c}function E(I,_,v=!0){if(b(I))throw new Error("first arg must be private key");if(!b(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(u(I)).toRawBytes(v)}const $=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const _=Et(I),v=I.length*8-e.nBitLength;return v>0?_>>BigInt(v):_},D=e.bits2int_modN||function(I){return o($(I))},S=oo(e.nBitLength);function A(I){return Jt("num < 2^"+e.nBitLength,I,lt,S),Zt(I,e.nByteLength)}function x(I,_,v=k){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:T}=e;let{lowS:P,prehash:N,extraEntropy:F}=v;P==null&&(P=!0),I=Ue("msgHash",I),El(v),N&&(I=Ue("prehashed msgHash",O(I)));const M=D(I),z=u(_),q=[A(z),A(M)];if(F!=null&&F!==!1){const G=F===!0?T(r.BYTES):F;q.push(Ue("extraEntropy",G))}const V=Xe(...q),K=M;function ee(G){const W=$(G);if(!h(W))return;const ye=a(W),ue=c.BASE.multiply(W).toAffine(),le=o(ue.x);if(le===lt)return;const $e=o(ye*o(K+le*z));if($e===lt)return;let Me=(ue.x===le?0:2)|Number(ue.y&re),Kt=$e;return P&&p($e)&&(Kt=f($e),Me^=1),new g(le,Kt,Me)}return{seed:V,k2sig:ee}}const k={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function B(I,_,v=k){const{seed:O,k2sig:T}=x(I,_,v),P=e;return Qu(P.hash.outputLen,P.nByteLength,P.hmac)(O,T)}c.BASE._setWindowSize(8);function j(I,_,v,O=C){const T=I;_=Ue("msgHash",_),v=Ue("publicKey",v);const{lowS:P,prehash:N,format:F}=O;if(El(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const M=typeof T=="string"||yr(T),z=!M&&!F&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!M&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,V;try{if(z&&(q=new g(T.r,T.s)),M){try{F!=="compact"&&(q=g.fromDER(T))}catch(Me){if(!(Me instanceof Ft.Err))throw Me}!q&&F!=="der"&&(q=g.fromCompact(T))}V=c.fromHex(v)}catch{return!1}if(!q||P&&q.hasHighS())return!1;N&&(_=e.hash(_));const{r:K,s:ee}=q,G=D(_),W=a(ee),ye=o(G*W),ue=o(K*W),le=c.BASE.multiplyAndAddUnsafe(V,ye,ue)?.toAffine();return le?o(le.x)===K:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:E,sign:B,verify:j,ProjectivePoint:c,Signature:g,utils:w}}function l1(t,e){const r=t.ORDER;let n=lt;for(let f=r-re;f%Xt===lt;f/=Xt)n+=re;const i=n,s=Xt<<i-re-re,o=s*Xt,a=(r-re)/o,c=(a-re)/Xt,u=o-re,l=s,h=t.pow(e,a),d=t.pow(e,(a+re)/Xt);let p=(f,y)=>{let g=h,w=t.pow(y,u),m=t.sqr(w);m=t.mul(m,y);let b=t.mul(f,m);b=t.pow(b,c),b=t.mul(b,w),w=t.mul(b,y),m=t.mul(b,f);let E=t.mul(m,w);b=t.pow(E,l);let $=t.eql(b,t.ONE);w=t.mul(m,d),b=t.mul(E,g),m=t.cmov(w,m,$),E=t.cmov(b,E,$);for(let D=i;D>re;D--){let S=D-Xt;S=Xt<<S-re;let A=t.pow(E,S);const x=t.eql(A,t.ONE);w=t.mul(m,g),g=t.mul(g,g),A=t.mul(E,g),m=t.cmov(w,m,x),E=t.cmov(A,E,x)}return{isValid:$,value:m}};if(t.ORDER%_l===Bi){const f=(t.ORDER-Bi)/_l,y=t.sqrt(t.neg(e));p=(g,w)=>{let m=t.sqr(w);const b=t.mul(g,w);m=t.mul(m,b);let E=t.pow(m,f);E=t.mul(E,b);const $=t.mul(E,y),D=t.mul(t.sqr(E),w),S=t.eql(D,g);let A=t.cmov($,E,S);return{isValid:S,value:A}}}return p}function h1(t,e){if(dl(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const r=l1(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:d,value:p}=r(s,u);h=t.mul(i,n),h=t.mul(h,p),l=t.cmov(l,o,d),h=t.cmov(h,p,d);const f=t.isOdd(n)===t.isOdd(h);return h=t.cmov(t.neg(h),h,f),l=t.div(l,a),{x:l,y:h}}}function d1(t){return{hash:t,hmac:(e,...r)=>ul(t,e,Bb(...r)),randomBytes:ku}}function f1(t,e){const r=n=>u1({...t,...d1(n)});return{...r(e),create:r}}const p1=Et;function Qt(t,e){if(Dn(t),Dn(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 g1(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 Dn(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function y1(t,e,r,n){vt(t),vt(e),Dn(r),e.length>255&&(e=n(Xe(Ri("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=Xe(e,Qt(e.length,1)),c=Qt(0,s),u=Qt(r,2),l=new Array(o),h=n(Xe(c,t,u,Qt(0,1),a));l[0]=n(Xe(h,Qt(1,1),a));for(let p=1;p<=o;p++){const f=[g1(h,l[p-1]),Qt(p+1,1),a];l[p]=n(Xe(...f))}return Xe(...l).slice(0,r)}function w1(t,e,r,n,i){if(vt(t),vt(e),Dn(r),e.length>255){const s=Math.ceil(2*n/8);e=i.create({dkLen:s}).update(Ri("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(Qt(r,2)).update(e).update(Qt(e.length,1)).digest()}function Sl(t,e,r){Yr(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;vt(t),Dn(e);const u=typeof c=="string"?Ri(c):c,l=n.toString(2).length,h=Math.ceil((l+i)/8),d=e*s*h;let p;if(a==="xmd")p=y1(t,u,d,o);else if(a==="xof")p=w1(t,u,d,i,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const f=new Array(e);for(let y=0;y<e;y++){const g=new Array(s);for(let w=0;w<s;w++){const m=h*(w+y*s),b=p.subarray(m,m+h);g[w]=_e(p1(b),n)}f[y]=g}return f}function m1(t,e){const r=e.map(n=>Array.from(n).reverse());return(n,i)=>{const[s,o,a,c]=r.map(u=>u.reduce((l,h)=>t.add(t.mul(l,n),h)));return n=t.div(s,o),i=t.mul(i,t.div(a,c)),{x:n,y:i}}}function b1(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(n,i){const s=Sl(n,2,{...r,DST:r.DST,...i}),o=t.fromAffine(e(s[0])),a=t.fromAffine(e(s[1])),c=o.add(a).clearCofactor();return c.assertValidity(),c},encodeToCurve(n,i){const s=Sl(n,1,{...r,DST:r.encodeDST,...i}),o=t.fromAffine(e(s[0])).clearCofactor();return o.assertValidity(),o},mapToCurve(n){if(!Array.isArray(n))throw new Error("mapToCurve: expected array of bigints");for(const s of n)if(typeof s!="bigint")throw new Error("mapToCurve: expected array of bigints");const i=t.fromAffine(e(n)).clearCofactor();return i.assertValidity(),i}}}const On=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fi=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),$n=BigInt(1),Li=BigInt(2),xl=(t,e)=>(t+e/Li)/e;function Il(t){const e=On,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=it(l,r,e)*l%e,d=it(h,r,e)*l%e,p=it(d,Li,e)*u%e,f=it(p,i,e)*p%e,y=it(f,s,e)*f%e,g=it(y,a,e)*y%e,w=it(g,c,e)*g%e,m=it(w,a,e)*y%e,b=it(m,r,e)*l%e,E=it(b,o,e)*f%e,$=it(E,n,e)*u%e,D=it($,Li,e);if(!er.eql(er.sqr(D),t))throw new Error("Cannot find square root");return D}const er=pl(On,void 0,void 0,{sqrt:Il}),An=f1({a:BigInt(0),b:BigInt(7),Fp:er,n:Fi,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Fi,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-$n*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=xl(s*t,e),c=xl(-n*t,e);let u=_e(t-a*r-c*i,e),l=_e(-a*n-c*s,e);const h=u>o,d=l>o;if(h&&(u=e-u),d&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:d,k2:l}}}},Ai),Dl=BigInt(0),Ol={};function Ui(t,...e){let r=Ol[t];if(r===void 0){const n=Ai(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Xe(n,n),Ol[t]=r}return Ai(Xe(r,...e))}const Eo=t=>t.toRawBytes(!0).slice(1),_o=t=>Zt(t,32),So=t=>_e(t,On),Pn=t=>_e(t,Fi),xo=An.ProjectivePoint,v1=(t,e,r)=>xo.BASE.multiplyAndAddUnsafe(t,e,r);function Io(t){let e=An.utils.normPrivateKeyToScalar(t),r=xo.fromPrivateKey(e);return{scalar:r.hasEvenY()?e:Pn(-e),bytes:Eo(r)}}function $l(t){Jt("x",t,$n,On);const e=So(t*t),r=So(e*t+BigInt(7));let n=Il(r);n%Li!==Dl&&(n=So(-n));const i=new xo(t,n,$n);return i.assertValidity(),i}const Zr=Et;function Al(...t){return Pn(Zr(Ui("BIP0340/challenge",...t)))}function E1(t){return Io(t).bytes}function _1(t,e,r=ku(32)){const n=Ue("message",t),{bytes:i,scalar:s}=Io(e),o=Ue("auxRand",r,32),a=_o(s^Zr(Ui("BIP0340/aux",o))),c=Ui("BIP0340/nonce",a,i,n),u=Pn(Zr(c));if(u===Dl)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Io(u),d=Al(l,i,n),p=new Uint8Array(64);if(p.set(l,0),p.set(_o(Pn(h+d*s)),32),!Pl(p,n,i))throw new Error("sign: Invalid signature produced");return p}function Pl(t,e,r){const n=Ue("signature",t,64),i=Ue("message",e),s=Ue("publicKey",r,32);try{const o=$l(Zr(s)),a=Zr(n.subarray(0,32));if(!Gr(a,$n,On))return!1;const c=Zr(n.subarray(32,64));if(!Gr(c,$n,Fi))return!1;const u=Al(_o(a),Eo(o),i),l=v1(o,c,Pn(-u));return!(!l||!l.hasEvenY()||l.toAffine().x!==a)}catch{return!1}}const S1=(()=>({getPublicKey:E1,sign:_1,verify:Pl,utils:{randomPrivateKey:An.utils.randomPrivateKey,lift_x:$l,pointToBytes:Eo,numberToBytesBE:Zt,bytesToNumberBE:Et,taggedHash:Ui,mod:_e}}))(),x1=(()=>m1(er,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))))(),I1=(()=>h1(er,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:er.create(BigInt("-11"))}))(),Tl=(()=>b1(An.ProjectivePoint,t=>{const{x:e,y:r}=I1(er.create(t[0]));return x1(e,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:er.ORDER,m:1,k:128,expand:"xmd",hash:Ai}))();var D1=Object.freeze({__proto__:null,secp256k1:An,schnorr:S1,hashToCurve:(()=>Tl.hashToCurve)(),encodeToCurve:(()=>Tl.encodeToCurve)()});function O1(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,d=0;const p=u.length;for(;d!==p&&u[d]===0;)d++,l++;const f=(p-d)*s+1>>>0,y=new Uint8Array(f);for(;d!==p;){let m=u[d],b=0;for(let E=f-1;(m!==0||b<h)&&E!==-1;E--,b++)m+=256*y[E]>>>0,y[E]=m%r>>>0,m=m/r>>>0;if(m!==0)throw new Error("Non-zero carry");h=b,d++}let g=f-h;for(;g!==f&&y[g]===0;)g++;let w=n.repeat(l);for(;g<f;++g)w+=t.charAt(y[g]);return w}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===n;)h++,l++;const p=(u.length-l)*i+1>>>0,f=new Uint8Array(p);for(;l<u.length;){const m=u.charCodeAt(l);if(m>255)return;let b=e[m];if(b===255)return;let E=0;for(let $=p-1;(b!==0||E<d)&&$!==-1;$--,E++)b+=r*f[$]>>>0,f[$]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=E,l++}let y=p-d;for(;y!==p&&f[y]===0;)y++;const g=new Uint8Array(h+(p-y));let w=h;for(;y!==p;)g[w++]=f[y++];return g}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 $1="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",A1=O1($1);function Rl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Tn(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Rl(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return r}function P1(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var T1=P1,R1=T1;const Cl=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")},C1=t=>new TextEncoder().encode(t),N1=t=>new TextDecoder().decode(t);class B1{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 F1{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 Nl(this,e)}}class L1{constructor(e){this.decoders=e}or(e){return Nl(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 Nl=(t,e)=>new L1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class U1{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new B1(e,r,n),this.decoder=new F1(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ki=({name:t,prefix:e,encode:r,decode:n})=>new U1(t,e,r,n),Rn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=R1(r,e);return ki({prefix:t,name:e,encode:n,decode:s=>Cl(i(s))})},k1=(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},M1=(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},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ki({prefix:e,name:t,encode(i){return M1(i,n,r)},decode(i){return k1(i,n,r,t)}}),j1=ki({prefix:"\0",name:"identity",encode:t=>N1(t),decode:t=>C1(t)});var q1=Object.freeze({__proto__:null,identity:j1});const z1=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var V1=Object.freeze({__proto__:null,base2:z1});const K1=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var H1=Object.freeze({__proto__:null,base8:K1});const W1=Rn({prefix:"9",name:"base10",alphabet:"0123456789"});var G1=Object.freeze({__proto__:null,base10:W1});const Y1=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Z1=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var J1=Object.freeze({__proto__:null,base16:Y1,base16upper:Z1});const X1=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Q1=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ev=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tv=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rv=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nv=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iv=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),sv=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ov=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var av=Object.freeze({__proto__:null,base32:X1,base32upper:Q1,base32pad:ev,base32padupper:tv,base32hex:rv,base32hexupper:nv,base32hexpad:iv,base32hexpadupper:sv,base32z:ov});const cv=Rn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),uv=Rn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var lv=Object.freeze({__proto__:null,base36:cv,base36upper:uv});const hv=Rn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dv=Rn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fv=Object.freeze({__proto__:null,base58btc:hv,base58flickr:dv});const pv=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gv=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yv=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),wv=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mv=Object.freeze({__proto__:null,base64:pv,base64pad:gv,base64url:yv,base64urlpad:wv});const Bl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),bv=Bl.reduce((t,e,r)=>(t[r]=e,t),[]),vv=Bl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Ev(t){return t.reduce((e,r)=>(e+=bv[r],e),"")}function _v(t){const e=[];for(const r of t){const n=vv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const Sv=ki({prefix:"\u{1F680}",name:"base256emoji",encode:Ev,decode:_v});var xv=Object.freeze({__proto__:null,base256emoji:Sv}),Iv=Ll,Fl=128,Dv=127,Ov=~Dv,$v=Math.pow(2,31);function Ll(t,e,r){e=e||[],r=r||0;for(var n=r;t>=$v;)e[r++]=t&255|Fl,t/=128;for(;t&Ov;)e[r++]=t&255|Fl,t>>>=7;return e[r]=t|0,Ll.bytes=r-n+1,e}var Av=Do,Pv=128,Ul=127;function Do(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Do.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Ul)<<i:(o&Ul)*Math.pow(2,i),i+=7}while(o>=Pv);return Do.bytes=s-n,r}var Tv=Math.pow(2,7),Rv=Math.pow(2,14),Cv=Math.pow(2,21),Nv=Math.pow(2,28),Bv=Math.pow(2,35),Fv=Math.pow(2,42),Lv=Math.pow(2,49),Uv=Math.pow(2,56),kv=Math.pow(2,63),Mv=function(t){return t<Tv?1:t<Rv?2:t<Cv?3:t<Nv?4:t<Bv?5:t<Fv?6:t<Lv?7:t<Uv?8:t<kv?9:10},jv={encode:Iv,decode:Av,encodingLength:Mv},kl=jv;const Ml=(t,e,r=0)=>(kl.encode(t,e,r),e),jl=t=>kl.encodingLength(t),Oo=(t,e)=>{const r=e.byteLength,n=jl(t),i=n+jl(r),s=new Uint8Array(i+r);return Ml(t,s,0),Ml(r,s,n),s.set(e,i),new qv(t,r,e,s)};class qv{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const ql=({name:t,code:e,encode:r})=>new zv(t,e,r);class zv{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?Oo(this.code,r):r.then(n=>Oo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const zl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Vv=ql({name:"sha2-256",code:18,encode:zl("SHA-256")}),Kv=ql({name:"sha2-512",code:19,encode:zl("SHA-512")});var Hv=Object.freeze({__proto__:null,sha256:Vv,sha512:Kv});const Vl=0,Wv="identity",Kl=Cl;var Gv=Object.freeze({__proto__:null,identity:{code:Vl,name:Wv,encode:Kl,digest:t=>Oo(Vl,Kl(t))}});new TextEncoder,new TextDecoder;const Hl={...q1,...V1,...H1,...G1,...J1,...av,...lv,...fv,...mv,...xv};({...Hv,...Gv});function Wl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Gl=Wl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),$o=Wl("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=Rl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Yl={utf8:Gl,"utf-8":Gl,hex:Hl.base16,latin1:$o,ascii:$o,binary:$o,...Hl};function st(t,e="utf8"){const r=Yl[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,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Ge(t,e="utf8"){const r=Yl[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 Yv={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"}},Zv=":";function Mi(t){const[e,r]=t.split(Zv);return{namespace:e,reference:r}}function Zl(t,e){return t.includes(":")?[t]:e.chains||[]}var Jv=Object.defineProperty,Xv=Object.defineProperties,Qv=Object.getOwnPropertyDescriptors,Jl=Object.getOwnPropertySymbols,eE=Object.prototype.hasOwnProperty,tE=Object.prototype.propertyIsEnumerable,Xl=(t,e,r)=>e in t?Jv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ql=(t,e)=>{for(var r in e||(e={}))eE.call(e,r)&&Xl(t,r,e[r]);if(Jl)for(var r of Jl(e))tE.call(e,r)&&Xl(t,r,e[r]);return t},rE=(t,e)=>Xv(t,Qv(e));const nE="ReactNative",Qe={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},iE="js";function ji(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function tr(){return!_n()&&!!Ws()&&navigator.product===nE}function sE(){return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function oE(){return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Cn(){return!ji()&&!!Ws()&&!!_n()}function Nn(){return tr()?Qe.reactNative:ji()?Qe.node:Cn()?Qe.browser:Qe.unknown}function eh(){var t;try{return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function aE(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 cE(t){var e,r;const n=th();try{return t!=null&&t.url&&n.url&&t.url!==n.url&&(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!=="")),rE(Ql(Ql({},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 th(){return Su()||{name:"",description:"",url:"",icons:[""]}}function uE(){if(Nn()===Qe.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=Ym();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 lE(){var t;const e=Nn();return e===Qe.browser?[e,((t=_u())==null?void 0:t.host)||"unknown"].join(":"):e}function rh(t,e,r){const n=uE(),i=lE();return[[t,e].join("-"),[iE,r].join("-"),n,i].join("/")}function hE({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=rh(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=aE(u[1]||"",h);return u[0]+"?"+d}function mr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Ao(t){return Object.fromEntries(t.entries())}function Po(t){return new Map(Object.entries(t))}function br(t=L.FIVE_MINUTES,e){const r=L.toMiliseconds(t||L.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 rr(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 nh(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 dE(t){return nh("topic",t)}function fE(t){return nh("id",t)}function ih(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 L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function nr(t){return Date.now()>=L.toMiliseconds(t)}function Q(t,e){return`${t}${e?`:${e}`:""}`}function pE(t=[],e=[]){return[...new Set([...t,...e])]}async function gE({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=yE(s,t,e),a=Nn();if(a===Qe.browser){if(!((n=_n())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}wE(o)}else a===Qe.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function yE(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}${EE(n,!0)}`}else i=`${i}/wc?${n}`;return i}function wE(t){let e="_self";vE()?e="_top":(bE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function mE(t,e){let r="";try{if(Cn()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function sh(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function oh(){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 To(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function bE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function vE(){try{return window.self!==window.top}catch{return!1}}function EE(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function ah(t){return Buffer.from(t,"base64").toString("utf-8")}function _E(t){return new Promise(e=>setTimeout(e,t))}function Bn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function SE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Fn(t,...e){if(!SE(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 Ro(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Bn(t.outputLen),Bn(t.blockLen)}function Jr(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 ch(t,e){Fn(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const qi=BigInt(2**32-1),uh=BigInt(32);function xE(t,e=!1){return e?{h:Number(t&qi),l:Number(t>>uh&qi)}:{h:Number(t>>uh&qi)|0,l:Number(t&qi)|0}}function IE(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}=xE(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const DE=(t,e,r)=>t<<r|e>>>32-r,OE=(t,e,r)=>e<<r|t>>>32-r,$E=(t,e,r)=>e<<r-32|t>>>64-r,AE=(t,e,r)=>t<<r-32|e>>>64-r,Xr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function PE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Co(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function _t(t,e){return t<<32-e|t>>>e}const lh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function TE(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function hh(t){for(let e=0;e<t.length;e++)t[e]=TE(t[e])}function RE(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Qr(t){return typeof t=="string"&&(t=RE(t)),Fn(t),t}function CE(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Fn(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 No{clone(){return this._cloneInto()}}function dh(t){const e=n=>t().update(Qr(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function en(t=32){if(Xr&&typeof Xr.getRandomValues=="function")return Xr.getRandomValues(new Uint8Array(t));if(Xr&&typeof Xr.randomBytes=="function")return Xr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const fh=[],ph=[],gh=[],NE=BigInt(0),Ln=BigInt(1),BE=BigInt(2),FE=BigInt(7),LE=BigInt(256),UE=BigInt(113);for(let t=0,e=Ln,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],fh.push(2*(5*n+r)),ph.push((t+1)*(t+2)/2%64);let i=NE;for(let s=0;s<7;s++)e=(e<<Ln^(e>>FE)*UE)%LE,e&BE&&(i^=Ln<<(Ln<<BigInt(s))-Ln);gh.push(i)}const[kE,ME]=IE(gh,!0),yh=(t,e,r)=>r>32?$E(t,e,r):DE(t,e,r),wh=(t,e,r)=>r>32?AE(t,e,r):OE(t,e,r);function jE(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=yh(u,l,1)^r[a],d=wh(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ph[o],c=yh(i,s,a),u=wh(i,s,a),l=fh[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]^=kE[n],t[1]^=ME[n]}r.fill(0)}class Bo extends No{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Bn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=PE(this.state)}keccak(){lh||hh(this.state32),jE(this.state32,this.rounds),lh||hh(this.state32),this.posOut=0,this.pos=0}update(e){Jr(this);const{blockLen:r,state:n}=this;e=Qr(e);const 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){Jr(this,!1),Fn(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 Bn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ch(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new Bo(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 qE=(t,e,r)=>dh(()=>new Bo(e,t,r)),zE=qE(1,136,256/8),VE="https://rpc.walletconnect.org/v1";function mh(t){const e=`Ethereum Signed Message:
17
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class V0 extends qe{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 cl extends Qs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Ib(e);const n=$i(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),s.fill(0)}update(e){return zr(this),this.iHash.update(e),this}digestInto(e){zr(this),In(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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ul=(t,e,r)=>new cl(t,e).update(r).digest();ul.create=(t,e)=>new cl(t,e);const Ee=BigInt(0),de=BigInt(1),br=BigInt(2),K0=BigInt(3),go=BigInt(4),ll=BigInt(5),hl=BigInt(8);function _e(t,e){const r=t%e;return r>=Ee?r:e+r}function H0(t,e,r){if(e<Ee)throw new Error("invalid exponent, negatives unsupported");if(r<=Ee)throw new Error("invalid modulus");if(r===de)return Ee;let n=de;for(;e>Ee;)e&de&&(n=n*t%r),t=t*t%r,e>>=de;return n}function it(t,e,r){let n=t;for(;e-- >Ee;)n*=n,n%=r;return n}function yo(t,e){if(t===Ee)throw new Error("invert: expected non-zero number");if(e<=Ee)throw new Error("invert: expected positive modulus, got "+e);let r=_e(t,e),n=e,i=Ee,s=de;for(;r!==Ee;){const a=n/r,c=n%r,u=i-s*a;n=r,r=c,i=s,s=u}if(n!==de)throw new Error("invert: does not exist");return _e(i,e)}function W0(t){const e=(t-de)/br;let r,n,i;for(r=t-de,n=0;r%br===Ee;r/=br,n++);for(i=br;i<t&&H0(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)/go;return function(c,u){const l=c.pow(u,o);if(!c.eql(c.sqr(l),u))throw new Error("Cannot find square root");return l}}const s=(r+de)/br;return function(a,c){if(a.pow(c,e)===a.neg(a.ONE))throw new Error("Cannot find square root");let u=n,l=a.pow(a.mul(a.ONE,i),r),h=a.pow(c,s),d=a.pow(c,r);for(;!a.eql(d,a.ONE);){if(a.eql(d,a.ZERO))return a.ZERO;let p=1;for(let y=a.sqr(d);p<u&&!a.eql(y,a.ONE);p++)y=a.sqr(y);const f=a.pow(l,de<<BigInt(u-p-1));l=a.sqr(f),h=a.mul(h,f),d=a.mul(d,l),u=p}return h}}function G0(t){if(t%go===K0){const e=(t+de)/go;return function(n,i){const s=n.pow(i,e);if(!n.eql(n.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%hl===ll){const e=(t-ll)/hl;return function(n,i){const s=n.mul(i,br),o=n.pow(s,e),a=n.mul(i,o),c=n.mul(n.mul(a,br),o),u=n.mul(a,n.sub(c,n.ONE));if(!n.eql(n.sqr(u),i))throw new Error("Cannot find square root");return u}}return W0(t)}const Y0=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function dl(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=Y0.reduce((n,i)=>(n[i]="function",n),e);return Zr(t,r)}function Z0(t,e,r){if(r<Ee)throw new Error("invalid exponent, negatives unsupported");if(r===Ee)return t.ONE;if(r===de)return e;let n=t.ONE,i=e;for(;r>Ee;)r&de&&(n=t.mul(n,i)),i=t.sqr(i),r>>=de;return n}function J0(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 fl(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function pl(t,e,r=!1,n={}){if(t<=Ee)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=fl(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:oo(i),ZERO:Ee,ONE:de,create:c=>_e(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ee<=c&&c<t},is0:c=>c===Ee,isOdd:c=>(c&de)===de,neg:c=>_e(-c,t),eql:(c,u)=>c===u,sqr:c=>_e(c*c,t),add:(c,u)=>_e(c+u,t),sub:(c,u)=>_e(c-u,t),mul:(c,u)=>_e(c*u,t),pow:(c,u)=>Z0(a,c,u),div:(c,u)=>_e(c*yo(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>yo(c,t),sqrt:n.sqrt||(c=>(o||(o=G0(t)),o(a,c))),invertBatch:c=>J0(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?io(c,s):Zt(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?no(c):Et(c)}});return Object.freeze(a)}function gl(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 yl(t){const e=gl(t);return e+Math.ceil(e/2)}function X0(t,e,r=!1){const n=t.length,i=gl(e),s=yl(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?no(t):Et(t),a=_e(o,e-de)+de;return r?io(a,i):Zt(a,i)}const wl=BigInt(0),Ni=BigInt(1);function wo(t,e){const r=e.negate();return t?r:e}function ml(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function mo(t,e){ml(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function Q0(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 e1(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 bo=new WeakMap,bl=new WeakMap;function vo(t){return bl.get(t)||1}function t1(t,e){return{constTimeNegate:wo,hasPrecomputes(r){return vo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>wl;)n&Ni&&(i=i.add(s)),s=s.double(),n>>=Ni;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=mo(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}=mo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=Ni);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(wo(w,n[y])):a=a.add(wo(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=mo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===wl)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=Ni),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=bo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&bo.set(n,i(s))),s},wNAFCached(r,n,i){const s=vo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=vo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){ml(n,e),bl.set(r,n),bo.delete(r)}}}function r1(t,e,r,n){if(Q0(r,t),e1(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Ju(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function vl(t){return dl(t.Fp),Zr(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...fl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function El(t){t.lowS!==void 0&&Kr("lowS",t.lowS),t.prehash!==void 0&&Kr("prehash",t.prehash)}function n1(t){const e=vl(t);Zr(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:i1,hexToBytes:s1}=d0;class o1 extends Error{constructor(e=""){super(e)}}const Ft={Err:o1,_tlv:{encode:(t,e)=>{const{Err:r}=Ft;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=Wr(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?Wr(i.length/2|128):"";return Wr(t)+s+i+e},decode(t,e){const{Err:r}=Ft;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}=Ft;if(t<lt)throw new e("integer: negative integers are not allowed");let r=Wr(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}=Ft;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 i1(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=Ft,i=typeof t=="string"?s1(t):t;vt(i);const{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}=Ft,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},lt=BigInt(0),re=BigInt(1),Xt=BigInt(2),Bi=BigInt(3),_l=BigInt(4);function a1(t){const e=n1(t),{Fp:r}=e,n=pl(e.n,e.nBitLength),i=e.toBytes||((y,g,w)=>{const m=g.toAffine();return Xe(Uint8Array.from([4]),r.toBytes(m.x),r.toBytes(m.y))}),s=e.fromBytes||(y=>{const g=y.subarray(1),w=r.fromBytes(g.subarray(0,r.BYTES)),m=r.fromBytes(g.subarray(r.BYTES,2*r.BYTES));return{x:w,y:m}});function o(y){const{a:g,b:w}=e,m=r.sqr(y),b=r.mul(m,y);return r.add(r.add(b,r.mul(y,g)),w)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Yr(y,re,e.n)}function c(y){const{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:m,n:b}=e;if(g&&typeof y!="bigint"){if(mr(y)&&(y=Hr(y)),typeof y!="string"||!g.includes(y.length))throw new Error("invalid private key");y=y.padStart(w*2,"0")}let E;try{E=typeof y=="bigint"?y:Et(Ue("private key",y,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof y)}return m&&(E=_e(E,b)),Jt("private key",E,re,b),E}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=co((y,g)=>{const{px:w,py:m,pz:b}=y;if(r.eql(b,r.ONE))return{x:w,y:m};const E=y.is0();g==null&&(g=E?r.ONE:r.inv(b));const $=r.mul(w,g),D=r.mul(m,g),S=r.mul(b,g);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),h=co(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:g,y:w}=y.toAffine();if(!r.isValid(g)||!r.isValid(w))throw new Error("bad point: x or y not FE");const m=r.sqr(w),b=o(g);if(!r.eql(m,b))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,w,m){if(this.px=g,this.py=w,this.pz=m,g==null||!r.isValid(g))throw new Error("x required");if(w==null||!r.isValid(w))throw new Error("y required");if(m==null||!r.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(g){const{x:w,y:m}=g||{};if(!g||!r.isValid(w)||!r.isValid(m))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");const b=E=>r.eql(E,r.ZERO);return b(w)&&b(m)?d.ZERO:new d(w,m,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){const w=r.invertBatch(g.map(m=>m.pz));return g.map((m,b)=>m.toAffine(w[b])).map(d.fromAffine)}static fromHex(g){const w=d.fromAffine(s(Ue("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return r1(d,n,g,w)}_setWindowSize(g){f.setWindowSize(this,g)}assertValidity(){h(this)}hasEvenY(){const{y:g}=this.toAffine();if(r.isOdd)return!r.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g,S=r.eql(r.mul(w,D),r.mul(E,b)),A=r.eql(r.mul(m,D),r.mul($,b));return S&&A}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:g,b:w}=e,m=r.mul(w,Bi),{px:b,py:E,pz:$}=this;let D=r.ZERO,S=r.ZERO,A=r.ZERO,x=r.mul(b,b),k=r.mul(E,E),C=r.mul($,$),B=r.mul(b,E);return B=r.add(B,B),A=r.mul(b,$),A=r.add(A,A),D=r.mul(g,A),S=r.mul(m,C),S=r.add(D,S),D=r.sub(k,S),S=r.add(k,S),S=r.mul(D,S),D=r.mul(B,D),A=r.mul(m,A),C=r.mul(g,C),B=r.sub(x,C),B=r.mul(g,B),B=r.add(B,A),A=r.add(x,x),x=r.add(A,x),x=r.add(x,C),x=r.mul(x,B),S=r.add(S,x),C=r.mul(E,$),C=r.add(C,C),x=r.mul(C,B),D=r.sub(D,x),A=r.mul(C,k),A=r.add(A,A),A=r.add(A,A),new d(D,S,A)}add(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g;let S=r.ZERO,A=r.ZERO,x=r.ZERO;const k=e.a,C=r.mul(e.b,Bi);let B=r.mul(w,E),j=r.mul(m,$),I=r.mul(b,D),_=r.add(w,m),v=r.add(E,$);_=r.mul(_,v),v=r.add(B,j),_=r.sub(_,v),v=r.add(w,b);let O=r.add(E,D);return v=r.mul(v,O),O=r.add(B,I),v=r.sub(v,O),O=r.add(m,b),S=r.add($,D),O=r.mul(O,S),S=r.add(j,I),O=r.sub(O,S),x=r.mul(k,v),S=r.mul(C,I),x=r.add(S,x),S=r.sub(j,x),x=r.add(j,x),A=r.mul(S,x),j=r.add(B,B),j=r.add(j,B),I=r.mul(k,I),v=r.mul(C,v),j=r.add(j,I),I=r.sub(B,I),I=r.mul(k,I),v=r.add(v,I),B=r.mul(j,v),A=r.add(A,B),B=r.mul(O,v),S=r.mul(_,S),S=r.sub(S,B),B=r.mul(_,j),x=r.mul(O,x),x=r.add(x,B),new d(S,A,x)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return f.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){const{endo:w,n:m}=e;Jt("scalar",g,lt,m);const b=d.ZERO;if(g===lt)return b;if(this.is0()||g===re)return this;if(!w||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:E,k1:$,k2neg:D,k2:S}=w.splitScalar(g),A=b,x=b,k=this;for(;$>lt||S>lt;)$&re&&(A=A.add(k)),S&re&&(x=x.add(k)),k=k.double(),$>>=re,S>>=re;return E&&(A=A.negate()),D&&(x=x.negate()),x=new d(r.mul(x.px,w.beta),x.py,x.pz),A.add(x)}multiply(g){const{endo:w,n:m}=e;Jt("scalar",g,re,m);let b,E;if(w){const{k1neg:$,k1:D,k2neg:S,k2:A}=w.splitScalar(g);let{p:x,f:k}=this.wNAF(D),{p:C,f:B}=this.wNAF(A);x=f.constTimeNegate($,x),C=f.constTimeNegate(S,C),C=new d(r.mul(C.px,w.beta),C.py,C.pz),b=x.add(C),E=k.add(B)}else{const{p:$,f:D}=this.wNAF(g);b=$,E=D}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(g,w,m){const b=d.BASE,E=(D,S)=>S===lt||S===re||!D.equals(b)?D.multiplyUnsafe(S):D.multiply(S),$=E(this,w).add(E(g,m));return $.is0()?void 0:$}toAffine(g){return l(this,g)}isTorsionFree(){const{h:g,isTorsionFree:w}=e;if(g===re)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:g,clearCofactor:w}=e;return g===re?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return Kr("isCompressed",g),this.assertValidity(),i(d,this,g)}toHex(g=!0){return Kr("isCompressed",g),Hr(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const p=e.nBitLength,f=t1(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function c1(t){const e=vl(t);return Zr(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function u1(t){const e=c1(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(I){return _e(I,n)}function a(I){return yo(I,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=a1({...e,toBytes(I,_,v){const O=_.toAffine(),T=r.toBytes(O.x),P=Xe;return Kr("isCompressed",v),v?P(Uint8Array.from([_.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,r.toBytes(O.y))},fromBytes(I){const _=I.length,v=I[0],O=I.subarray(1);if(_===i&&(v===2||v===3)){const T=Et(O);if(!Yr(T,re,r.ORDER))throw new Error("Point is not on curve");const P=l(T);let N;try{N=r.sqrt(P)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const F=(N&re)===re;return(v&1)===1!==F&&(N=r.neg(N)),{x:T,y:N}}else if(_===s&&v===4){const T=r.fromBytes(O.subarray(0,r.BYTES)),P=r.fromBytes(O.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}}else{const T=i,P=s;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+P+", got "+_)}}}),d=I=>Hr(Zt(I,e.nByteLength));function p(I){const _=n>>re;return I>_}function f(I){return p(I)?o(-I):I}const y=(I,_,v)=>Et(I.slice(_,v));class g{constructor(_,v,O){this.r=_,this.s=v,this.recovery=O,this.assertValidity()}static fromCompact(_){const v=e.nByteLength;return _=Ue("compactSignature",_,v*2),new g(y(_,0,v),y(_,v,2*v))}static fromDER(_){const{r:v,s:O}=Ft.toSig(Ue("DER",_));return new g(v,O)}assertValidity(){Jt("r",this.r,re,n),Jt("s",this.s,re,n)}addRecoveryBit(_){return new g(this.r,this.s,_)}recoverPublicKey(_){const{r:v,s:O,recovery:T}=this,P=D(Ue("msgHash",_));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const N=T===2||T===3?v+e.n:v;if(N>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const F=T&1?"03":"02",M=c.fromHex(F+d(N)),z=a(N),q=o(-P*z),V=o(O*z),K=c.BASE.multiplyAndAddUnsafe(M,q,V);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return Gr(this.toDERHex())}toDERHex(){return Ft.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return Gr(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const I=yl(e.n);return X0(e.randomBytes(I),e.n)},precompute(I=8,_=c.BASE){return _._setWindowSize(I),_.multiply(BigInt(3)),_}};function m(I,_=!0){return c.fromPrivateKey(I).toRawBytes(_)}function b(I){const _=mr(I),v=typeof I=="string",O=(_||v)&&I.length;return _?O===i||O===s:v?O===2*i||O===2*s:I instanceof c}function E(I,_,v=!0){if(b(I))throw new Error("first arg must be private key");if(!b(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(u(I)).toRawBytes(v)}const $=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const _=Et(I),v=I.length*8-e.nBitLength;return v>0?_>>BigInt(v):_},D=e.bits2int_modN||function(I){return o($(I))},S=oo(e.nBitLength);function A(I){return Jt("num < 2^"+e.nBitLength,I,lt,S),Zt(I,e.nByteLength)}function x(I,_,v=k){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:T}=e;let{lowS:P,prehash:N,extraEntropy:F}=v;P==null&&(P=!0),I=Ue("msgHash",I),El(v),N&&(I=Ue("prehashed msgHash",O(I)));const M=D(I),z=u(_),q=[A(z),A(M)];if(F!=null&&F!==!1){const G=F===!0?T(r.BYTES):F;q.push(Ue("extraEntropy",G))}const V=Xe(...q),K=M;function ee(G){const W=$(G);if(!h(W))return;const ye=a(W),ue=c.BASE.multiply(W).toAffine(),le=o(ue.x);if(le===lt)return;const $e=o(ye*o(K+le*z));if($e===lt)return;let Me=(ue.x===le?0:2)|Number(ue.y&re),Kt=$e;return P&&p($e)&&(Kt=f($e),Me^=1),new g(le,Kt,Me)}return{seed:V,k2sig:ee}}const k={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function B(I,_,v=k){const{seed:O,k2sig:T}=x(I,_,v),P=e;return Qu(P.hash.outputLen,P.nByteLength,P.hmac)(O,T)}c.BASE._setWindowSize(8);function j(I,_,v,O=C){const T=I;_=Ue("msgHash",_),v=Ue("publicKey",v);const{lowS:P,prehash:N,format:F}=O;if(El(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const M=typeof T=="string"||mr(T),z=!M&&!F&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!M&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,V;try{if(z&&(q=new g(T.r,T.s)),M){try{F!=="compact"&&(q=g.fromDER(T))}catch(Me){if(!(Me instanceof Ft.Err))throw Me}!q&&F!=="der"&&(q=g.fromCompact(T))}V=c.fromHex(v)}catch{return!1}if(!q||P&&q.hasHighS())return!1;N&&(_=e.hash(_));const{r:K,s:ee}=q,G=D(_),W=a(ee),ye=o(G*W),ue=o(K*W),le=c.BASE.multiplyAndAddUnsafe(V,ye,ue)?.toAffine();return le?o(le.x)===K:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:E,sign:B,verify:j,ProjectivePoint:c,Signature:g,utils:w}}function l1(t,e){const r=t.ORDER;let n=lt;for(let f=r-re;f%Xt===lt;f/=Xt)n+=re;const i=n,s=Xt<<i-re-re,o=s*Xt,a=(r-re)/o,c=(a-re)/Xt,u=o-re,l=s,h=t.pow(e,a),d=t.pow(e,(a+re)/Xt);let p=(f,y)=>{let g=h,w=t.pow(y,u),m=t.sqr(w);m=t.mul(m,y);let b=t.mul(f,m);b=t.pow(b,c),b=t.mul(b,w),w=t.mul(b,y),m=t.mul(b,f);let E=t.mul(m,w);b=t.pow(E,l);let $=t.eql(b,t.ONE);w=t.mul(m,d),b=t.mul(E,g),m=t.cmov(w,m,$),E=t.cmov(b,E,$);for(let D=i;D>re;D--){let S=D-Xt;S=Xt<<S-re;let A=t.pow(E,S);const x=t.eql(A,t.ONE);w=t.mul(m,g),g=t.mul(g,g),A=t.mul(E,g),m=t.cmov(w,m,x),E=t.cmov(A,E,x)}return{isValid:$,value:m}};if(t.ORDER%_l===Bi){const f=(t.ORDER-Bi)/_l,y=t.sqrt(t.neg(e));p=(g,w)=>{let m=t.sqr(w);const b=t.mul(g,w);m=t.mul(m,b);let E=t.pow(m,f);E=t.mul(E,b);const $=t.mul(E,y),D=t.mul(t.sqr(E),w),S=t.eql(D,g);let A=t.cmov($,E,S);return{isValid:S,value:A}}}return p}function h1(t,e){if(dl(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const r=l1(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:d,value:p}=r(s,u);h=t.mul(i,n),h=t.mul(h,p),l=t.cmov(l,o,d),h=t.cmov(h,p,d);const f=t.isOdd(n)===t.isOdd(h);return h=t.cmov(t.neg(h),h,f),l=t.div(l,a),{x:l,y:h}}}function d1(t){return{hash:t,hmac:(e,...r)=>ul(t,e,Bb(...r)),randomBytes:ku}}function f1(t,e){const r=n=>u1({...t,...d1(n)});return{...r(e),create:r}}const p1=Et;function Qt(t,e){if(On(t),On(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 g1(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 On(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function y1(t,e,r,n){vt(t),vt(e),On(r),e.length>255&&(e=n(Xe(Ri("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=Xe(e,Qt(e.length,1)),c=Qt(0,s),u=Qt(r,2),l=new Array(o),h=n(Xe(c,t,u,Qt(0,1),a));l[0]=n(Xe(h,Qt(1,1),a));for(let p=1;p<=o;p++){const f=[g1(h,l[p-1]),Qt(p+1,1),a];l[p]=n(Xe(...f))}return Xe(...l).slice(0,r)}function w1(t,e,r,n,i){if(vt(t),vt(e),On(r),e.length>255){const s=Math.ceil(2*n/8);e=i.create({dkLen:s}).update(Ri("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(Qt(r,2)).update(e).update(Qt(e.length,1)).digest()}function Sl(t,e,r){Zr(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;vt(t),On(e);const u=typeof c=="string"?Ri(c):c,l=n.toString(2).length,h=Math.ceil((l+i)/8),d=e*s*h;let p;if(a==="xmd")p=y1(t,u,d,o);else if(a==="xof")p=w1(t,u,d,i,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const f=new Array(e);for(let y=0;y<e;y++){const g=new Array(s);for(let w=0;w<s;w++){const m=h*(w+y*s),b=p.subarray(m,m+h);g[w]=_e(p1(b),n)}f[y]=g}return f}function m1(t,e){const r=e.map(n=>Array.from(n).reverse());return(n,i)=>{const[s,o,a,c]=r.map(u=>u.reduce((l,h)=>t.add(t.mul(l,n),h)));return n=t.div(s,o),i=t.mul(i,t.div(a,c)),{x:n,y:i}}}function b1(t,e,r){if(typeof e!="function")throw new Error("mapToCurve() must be defined");return{hashToCurve(n,i){const s=Sl(n,2,{...r,DST:r.DST,...i}),o=t.fromAffine(e(s[0])),a=t.fromAffine(e(s[1])),c=o.add(a).clearCofactor();return c.assertValidity(),c},encodeToCurve(n,i){const s=Sl(n,1,{...r,DST:r.encodeDST,...i}),o=t.fromAffine(e(s[0])).clearCofactor();return o.assertValidity(),o},mapToCurve(n){if(!Array.isArray(n))throw new Error("mapToCurve: expected array of bigints");for(const s of n)if(typeof s!="bigint")throw new Error("mapToCurve: expected array of bigints");const i=t.fromAffine(e(n)).clearCofactor();return i.assertValidity(),i}}}const $n=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Fi=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),An=BigInt(1),Li=BigInt(2),xl=(t,e)=>(t+e/Li)/e;function Il(t){const e=$n,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=it(l,r,e)*l%e,d=it(h,r,e)*l%e,p=it(d,Li,e)*u%e,f=it(p,i,e)*p%e,y=it(f,s,e)*f%e,g=it(y,a,e)*y%e,w=it(g,c,e)*g%e,m=it(w,a,e)*y%e,b=it(m,r,e)*l%e,E=it(b,o,e)*f%e,$=it(E,n,e)*u%e,D=it($,Li,e);if(!er.eql(er.sqr(D),t))throw new Error("Cannot find square root");return D}const er=pl($n,void 0,void 0,{sqrt:Il}),Pn=f1({a:BigInt(0),b:BigInt(7),Fp:er,n:Fi,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Fi,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-An*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=xl(s*t,e),c=xl(-n*t,e);let u=_e(t-a*r-c*i,e),l=_e(-a*n-c*s,e);const h=u>o,d=l>o;if(h&&(u=e-u),d&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:d,k2:l}}}},Ai),Dl=BigInt(0),Ol={};function Ui(t,...e){let r=Ol[t];if(r===void 0){const n=Ai(Uint8Array.from(t,i=>i.charCodeAt(0)));r=Xe(n,n),Ol[t]=r}return Ai(Xe(r,...e))}const Eo=t=>t.toRawBytes(!0).slice(1),_o=t=>Zt(t,32),So=t=>_e(t,$n),Tn=t=>_e(t,Fi),xo=Pn.ProjectivePoint,v1=(t,e,r)=>xo.BASE.multiplyAndAddUnsafe(t,e,r);function Io(t){let e=Pn.utils.normPrivateKeyToScalar(t),r=xo.fromPrivateKey(e);return{scalar:r.hasEvenY()?e:Tn(-e),bytes:Eo(r)}}function $l(t){Jt("x",t,An,$n);const e=So(t*t),r=So(e*t+BigInt(7));let n=Il(r);n%Li!==Dl&&(n=So(-n));const i=new xo(t,n,An);return i.assertValidity(),i}const Jr=Et;function Al(...t){return Tn(Jr(Ui("BIP0340/challenge",...t)))}function E1(t){return Io(t).bytes}function _1(t,e,r=ku(32)){const n=Ue("message",t),{bytes:i,scalar:s}=Io(e),o=Ue("auxRand",r,32),a=_o(s^Jr(Ui("BIP0340/aux",o))),c=Ui("BIP0340/nonce",a,i,n),u=Tn(Jr(c));if(u===Dl)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Io(u),d=Al(l,i,n),p=new Uint8Array(64);if(p.set(l,0),p.set(_o(Tn(h+d*s)),32),!Pl(p,n,i))throw new Error("sign: Invalid signature produced");return p}function Pl(t,e,r){const n=Ue("signature",t,64),i=Ue("message",e),s=Ue("publicKey",r,32);try{const o=$l(Jr(s)),a=Jr(n.subarray(0,32));if(!Yr(a,An,$n))return!1;const c=Jr(n.subarray(32,64));if(!Yr(c,An,Fi))return!1;const u=Al(_o(a),Eo(o),i),l=v1(o,c,Tn(-u));return!(!l||!l.hasEvenY()||l.toAffine().x!==a)}catch{return!1}}const S1=(()=>({getPublicKey:E1,sign:_1,verify:Pl,utils:{randomPrivateKey:Pn.utils.randomPrivateKey,lift_x:$l,pointToBytes:Eo,numberToBytesBE:Zt,bytesToNumberBE:Et,taggedHash:Ui,mod:_e}}))(),x1=(()=>m1(er,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))))(),I1=(()=>h1(er,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:er.create(BigInt("-11"))}))(),Tl=(()=>b1(Pn.ProjectivePoint,t=>{const{x:e,y:r}=I1(er.create(t[0]));return x1(e,r)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:er.ORDER,m:1,k:128,expand:"xmd",hash:Ai}))();var D1=Object.freeze({__proto__:null,secp256k1:Pn,schnorr:S1,hashToCurve:(()=>Tl.hashToCurve)(),encodeToCurve:(()=>Tl.encodeToCurve)()});function O1(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,d=0;const p=u.length;for(;d!==p&&u[d]===0;)d++,l++;const f=(p-d)*s+1>>>0,y=new Uint8Array(f);for(;d!==p;){let m=u[d],b=0;for(let E=f-1;(m!==0||b<h)&&E!==-1;E--,b++)m+=256*y[E]>>>0,y[E]=m%r>>>0,m=m/r>>>0;if(m!==0)throw new Error("Non-zero carry");h=b,d++}let g=f-h;for(;g!==f&&y[g]===0;)g++;let w=n.repeat(l);for(;g<f;++g)w+=t.charAt(y[g]);return w}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,d=0;for(;u[l]===n;)h++,l++;const p=(u.length-l)*i+1>>>0,f=new Uint8Array(p);for(;l<u.length;){const m=u.charCodeAt(l);if(m>255)return;let b=e[m];if(b===255)return;let E=0;for(let $=p-1;(b!==0||E<d)&&$!==-1;$--,E++)b+=r*f[$]>>>0,f[$]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");d=E,l++}let y=p-d;for(;y!==p&&f[y]===0;)y++;const g=new Uint8Array(h+(p-y));let w=h;for(;y!==p;)g[w++]=f[y++];return g}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 $1="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",A1=O1($1);function Rl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function Rn(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const r=Rl(e);let n=0;for(const i of t)r.set(i,n),n+=i.length;return r}function P1(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var T1=P1,R1=T1;const Cl=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")},C1=t=>new TextEncoder().encode(t),N1=t=>new TextDecoder().decode(t);class B1{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 F1{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 Nl(this,e)}}class L1{constructor(e){this.decoders=e}or(e){return Nl(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 Nl=(t,e)=>new L1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class U1{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new B1(e,r,n),this.decoder=new F1(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ki=({name:t,prefix:e,encode:r,decode:n})=>new U1(t,e,r,n),Cn=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=R1(r,e);return ki({prefix:t,name:e,encode:n,decode:s=>Cl(i(s))})},k1=(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},M1=(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},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>ki({prefix:e,name:t,encode(i){return M1(i,n,r)},decode(i){return k1(i,n,r,t)}}),j1=ki({prefix:"\0",name:"identity",encode:t=>N1(t),decode:t=>C1(t)});var q1=Object.freeze({__proto__:null,identity:j1});const z1=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var V1=Object.freeze({__proto__:null,base2:z1});const K1=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var H1=Object.freeze({__proto__:null,base8:K1});const W1=Cn({prefix:"9",name:"base10",alphabet:"0123456789"});var G1=Object.freeze({__proto__:null,base10:W1});const Y1=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Z1=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var J1=Object.freeze({__proto__:null,base16:Y1,base16upper:Z1});const X1=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Q1=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),ev=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),tv=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rv=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),nv=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),iv=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),sv=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ov=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var av=Object.freeze({__proto__:null,base32:X1,base32upper:Q1,base32pad:ev,base32padupper:tv,base32hex:rv,base32hexupper:nv,base32hexpad:iv,base32hexpadupper:sv,base32z:ov});const cv=Cn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),uv=Cn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var lv=Object.freeze({__proto__:null,base36:cv,base36upper:uv});const hv=Cn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dv=Cn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var fv=Object.freeze({__proto__:null,base58btc:hv,base58flickr:dv});const pv=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),gv=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),yv=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),wv=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mv=Object.freeze({__proto__:null,base64:pv,base64pad:gv,base64url:yv,base64urlpad:wv});const Bl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),bv=Bl.reduce((t,e,r)=>(t[r]=e,t),[]),vv=Bl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Ev(t){return t.reduce((e,r)=>(e+=bv[r],e),"")}function _v(t){const e=[];for(const r of t){const n=vv[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const Sv=ki({prefix:"\u{1F680}",name:"base256emoji",encode:Ev,decode:_v});var xv=Object.freeze({__proto__:null,base256emoji:Sv}),Iv=Ll,Fl=128,Dv=127,Ov=~Dv,$v=Math.pow(2,31);function Ll(t,e,r){e=e||[],r=r||0;for(var n=r;t>=$v;)e[r++]=t&255|Fl,t/=128;for(;t&Ov;)e[r++]=t&255|Fl,t>>>=7;return e[r]=t|0,Ll.bytes=r-n+1,e}var Av=Do,Pv=128,Ul=127;function Do(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw Do.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Ul)<<i:(o&Ul)*Math.pow(2,i),i+=7}while(o>=Pv);return Do.bytes=s-n,r}var Tv=Math.pow(2,7),Rv=Math.pow(2,14),Cv=Math.pow(2,21),Nv=Math.pow(2,28),Bv=Math.pow(2,35),Fv=Math.pow(2,42),Lv=Math.pow(2,49),Uv=Math.pow(2,56),kv=Math.pow(2,63),Mv=function(t){return t<Tv?1:t<Rv?2:t<Cv?3:t<Nv?4:t<Bv?5:t<Fv?6:t<Lv?7:t<Uv?8:t<kv?9:10},jv={encode:Iv,decode:Av,encodingLength:Mv},kl=jv;const Ml=(t,e,r=0)=>(kl.encode(t,e,r),e),jl=t=>kl.encodingLength(t),Oo=(t,e)=>{const r=e.byteLength,n=jl(t),i=n+jl(r),s=new Uint8Array(i+r);return Ml(t,s,0),Ml(r,s,n),s.set(e,i),new qv(t,r,e,s)};class qv{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const ql=({name:t,code:e,encode:r})=>new zv(t,e,r);class zv{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?Oo(this.code,r):r.then(n=>Oo(this.code,n))}else throw Error("Unknown type, must be binary type")}}const zl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Vv=ql({name:"sha2-256",code:18,encode:zl("SHA-256")}),Kv=ql({name:"sha2-512",code:19,encode:zl("SHA-512")});var Hv=Object.freeze({__proto__:null,sha256:Vv,sha512:Kv});const Vl=0,Wv="identity",Kl=Cl;var Gv=Object.freeze({__proto__:null,identity:{code:Vl,name:Wv,encode:Kl,digest:t=>Oo(Vl,Kl(t))}});new TextEncoder,new TextDecoder;const Hl={...q1,...V1,...H1,...G1,...J1,...av,...lv,...fv,...mv,...xv};({...Hv,...Gv});function Wl(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const Gl=Wl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),$o=Wl("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=Rl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Yl={utf8:Gl,"utf-8":Gl,hex:Hl.base16,latin1:$o,ascii:$o,binary:$o,...Hl};function st(t,e="utf8"){const r=Yl[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,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}function Ge(t,e="utf8"){const r=Yl[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 Yv={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"}},Zv=":";function Mi(t){const[e,r]=t.split(Zv);return{namespace:e,reference:r}}function Zl(t,e){return t.includes(":")?[t]:e.chains||[]}var Jv=Object.defineProperty,Xv=Object.defineProperties,Qv=Object.getOwnPropertyDescriptors,Jl=Object.getOwnPropertySymbols,eE=Object.prototype.hasOwnProperty,tE=Object.prototype.propertyIsEnumerable,Xl=(t,e,r)=>e in t?Jv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ql=(t,e)=>{for(var r in e||(e={}))eE.call(e,r)&&Xl(t,r,e[r]);if(Jl)for(var r of Jl(e))tE.call(e,r)&&Xl(t,r,e[r]);return t},rE=(t,e)=>Xv(t,Qv(e));const nE="ReactNative",Qe={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},iE="js";function ji(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function tr(){return!yr()&&!!Ws()&&navigator.product===nE}function sE(){return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function oE(){return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Xr(){return!ji()&&!!Ws()&&!!yr()}function Nn(){return tr()?Qe.reactNative:ji()?Qe.node:Xr()?Qe.browser:Qe.unknown}function eh(){var t;try{return tr()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function aE(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 cE(t){var e,r;const n=th();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!=="")),rE(Ql(Ql({},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 th(){return Su()||{name:"",description:"",url:"",icons:[""]}}function uE(){if(Nn()===Qe.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=Ym();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 lE(){var t;const e=Nn();return e===Qe.browser?[e,((t=_u())==null?void 0:t.host)||"unknown"].join(":"):e}function rh(t,e,r){const n=uE(),i=lE();return[[t,e].join("-"),[iE,r].join("-"),n,i].join("/")}function hE({protocol:t,version:e,relayUrl:r,sdkVersion:n,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=rh(t,e,n),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=aE(u[1]||"",h);return u[0]+"?"+d}function vr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Ao(t){return Object.fromEntries(t.entries())}function Po(t){return new Map(Object.entries(t))}function Er(t=L.FIVE_MINUTES,e){const r=L.toMiliseconds(t||L.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 rr(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 nh(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 dE(t){return nh("topic",t)}function fE(t){return nh("id",t)}function ih(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 L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function nr(t){return Date.now()>=L.toMiliseconds(t)}function Q(t,e){return`${t}${e?`:${e}`:""}`}function pE(t=[],e=[]){return[...new Set([...t,...e])]}async function gE({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=yE(s,t,e),a=Nn();if(a===Qe.browser){if(!((n=yr())!=null&&n.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}wE(o)}else a===Qe.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function yE(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}${EE(n,!0)}`}else i=`${i}/wc?${n}`;return i}function wE(t){let e="_self";vE()?e="_top":(bE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function mE(t,e){let r="";try{if(Xr()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(n){console.error(n)}return r}function sh(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),n=r.indexOf(e);return r[n+2]}function oh(){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 To(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function bE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function vE(){try{return window.self!==window.top}catch{return!1}}function EE(t,e=!1){const r=Buffer.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function ah(t){return Buffer.from(t,"base64").toString("utf-8")}function _E(t){return new Promise(e=>setTimeout(e,t))}function Bn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function SE(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Fn(t,...e){if(!SE(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 Ro(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");Bn(t.outputLen),Bn(t.blockLen)}function Qr(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 ch(t,e){Fn(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const qi=BigInt(2**32-1),uh=BigInt(32);function xE(t,e=!1){return e?{h:Number(t&qi),l:Number(t>>uh&qi)}:{h:Number(t>>uh&qi)|0,l:Number(t&qi)|0}}function IE(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}=xE(t[i],e);[r[i],n[i]]=[s,o]}return[r,n]}const DE=(t,e,r)=>t<<r|e>>>32-r,OE=(t,e,r)=>e<<r|t>>>32-r,$E=(t,e,r)=>e<<r-32|t>>>64-r,AE=(t,e,r)=>t<<r-32|e>>>64-r,en=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function PE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Co(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function _t(t,e){return t<<32-e|t>>>e}const lh=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function TE(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function hh(t){for(let e=0;e<t.length;e++)t[e]=TE(t[e])}function RE(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function tn(t){return typeof t=="string"&&(t=RE(t)),Fn(t),t}function CE(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Fn(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 No{clone(){return this._cloneInto()}}function dh(t){const e=n=>t().update(tn(n)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function rn(t=32){if(en&&typeof en.getRandomValues=="function")return en.getRandomValues(new Uint8Array(t));if(en&&typeof en.randomBytes=="function")return en.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}const fh=[],ph=[],gh=[],NE=BigInt(0),Ln=BigInt(1),BE=BigInt(2),FE=BigInt(7),LE=BigInt(256),UE=BigInt(113);for(let t=0,e=Ln,r=1,n=0;t<24;t++){[r,n]=[n,(2*r+3*n)%5],fh.push(2*(5*n+r)),ph.push((t+1)*(t+2)/2%64);let i=NE;for(let s=0;s<7;s++)e=(e<<Ln^(e>>FE)*UE)%LE,e&BE&&(i^=Ln<<(Ln<<BigInt(s))-Ln);gh.push(i)}const[kE,ME]=IE(gh,!0),yh=(t,e,r)=>r>32?$E(t,e,r):DE(t,e,r),wh=(t,e,r)=>r>32?AE(t,e,r):OE(t,e,r);function jE(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=yh(u,l,1)^r[a],d=wh(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=ph[o],c=yh(i,s,a),u=wh(i,s,a),l=fh[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]^=kE[n],t[1]^=ME[n]}r.fill(0)}class Bo extends No{constructor(e,r,n,i=!1,s=24){if(super(),this.blockLen=e,this.suffix=r,this.outputLen=n,this.enableXOF=i,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,Bn(n),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=PE(this.state)}keccak(){lh||hh(this.state32),jE(this.state32,this.rounds),lh||hh(this.state32),this.posOut=0,this.pos=0}update(e){Qr(this);const{blockLen:r,state:n}=this;e=tn(e);const 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){Qr(this,!1),Fn(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 Bn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ch(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,this.state.fill(0)}_cloneInto(e){const{blockLen:r,suffix:n,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new Bo(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 qE=(t,e,r)=>dh(()=>new Bo(e,t,r)),zE=qE(1,136,256/8),VE="https://rpc.walletconnect.org/v1";function mh(t){const e=`Ethereum Signed Message:
18
18
  ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(zE(r)).toString("hex")}async function KE(t,e,r,n,i,s){switch(r.t){case"eip191":return await HE(t,e,r.s);case"eip1271":return await WE(t,e,r.s,n,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}async function HE(t,e,r){return(await Wb({hash:mh(e),signature:r})).toLowerCase()===t.toLowerCase()}async function WE(t,e,r,n,i,s){const o=Mi(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="0000000000000000000000000000000000000000000000000000000000000041",l=r.substring(2),h=mh(e).substring(2),d=a+h+c+u+l,p=await fetch(`${s||VE}/?chainId=${n}&projectId=${i}`,{method:"POST",body:JSON.stringify({id:GE(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:f}=await p.json();return f?f.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function GE(){return Date.now()+Math.floor(Math.random()*1e3)}function YE(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 A1.encode(s)}var ZE=Object.defineProperty,JE=Object.defineProperties,XE=Object.getOwnPropertyDescriptors,bh=Object.getOwnPropertySymbols,QE=Object.prototype.hasOwnProperty,e2=Object.prototype.propertyIsEnumerable,vh=(t,e,r)=>e in t?ZE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,t2=(t,e)=>{for(var r in e||(e={}))QE.call(e,r)&&vh(t,r,e[r]);if(bh)for(var r of bh(e))e2.call(e,r)&&vh(t,r,e[r]);return t},r2=(t,e)=>JE(t,XE(e));const n2="did:pkh:",Fo=t=>t?.split(":"),i2=t=>{const e=t&&Fo(t);if(e)return t.includes(n2)?e[3]:e[1]},Lo=t=>{const e=t&&Fo(t);if(e)return e[2]+":"+e[3]},zi=t=>{const e=t&&Fo(t);if(e)return e.pop()};async function Eh(t){const{cacao:e,projectId:r}=t,{s:n,p:i}=e,s=_h(i,i.iss),o=zi(i.iss);return await KE(o,s,n,Lo(i.iss),r)}const _h=(t,e)=>{const r=`${t.domain} wants you to sign in with your Ethereum account:`,n=zi(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: ${i2(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,d=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(y=>`
19
19
  - ${y}`).join("")}`:void 0,f=Vi(t.resources);if(f){const y=Un(f);i=f2(i,y)}return[r,n,"",i,"",s,o,a,c,u,l,h,d,p].filter(y=>y!=null).join(`
20
- `)};function s2(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function o2(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function vr(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 a2(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:c2(e,r,n)}}}function c2(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function Sh(t){return vr(t),`urn:recap:${s2(t).replace(/=/g,"")}`}function Un(t){const e=o2(t.replace("urn:recap:",""));return vr(e),e}function u2(t,e,r){const n=a2(t,e,r);return Sh(n)}function l2(t){return t&&t.includes("urn:recap:")}function h2(t,e){const r=Un(t),n=Un(e),i=d2(r,n);return Sh(i)}function d2(t,e){vr(t),vr(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]=r2(t2({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function f2(t="",e){vr(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,d)=>h.action.localeCompare(d.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 xh(t){var e;const r=Un(t);vr(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Ih(t){const e=Un(t);vr(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 Vi(t){if(!t)return;const e=t?.[t.length-1];return l2(e)?e:void 0}function Uo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Dh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function et(t,...e){if(!Dh(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 Oh(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 p2(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 $h(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const ir=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),g2=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function y2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ko(t){if(typeof t=="string")t=y2(t);else if(Dh(t))t=Mo(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function w2(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function m2(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 b2=(t,e)=>{function r(n,...i){if(et(n),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 Ah(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&&!v2(e))throw new Error("invalid output, must be aligned");return e}function Ph(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 v2(t){return t.byteOffset%4===0}function Mo(t){return Uint8Array.from(t)}function tn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Th=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),E2=Th("expand 16-byte k"),_2=Th("expand 32-byte k"),S2=ir(E2),x2=ir(_2);function J(t,e){return t<<e|t>>>32-e}function jo(t){return t.byteOffset%4===0}const Ki=64,I2=16,Rh=2**32-1,Ch=new Uint32Array;function D2(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(Ki),l=ir(u),h=jo(i)&&jo(s),d=h?ir(i):Ch,p=h?ir(s):Ch;for(let f=0;f<c;o++){if(t(e,r,n,l,o,a),o>=Rh)throw new Error("arx: counter overflow");const y=Math.min(Ki,c-f);if(h&&y===Ki){const g=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<I2;w++)m=g+w,p[m]=d[m]^l[w];f+=Ki;continue}for(let g=0,w;g<y;g++)w=f+g,s[w]=i[w]^u[g];f+=y}}function O2(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=w2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Uo(i),Uo(o),$h(s),$h(r),(a,c,u,l,h=0)=>{et(a),et(c),et(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),et(l),Uo(h),h<0||h>=Rh)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const p=[];let f=a.length,y,g;if(f===32)p.push(y=Mo(a)),g=x2;else if(f===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),g=S2,p.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);jo(c)||p.push(c=Mo(c));const w=ir(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,w,ir(c.subarray(0,16)),w),c=c.subarray(16)}const m=16-i;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const E=new Uint8Array(12);E.set(c,s?0:12-c.length),c=E,p.push(c)}const b=ir(c);return D2(t,g,w,b,u,l,h,o),tn(...p),l}}const Te=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class $2{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=ko(e),et(e,32);const r=Te(e,0),n=Te(e,2),i=Te(e,4),s=Te(e,6),o=Te(e,8),a=Te(e,10),c=Te(e,12),u=Te(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]=Te(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],d=o[5],p=o[6],f=o[7],y=o[8],g=o[9],w=Te(e,r+0),m=Te(e,r+2),b=Te(e,r+4),E=Te(e,r+6),$=Te(e,r+8),D=Te(e,r+10),S=Te(e,r+12),A=Te(e,r+14);let x=s[0]+(w&8191),k=s[1]+((w>>>13|m<<3)&8191),C=s[2]+((m>>>10|b<<6)&8191),B=s[3]+((b>>>7|E<<9)&8191),j=s[4]+((E>>>4|$<<12)&8191),I=s[5]+($>>>1&8191),_=s[6]+(($>>>14|D<<2)&8191),v=s[7]+((D>>>11|S<<5)&8191),O=s[8]+((S>>>8|A<<8)&8191),T=s[9]+(A>>>5|i),P=0,N=P+x*a+k*(5*g)+C*(5*y)+B*(5*f)+j*(5*p);P=N>>>13,N&=8191,N+=I*(5*d)+_*(5*h)+v*(5*l)+O*(5*u)+T*(5*c),P+=N>>>13,N&=8191;let F=P+x*c+k*a+C*(5*g)+B*(5*y)+j*(5*f);P=F>>>13,F&=8191,F+=I*(5*p)+_*(5*d)+v*(5*h)+O*(5*l)+T*(5*u),P+=F>>>13,F&=8191;let M=P+x*u+k*c+C*a+B*(5*g)+j*(5*y);P=M>>>13,M&=8191,M+=I*(5*f)+_*(5*p)+v*(5*d)+O*(5*h)+T*(5*l),P+=M>>>13,M&=8191;let z=P+x*l+k*u+C*c+B*a+j*(5*g);P=z>>>13,z&=8191,z+=I*(5*y)+_*(5*f)+v*(5*p)+O*(5*d)+T*(5*h),P+=z>>>13,z&=8191;let q=P+x*h+k*l+C*u+B*c+j*a;P=q>>>13,q&=8191,q+=I*(5*g)+_*(5*y)+v*(5*f)+O*(5*p)+T*(5*d),P+=q>>>13,q&=8191;let V=P+x*d+k*h+C*l+B*u+j*c;P=V>>>13,V&=8191,V+=I*a+_*(5*g)+v*(5*y)+O*(5*f)+T*(5*p),P+=V>>>13,V&=8191;let K=P+x*p+k*d+C*h+B*l+j*u;P=K>>>13,K&=8191,K+=I*c+_*a+v*(5*g)+O*(5*y)+T*(5*f),P+=K>>>13,K&=8191;let ee=P+x*f+k*p+C*d+B*h+j*l;P=ee>>>13,ee&=8191,ee+=I*u+_*c+v*a+O*(5*g)+T*(5*y),P+=ee>>>13,ee&=8191;let G=P+x*y+k*f+C*p+B*d+j*h;P=G>>>13,G&=8191,G+=I*l+_*u+v*c+O*a+T*(5*g),P+=G>>>13,G&=8191;let W=P+x*g+k*y+C*f+B*p+j*d;P=W>>>13,W&=8191,W+=I*h+_*l+v*u+O*c+T*a,P+=W>>>13,W&=8191,P=(P<<2)+P|0,P=P+N|0,N=P&8191,P=P>>>13,F+=P,s[0]=N,s[1]=F,s[2]=M,s[3]=z,s[4]=q,s[5]=V,s[6]=K,s[7]=ee,s[8]=G,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;tn(n)}update(e){Oh(this);const{buffer:r,blockLen:n}=this;e=ko(e);const 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(){tn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Oh(this),p2(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 A2(t){const e=(n,i)=>t(i).update(ko(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const P2=A2(t=>new $2(t));function T2(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],d=e[2],p=e[3],f=e[4],y=e[5],g=e[6],w=e[7],m=i,b=r[0],E=r[1],$=r[2],D=o,S=a,A=c,x=u,k=l,C=h,B=d,j=p,I=f,_=y,v=g,O=w,T=m,P=b,N=E,F=$;for(let z=0;z<s;z+=2)D=D+k|0,T=J(T^D,16),I=I+T|0,k=J(k^I,12),D=D+k|0,T=J(T^D,8),I=I+T|0,k=J(k^I,7),S=S+C|0,P=J(P^S,16),_=_+P|0,C=J(C^_,12),S=S+C|0,P=J(P^S,8),_=_+P|0,C=J(C^_,7),A=A+B|0,N=J(N^A,16),v=v+N|0,B=J(B^v,12),A=A+B|0,N=J(N^A,8),v=v+N|0,B=J(B^v,7),x=x+j|0,F=J(F^x,16),O=O+F|0,j=J(j^O,12),x=x+j|0,F=J(F^x,8),O=O+F|0,j=J(j^O,7),D=D+C|0,F=J(F^D,16),v=v+F|0,C=J(C^v,12),D=D+C|0,F=J(F^D,8),v=v+F|0,C=J(C^v,7),S=S+B|0,T=J(T^S,16),O=O+T|0,B=J(B^O,12),S=S+B|0,T=J(T^S,8),O=O+T|0,B=J(B^O,7),A=A+j|0,P=J(P^A,16),I=I+P|0,j=J(j^I,12),A=A+j|0,P=J(P^A,8),I=I+P|0,j=J(j^I,7),x=x+k|0,N=J(N^x,16),_=_+N|0,k=J(k^_,12),x=x+k|0,N=J(N^x,8),_=_+N|0,k=J(k^_,7);let M=0;n[M++]=o+D|0,n[M++]=a+S|0,n[M++]=c+A|0,n[M++]=u+x|0,n[M++]=l+k|0,n[M++]=h+C|0,n[M++]=d+B|0,n[M++]=p+j|0,n[M++]=f+I|0,n[M++]=y+_|0,n[M++]=g+v|0,n[M++]=w+O|0,n[M++]=m+T|0,n[M++]=b+P|0,n[M++]=E+N|0,n[M++]=$+F|0}const R2=O2(T2,{counterRight:!1,counterLength:4,allowShortKeys:!1}),C2=new Uint8Array(16),Nh=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(C2.subarray(r))},N2=new Uint8Array(32);function Bh(t,e,r,n,i){const s=t(e,r,N2),o=P2.create(s);i&&Nh(o,i),Nh(o,n);const a=new Uint8Array(16),c=g2(a);Ph(c,0,BigInt(i?i.length:0),!0),Ph(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return tn(s,a),u}const B2=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=Ah(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Bh(t,e,r,a,n);return s.set(c,o),tn(c),s},decrypt(i,s){s=Ah(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Bh(t,e,r,o,n);if(!m2(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),tn(c),s}}),Fh=b2({blockSize:64,nonceLength:12,tagLength:16},B2(R2));class Lh extends No{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Ro(e);const n=Qr(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),s.fill(0)}update(e){return Jr(this),this.iHash.update(e),this}digestInto(e){Jr(this),Fn(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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Hi=(t,e,r)=>new Lh(t,e).update(r).digest();Hi.create=(t,e)=>new Lh(t,e);function F2(t,e,r){return Ro(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Hi(t,Qr(r),Qr(e))}const qo=new Uint8Array([0]),Uh=new Uint8Array;function L2(t,e,r,n=32){if(Ro(t),Bn(n),n>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/t.outputLen);r===void 0&&(r=Uh);const s=new Uint8Array(i*t.outputLen),o=Hi.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)qo[0]=u+1,a.update(u===0?Uh:c).update(r).update(qo).digestInto(c),s.set(c,t.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),qo.fill(0),s.slice(0,n)}const U2=(t,e,r,n,i)=>L2(t,F2(t,e,r),n,i);function k2(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 M2(t,e,r){return t&e^~t&r}function j2(t,e,r){return t&e^t&r^e&r}class q2 extends No{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){Jr(this);const{view:r,buffer:n,blockLen:i}=this;e=Qr(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Co(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Jr(this),ch(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;k2(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let 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 z2=new Uint32Array([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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64);class V2 extends q2{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[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 d=or[h-15],p=or[h-2],f=_t(d,7)^_t(d,18)^d>>>3,y=_t(p,17)^_t(p,19)^p>>>10;or[h]=y+or[h-7]+f+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 d=_t(a,6)^_t(a,11)^_t(a,25),p=l+d+M2(a,c,u)+z2[h]+or[h]|0,f=(_t(n,2)^_t(n,13)^_t(n,22))+j2(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+f|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(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const kn=dh(()=>new V2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wi=BigInt(0),Gi=BigInt(1),K2=BigInt(2);function Er(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mn(t){if(!Er(t))throw new Error("Uint8Array expected")}function rn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const H2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function nn(t){Mn(t);let e="";for(let r=0;r<t.length;r++)e+=H2[t[r]];return e}function sn(t){const e=t.toString(16);return e.length&1?"0"+e:e}function zo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Wi:BigInt("0x"+t)}const Lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function kh(t){if(t>=Lt._0&&t<=Lt._9)return t-Lt._0;if(t>=Lt.A&&t<=Lt.F)return t-(Lt.A-10);if(t>=Lt.a&&t<=Lt.f)return t-(Lt.a-10)}function on(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=kh(t.charCodeAt(s)),a=kh(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 _r(t){return zo(nn(t))}function jn(t){return Mn(t),zo(nn(Uint8Array.from(t).reverse()))}function an(t,e){return on(t.toString(16).padStart(e*2,"0"))}function Yi(t,e){return an(t,e).reverse()}function W2(t){return on(sn(t))}function tt(t,e,r){let n;if(typeof e=="string")try{n=on(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Er(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 qn(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Mn(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 G2(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}function Y2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Vo=t=>typeof t=="bigint"&&Wi<=t;function Zi(t,e,r){return Vo(t)&&Vo(e)&&Vo(r)&&e<=t&&t<r}function Ut(t,e,r,n){if(!Zi(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mh(t){let e;for(e=0;t>Wi;t>>=Gi,e+=1);return e}function Z2(t,e){return t>>BigInt(e)&Gi}function J2(t,e,r){return t|(r?Gi:Wi)<<BigInt(e)}const Ko=t=>(K2<<BigInt(t-1))-Gi,Ho=t=>new Uint8Array(t),jh=t=>Uint8Array.from(t);function qh(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=Ho(t),i=Ho(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...l)=>r(i,n,...l),c=(l=Ho())=>{i=a(jh([0]),l),n=a(),l.length!==0&&(i=a(jh([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){n=a();const d=n.slice();h.push(d),l+=n.length}return qn(...h)};return(l,h)=>{o(),c(l);let d;for(;!(d=h(u()));)c();return o(),d}}const X2={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"||Er(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 cn(t,e,r={}){const n=(i,s,o)=>{const a=X2[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}const Q2=()=>{throw new Error("not implemented")};function Wo(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}}var e_=Object.freeze({__proto__:null,isBytes:Er,abytes:Mn,abool:rn,bytesToHex:nn,numberToHexUnpadded:sn,hexToNumber:zo,hexToBytes:on,bytesToNumberBE:_r,bytesToNumberLE:jn,numberToBytesBE:an,numberToBytesLE:Yi,numberToVarBytesBE:W2,ensureBytes:tt,concatBytes:qn,equalBytes:G2,utf8ToBytes:Y2,inRange:Zi,aInRange:Ut,bitLen:Mh,bitGet:Z2,bitSet:J2,bitMask:Ko,createHmacDrbg:qh,validateObject:cn,notImplemented:Q2,memoized:Wo});const Se=BigInt(0),fe=BigInt(1),Sr=BigInt(2),t_=BigInt(3),Go=BigInt(4),zh=BigInt(5),Vh=BigInt(8);function Ye(t,e){const r=t%e;return r>=Se?r:e+r}function Kh(t,e,r){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(r<=Se)throw new Error("invalid modulus");if(r===fe)return Se;let n=fe;for(;e>Se;)e&fe&&(n=n*t%r),t=t*t%r,e>>=fe;return n}function ht(t,e,r){let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function Yo(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let r=Ye(t,e),n=e,i=Se,s=fe;for(;r!==Se;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==fe)throw new Error("invert: does not exist");return Ye(i,e)}function r_(t){const e=(t-fe)/Sr;let r,n,i;for(r=t-fe,n=0;r%Sr===Se;r/=Sr,n++);for(i=Sr;i<t&&Kh(i,e,t)!==t-fe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+fe)/Go;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+fe)/Sr;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 d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,fe<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function n_(t){if(t%Go===t_){const e=(t+fe)/Go;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%Vh===zh){const e=(t-zh)/Vh;return function(r,n){const i=r.mul(n,Sr),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,Sr),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 r_(t)}const i_=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function s_(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=i_.reduce((n,i)=>(n[i]="function",n),e);return cn(t,r)}function o_(t,e,r){if(r<Se)throw new Error("invalid exponent, negatives unsupported");if(r===Se)return t.ONE;if(r===fe)return e;let n=t.ONE,i=e;for(;r>Se;)r&fe&&(n=t.mul(n,i)),i=t.sqr(i),r>>=fe;return n}function a_(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 Hh(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Wh(t,e,r=!1,n={}){if(t<=Se)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Hh(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:Ko(i),ZERO:Se,ONE:fe,create:c=>Ye(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<t},is0:c=>c===Se,isOdd:c=>(c&fe)===fe,neg:c=>Ye(-c,t),eql:(c,u)=>c===u,sqr:c=>Ye(c*c,t),add:(c,u)=>Ye(c+u,t),sub:(c,u)=>Ye(c-u,t),mul:(c,u)=>Ye(c*u,t),pow:(c,u)=>o_(a,c,u),div:(c,u)=>Ye(c*Yo(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,t),sqrt:n.sqrt||(c=>(o||(o=n_(t)),o(a,c))),invertBatch:c=>a_(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Yi(c,s):an(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?jn(c):_r(c)}});return Object.freeze(a)}function Gh(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 Yh(t){const e=Gh(t);return e+Math.ceil(e/2)}function c_(t,e,r=!1){const n=t.length,i=Gh(e),s=Yh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?jn(t):_r(t),a=Ye(o,e-fe)+fe;return r?Yi(a,i):an(a,i)}const Zh=BigInt(0),Ji=BigInt(1);function Zo(t,e){const r=e.negate();return t?r:e}function Jh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Jo(t,e){Jh(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function u_(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 l_(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 Xo=new WeakMap,Xh=new WeakMap;function Qo(t){return Xh.get(t)||1}function h_(t,e){return{constTimeNegate:Zo,hasPrecomputes(r){return Qo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>Zh;)n&Ji&&(i=i.add(s)),s=s.double(),n>>=Ji;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Jo(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}=Jo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=Ji);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(Zo(w,n[y])):a=a.add(Zo(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Jo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===Zh)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=Ji),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=Xo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&Xo.set(n,i(s))),s},wNAFCached(r,n,i){const s=Qo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Qo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Jh(n,e),Xh.set(r,n),Xo.delete(r)}}}function d_(t,e,r,n){if(u_(r,t),l_(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Mh(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Qh(t){return s_(t.Fp),cn(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Hh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const un=BigInt(0),ea=BigInt(1);function f_(t){return cn(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function p_(t){const e=f_(t),{P:r}=e,n=m=>Ye(m,r),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>Kh(m,r-BigInt(2),r));function u(m,b,E){const $=n(m*(b-E));return b=n(b-$),E=n(E+$),[b,E]}const l=(e.a-BigInt(2))/BigInt(4);function h(m,b){Ut("u",m,un,r),Ut("scalar",b,un,r);const E=b,$=m;let D=ea,S=un,A=m,x=ea,k=un,C;for(let j=BigInt(i-1);j>=un;j--){const I=E>>j&ea;k^=I,C=u(k,D,A),D=C[0],A=C[1],C=u(k,S,x),S=C[0],x=C[1],k=I;const _=D+S,v=n(_*_),O=D-S,T=n(O*O),P=v-T,N=A+x,F=A-x,M=n(F*_),z=n(N*O),q=M+z,V=M-z;A=n(q*q),x=n($*n(V*V)),D=n(v*T),S=n(P*(v+n(l*P)))}C=u(k,D,A),D=C[0],A=C[1],C=u(k,S,x),S=C[0],x=C[1];const B=c(S);return n(D*B)}function d(m){return Yi(n(m),s)}function p(m){const b=tt("u coordinate",m,s);return o===32&&(b[31]&=127),jn(b)}function f(m){const b=tt("scalar",m),E=b.length;if(E!==s&&E!==o){let $=""+s+" or "+o;throw new Error("invalid scalar, expected "+$+" bytes, got "+E)}return jn(a(b))}function y(m,b){const E=p(b),$=f(m),D=h(E,$);if(D===un)throw new Error("invalid private or public key received");return d(D)}const g=d(e.Gu);function w(m){return y(m,g)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(m,b)=>y(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:g}}const ta=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const g_=BigInt(1),ed=BigInt(2),y_=BigInt(3),w_=BigInt(5);BigInt(8);function m_(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=ta,o=t*t%s*t%s,a=ht(o,ed,s)*o%s,c=ht(a,g_,s)*t%s,u=ht(c,w_,s)*c%s,l=ht(u,e,s)*u%s,h=ht(l,r,s)*l%s,d=ht(h,n,s)*h%s,p=ht(d,i,s)*d%s,f=ht(p,i,s)*d%s,y=ht(f,e,s)*u%s;return{pow_p_5_8:ht(y,ed,s)*t%s,b2:o}}function b_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ra=p_({P:ta,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=ta,{pow_p_5_8:r,b2:n}=m_(t);return Ye(ht(r,y_,e)*n,e)},adjustScalarBytes:b_,randomBytes:en});function td(t){t.lowS!==void 0&&rn("lowS",t.lowS),t.prehash!==void 0&&rn("prehash",t.prehash)}function v_(t){const e=Qh(t);cn(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:E_,hexToBytes:__}=e_;class S_ extends Error{constructor(e=""){super(e)}}const kt={Err:S_,_tlv:{encode:(t,e)=>{const{Err:r}=kt;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=sn(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?sn(i.length/2|128):"";return sn(t)+s+i+e},decode(t,e){const{Err:r}=kt;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}=kt;if(t<Mt)throw new e("integer: negative integers are not allowed");let r=sn(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}=kt;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 E_(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=kt,i=typeof t=="string"?__(t):t;Mn(i);const{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}=kt,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},Mt=BigInt(0),xe=BigInt(1);BigInt(2);const rd=BigInt(3);BigInt(4);function x_(t){const e=v_(t),{Fp:r}=e,n=Wh(e.n,e.nBitLength),i=e.toBytes||((y,g,w)=>{const m=g.toAffine();return qn(Uint8Array.from([4]),r.toBytes(m.x),r.toBytes(m.y))}),s=e.fromBytes||(y=>{const g=y.subarray(1),w=r.fromBytes(g.subarray(0,r.BYTES)),m=r.fromBytes(g.subarray(r.BYTES,2*r.BYTES));return{x:w,y:m}});function o(y){const{a:g,b:w}=e,m=r.sqr(y),b=r.mul(m,y);return r.add(r.add(b,r.mul(y,g)),w)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Zi(y,xe,e.n)}function c(y){const{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:m,n:b}=e;if(g&&typeof y!="bigint"){if(Er(y)&&(y=nn(y)),typeof y!="string"||!g.includes(y.length))throw new Error("invalid private key");y=y.padStart(w*2,"0")}let E;try{E=typeof y=="bigint"?y:_r(tt("private key",y,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof y)}return m&&(E=Ye(E,b)),Ut("private key",E,xe,b),E}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=Wo((y,g)=>{const{px:w,py:m,pz:b}=y;if(r.eql(b,r.ONE))return{x:w,y:m};const E=y.is0();g==null&&(g=E?r.ONE:r.inv(b));const $=r.mul(w,g),D=r.mul(m,g),S=r.mul(b,g);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),h=Wo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:g,y:w}=y.toAffine();if(!r.isValid(g)||!r.isValid(w))throw new Error("bad point: x or y not FE");const m=r.sqr(w),b=o(g);if(!r.eql(m,b))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,w,m){if(this.px=g,this.py=w,this.pz=m,g==null||!r.isValid(g))throw new Error("x required");if(w==null||!r.isValid(w))throw new Error("y required");if(m==null||!r.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(g){const{x:w,y:m}=g||{};if(!g||!r.isValid(w)||!r.isValid(m))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");const b=E=>r.eql(E,r.ZERO);return b(w)&&b(m)?d.ZERO:new d(w,m,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){const w=r.invertBatch(g.map(m=>m.pz));return g.map((m,b)=>m.toAffine(w[b])).map(d.fromAffine)}static fromHex(g){const w=d.fromAffine(s(tt("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return d_(d,n,g,w)}_setWindowSize(g){f.setWindowSize(this,g)}assertValidity(){h(this)}hasEvenY(){const{y:g}=this.toAffine();if(r.isOdd)return!r.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g,S=r.eql(r.mul(w,D),r.mul(E,b)),A=r.eql(r.mul(m,D),r.mul($,b));return S&&A}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:g,b:w}=e,m=r.mul(w,rd),{px:b,py:E,pz:$}=this;let D=r.ZERO,S=r.ZERO,A=r.ZERO,x=r.mul(b,b),k=r.mul(E,E),C=r.mul($,$),B=r.mul(b,E);return B=r.add(B,B),A=r.mul(b,$),A=r.add(A,A),D=r.mul(g,A),S=r.mul(m,C),S=r.add(D,S),D=r.sub(k,S),S=r.add(k,S),S=r.mul(D,S),D=r.mul(B,D),A=r.mul(m,A),C=r.mul(g,C),B=r.sub(x,C),B=r.mul(g,B),B=r.add(B,A),A=r.add(x,x),x=r.add(A,x),x=r.add(x,C),x=r.mul(x,B),S=r.add(S,x),C=r.mul(E,$),C=r.add(C,C),x=r.mul(C,B),D=r.sub(D,x),A=r.mul(C,k),A=r.add(A,A),A=r.add(A,A),new d(D,S,A)}add(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g;let S=r.ZERO,A=r.ZERO,x=r.ZERO;const k=e.a,C=r.mul(e.b,rd);let B=r.mul(w,E),j=r.mul(m,$),I=r.mul(b,D),_=r.add(w,m),v=r.add(E,$);_=r.mul(_,v),v=r.add(B,j),_=r.sub(_,v),v=r.add(w,b);let O=r.add(E,D);return v=r.mul(v,O),O=r.add(B,I),v=r.sub(v,O),O=r.add(m,b),S=r.add($,D),O=r.mul(O,S),S=r.add(j,I),O=r.sub(O,S),x=r.mul(k,v),S=r.mul(C,I),x=r.add(S,x),S=r.sub(j,x),x=r.add(j,x),A=r.mul(S,x),j=r.add(B,B),j=r.add(j,B),I=r.mul(k,I),v=r.mul(C,v),j=r.add(j,I),I=r.sub(B,I),I=r.mul(k,I),v=r.add(v,I),B=r.mul(j,v),A=r.add(A,B),B=r.mul(O,v),S=r.mul(_,S),S=r.sub(S,B),B=r.mul(_,j),x=r.mul(O,x),x=r.add(x,B),new d(S,A,x)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return f.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){const{endo:w,n:m}=e;Ut("scalar",g,Mt,m);const b=d.ZERO;if(g===Mt)return b;if(this.is0()||g===xe)return this;if(!w||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:E,k1:$,k2neg:D,k2:S}=w.splitScalar(g),A=b,x=b,k=this;for(;$>Mt||S>Mt;)$&xe&&(A=A.add(k)),S&xe&&(x=x.add(k)),k=k.double(),$>>=xe,S>>=xe;return E&&(A=A.negate()),D&&(x=x.negate()),x=new d(r.mul(x.px,w.beta),x.py,x.pz),A.add(x)}multiply(g){const{endo:w,n:m}=e;Ut("scalar",g,xe,m);let b,E;if(w){const{k1neg:$,k1:D,k2neg:S,k2:A}=w.splitScalar(g);let{p:x,f:k}=this.wNAF(D),{p:C,f:B}=this.wNAF(A);x=f.constTimeNegate($,x),C=f.constTimeNegate(S,C),C=new d(r.mul(C.px,w.beta),C.py,C.pz),b=x.add(C),E=k.add(B)}else{const{p:$,f:D}=this.wNAF(g);b=$,E=D}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(g,w,m){const b=d.BASE,E=(D,S)=>S===Mt||S===xe||!D.equals(b)?D.multiplyUnsafe(S):D.multiply(S),$=E(this,w).add(E(g,m));return $.is0()?void 0:$}toAffine(g){return l(this,g)}isTorsionFree(){const{h:g,isTorsionFree:w}=e;if(g===xe)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:g,clearCofactor:w}=e;return g===xe?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return rn("isCompressed",g),this.assertValidity(),i(d,this,g)}toHex(g=!0){return rn("isCompressed",g),nn(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const p=e.nBitLength,f=h_(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function I_(t){const e=Qh(t);return cn(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function D_(t){const e=I_(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(I){return Ye(I,n)}function a(I){return Yo(I,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=x_({...e,toBytes(I,_,v){const O=_.toAffine(),T=r.toBytes(O.x),P=qn;return rn("isCompressed",v),v?P(Uint8Array.from([_.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,r.toBytes(O.y))},fromBytes(I){const _=I.length,v=I[0],O=I.subarray(1);if(_===i&&(v===2||v===3)){const T=_r(O);if(!Zi(T,xe,r.ORDER))throw new Error("Point is not on curve");const P=l(T);let N;try{N=r.sqrt(P)}catch(M){const z=M instanceof Error?": "+M.message:"";throw new Error("Point is not on curve"+z)}const F=(N&xe)===xe;return(v&1)===1!==F&&(N=r.neg(N)),{x:T,y:N}}else if(_===s&&v===4){const T=r.fromBytes(O.subarray(0,r.BYTES)),P=r.fromBytes(O.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}}else{const T=i,P=s;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+P+", got "+_)}}}),d=I=>nn(an(I,e.nByteLength));function p(I){const _=n>>xe;return I>_}function f(I){return p(I)?o(-I):I}const y=(I,_,v)=>_r(I.slice(_,v));class g{constructor(_,v,O){this.r=_,this.s=v,this.recovery=O,this.assertValidity()}static fromCompact(_){const v=e.nByteLength;return _=tt("compactSignature",_,v*2),new g(y(_,0,v),y(_,v,2*v))}static fromDER(_){const{r:v,s:O}=kt.toSig(tt("DER",_));return new g(v,O)}assertValidity(){Ut("r",this.r,xe,n),Ut("s",this.s,xe,n)}addRecoveryBit(_){return new g(this.r,this.s,_)}recoverPublicKey(_){const{r:v,s:O,recovery:T}=this,P=D(tt("msgHash",_));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const N=T===2||T===3?v+e.n:v;if(N>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const F=T&1?"03":"02",M=c.fromHex(F+d(N)),z=a(N),q=o(-P*z),V=o(O*z),K=c.BASE.multiplyAndAddUnsafe(M,q,V);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return on(this.toDERHex())}toDERHex(){return kt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return on(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const I=Yh(e.n);return c_(e.randomBytes(I),e.n)},precompute(I=8,_=c.BASE){return _._setWindowSize(I),_.multiply(BigInt(3)),_}};function m(I,_=!0){return c.fromPrivateKey(I).toRawBytes(_)}function b(I){const _=Er(I),v=typeof I=="string",O=(_||v)&&I.length;return _?O===i||O===s:v?O===2*i||O===2*s:I instanceof c}function E(I,_,v=!0){if(b(I))throw new Error("first arg must be private key");if(!b(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(u(I)).toRawBytes(v)}const $=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const _=_r(I),v=I.length*8-e.nBitLength;return v>0?_>>BigInt(v):_},D=e.bits2int_modN||function(I){return o($(I))},S=Ko(e.nBitLength);function A(I){return Ut("num < 2^"+e.nBitLength,I,Mt,S),an(I,e.nByteLength)}function x(I,_,v=k){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:T}=e;let{lowS:P,prehash:N,extraEntropy:F}=v;P==null&&(P=!0),I=tt("msgHash",I),td(v),N&&(I=tt("prehashed msgHash",O(I)));const M=D(I),z=u(_),q=[A(z),A(M)];if(F!=null&&F!==!1){const G=F===!0?T(r.BYTES):F;q.push(tt("extraEntropy",G))}const V=qn(...q),K=M;function ee(G){const W=$(G);if(!h(W))return;const ye=a(W),ue=c.BASE.multiply(W).toAffine(),le=o(ue.x);if(le===Mt)return;const $e=o(ye*o(K+le*z));if($e===Mt)return;let Me=(ue.x===le?0:2)|Number(ue.y&xe),Kt=$e;return P&&p($e)&&(Kt=f($e),Me^=1),new g(le,Kt,Me)}return{seed:V,k2sig:ee}}const k={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function B(I,_,v=k){const{seed:O,k2sig:T}=x(I,_,v),P=e;return qh(P.hash.outputLen,P.nByteLength,P.hmac)(O,T)}c.BASE._setWindowSize(8);function j(I,_,v,O=C){const T=I;_=tt("msgHash",_),v=tt("publicKey",v);const{lowS:P,prehash:N,format:F}=O;if(td(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const M=typeof T=="string"||Er(T),z=!M&&!F&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!M&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,V;try{if(z&&(q=new g(T.r,T.s)),M){try{F!=="compact"&&(q=g.fromDER(T))}catch($e){if(!($e instanceof kt.Err))throw $e}!q&&F!=="der"&&(q=g.fromCompact(T))}V=c.fromHex(v)}catch{return!1}if(!q||P&&q.hasHighS())return!1;N&&(_=e.hash(_));const{r:K,s:ee}=q,G=D(_),W=a(ee),ye=o(G*W),ue=o(K*W),le=c.BASE.multiplyAndAddUnsafe(V,ye,ue)?.toAffine();return le?o(le.x)===K:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:E,sign:B,verify:j,ProjectivePoint:c,Signature:g,utils:w}}function O_(t){return{hash:t,hmac:(e,...r)=>Hi(t,e,CE(...r)),randomBytes:en}}function $_(t,e){const r=n=>D_({...t,...O_(n)});return{...r(e),create:r}}const nd=Wh(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),A_=nd.create(BigInt("-3")),P_=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),T_=$_({a:A_,b:P_,Fp:nd,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},kn),id="base10",ze="base16",dt="base64pad",ar="base64url",zn="utf8",sd=0,jt=1,Vn=2,R_=0,od=1,Kn=12,na=32;function C_(){const t=ra.utils.randomPrivateKey(),e=ra.getPublicKey(t);return{privateKey:Ge(t,ze),publicKey:Ge(e,ze)}}function ia(){const t=en(na);return Ge(t,ze)}function N_(t,e){const r=ra.getSharedSecret(st(t,ze),st(e,ze)),n=U2(kn,r,void 0,void 0,na);return Ge(n,ze)}function Xi(t){const e=kn(st(t,ze));return Ge(e,ze)}function St(t){const e=kn(st(t,zn));return Ge(e,ze)}function ad(t){return st(`${t}`,id)}function xr(t){return Number(Ge(t,id))}function cd(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ud(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function B_(t){const e=ad(typeof t.type<"u"?t.type:sd);if(xr(e)===jt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?st(t.senderPublicKey,ze):void 0,n=typeof t.iv<"u"?st(t.iv,ze):en(Kn),i=st(t.symKey,ze),s=Fh(i,n).encrypt(st(t.message,zn)),o=ld({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===ar?cd(o):o}function F_(t){const e=st(t.symKey,ze),{sealed:r,iv:n}=Hn({encoded:t.encoded,encoding:t.encoding}),i=Fh(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return Ge(i,zn)}function L_(t,e){const r=ad(Vn),n=en(Kn),i=st(t,zn),s=ld({type:r,sealed:i,iv:n});return e===ar?cd(s):s}function U_(t,e){const{sealed:r}=Hn({encoded:t,encoding:e});return Ge(r,zn)}function ld(t){if(xr(t.type)===Vn)return Ge(Tn([t.type,t.sealed]),dt);if(xr(t.type)===jt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ge(Tn([t.type,t.senderPublicKey,t.iv,t.sealed]),dt)}return Ge(Tn([t.type,t.iv,t.sealed]),dt)}function Hn(t){const e=(t.encoding||dt)===ar?ud(t.encoded):t.encoded,r=st(e,dt),n=r.slice(R_,od),i=od;if(xr(n)===jt){const c=i+na,u=c+Kn,l=r.slice(i,c),h=r.slice(c,u),d=r.slice(u);return{type:n,sealed:d,iv:h,senderPublicKey:l}}if(xr(n)===Vn){const c=r.slice(i),u=en(Kn);return{type:n,sealed:c,iv:u}}const s=i+Kn,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function k_(t,e){const r=Hn({encoded:t,encoding:e?.encoding});return hd({type:xr(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ge(r.senderPublicKey,ze):void 0,receiverPublicKey:e?.receiverPublicKey})}function hd(t){const e=t?.type||sd;if(e===jt){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 dd(t){return t.type===jt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function fd(t){return t.type===Vn}function M_(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return Tn([new Uint8Array([4]),e,r])}function j_(t,e){const[r,n,i]=t.split("."),s=Buffer.from(ud(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=kn(c),l=M_(e);if(!T_.verify(Tn([o,a]),u,l))throw new Error("Invalid signature");return Hs(t).payload}const q_="irn";function Qi(t){return t?.relay||{protocol:q_}}function Wn(t){const e=Yv[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function z_(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 pd(t){if(!t.includes("wc:")){const u=ah(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:V_(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:z_(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function V_(t){return t.startsWith("//")?t.substring(2):t}function K_(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 gd(t){const e=new URLSearchParams,r=K_(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 es(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}function ln(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function H_(t){const e=[];return Object.values(t).forEach(r=>{e.push(...ln(r.accounts))}),e}function W_(t,e){const r=[];return Object.values(t).forEach(n=>{ln(n.accounts).includes(e)&&r.push(...n.methods)}),r}function G_(t,e){const r=[];return Object.values(t).forEach(n=>{ln(n.accounts).includes(e)&&r.push(...n.events)}),r}function Y_(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 yd(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=Y_(e);for(const[n,i]of Object.entries(r))i.methods?i.methods=pE(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}const Z_={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}},J_={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 U(t,e){const{message:r,code:n}=J_[t];return{message:e?`${r} ${e}`:r,code:n}}function oe(t,e){const{message:r,code:n}=Z_[t];return{message:e?`${r} ${e}`:r,code:n}}function Gn(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ts(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Re(t){return typeof t>"u"}function pe(t,e){return e&&Re(t)?!0:typeof t=="string"&&!!t.trim().length}function sa(t,e){return e&&Re(t)?!0:typeof t=="number"&&!isNaN(t)}function X_(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return mr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=ln(a),h=r[o];(!mr(Zl(o,h),l)||!mr(h.methods,c)||!mr(h.events,u))&&(s=!1)}),s):!1}function rs(t){return pe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Q_(t){if(pe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&rs(r)}}return!1}function eS(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(pe(t,!1)){if(e(t))return!0;const r=ah(t);return e(r)}}catch{}return!1}function tS(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function rS(t){return t?.topic}function nS(t,e){let r=null;return pe(t?.publicKey,!1)||(r=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function wd(t){let e=!0;return Gn(t)?t.length&&(e=t.every(r=>pe(r,!1))):e=!1,e}function iS(t,e,r){let n=null;return Gn(e)&&e.length?e.forEach(i=>{n||rs(i)||(n=oe("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):rs(t)||(n=oe("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 sS(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=iS(i,Zl(i,s),`${e} ${r}`);o&&(n=o)}),n}function oS(t,e){let r=null;return Gn(t)?t.forEach(n=>{r||Q_(n)||(r=oe("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=oe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function aS(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=oS(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function cS(t,e){let r=null;return wd(t?.methods)?wd(t?.events)||(r=oe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=oe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function md(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=cS(n,`${e}, namespace`);i&&(r=i)}),r}function uS(t,e,r){let n=null;if(t&&ts(t)){const i=md(t,e);i&&(n=i);const s=sS(t,e,r);s&&(n=s)}else n=U("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function oa(t,e){let r=null;if(t&&ts(t)){const n=md(t,e);n&&(r=n);const i=aS(t,e);i&&(r=i)}else r=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function bd(t){return pe(t.protocol,!0)}function lS(t,e){let r=!1;return e&&!t?r=!0:t&&Gn(t)&&t.length&&t.forEach(n=>{r=bd(n)}),r}function hS(t){return typeof t=="number"}function Ze(t){return typeof t<"u"&&typeof t!==null}function dS(t){return!(!t||typeof t!="object"||!t.code||!sa(t.code,!1)||!t.message||!pe(t.message,!1))}function fS(t){return!(Re(t)||!pe(t.method,!1))}function pS(t){return!(Re(t)||Re(t.result)&&Re(t.error)||!sa(t.id,!1)||!pe(t.jsonrpc,!1))}function gS(t){return!(Re(t)||!pe(t.name,!1))}function vd(t,e){return!(!rs(e)||!H_(t).includes(e))}function yS(t,e,r){return pe(r,!1)?W_(t,e).includes(r):!1}function wS(t,e,r){return pe(r,!1)?G_(t,e).includes(r):!1}function Ed(t,e,r){let n=null;const i=mS(t),s=bS(e),o=Object.keys(i),a=Object.keys(s),c=_d(Object.keys(t)),u=_d(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
20
+ `)};function s2(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function o2(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function _r(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 a2(t,e,r,n={}){return r?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:c2(e,r,n)}}}function c2(t,e,r={}){e=e?.sort((i,s)=>i.localeCompare(s));const n=e.map(i=>({[`${t}/${i}`]:[r]}));return Object.assign({},...n)}function Sh(t){return _r(t),`urn:recap:${s2(t).replace(/=/g,"")}`}function Un(t){const e=o2(t.replace("urn:recap:",""));return _r(e),e}function u2(t,e,r){const n=a2(t,e,r);return Sh(n)}function l2(t){return t&&t.includes("urn:recap:")}function h2(t,e){const r=Un(t),n=Un(e),i=d2(r,n);return Sh(i)}function d2(t,e){_r(t),_r(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]=r2(t2({},n.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),n}function f2(t="",e){_r(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,d)=>h.action.localeCompare(d.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 xh(t){var e;const r=Un(t);_r(r);const n=(e=r.att)==null?void 0:e.eip155;return n?Object.keys(n).map(i=>i.split("/")[1]):[]}function Ih(t){const e=Un(t);_r(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 Vi(t){if(!t)return;const e=t?.[t.length-1];return l2(e)?e:void 0}function Uo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Dh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function et(t,...e){if(!Dh(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 Oh(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 p2(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 $h(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}const ir=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4)),g2=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);if(!(new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68))throw new Error("Non little-endian hardware is not supported");function y2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ko(t){if(typeof t=="string")t=y2(t);else if(Dh(t))t=Mo(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function w2(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function m2(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 b2=(t,e)=>{function r(n,...i){if(et(n),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 Ah(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&&!v2(e))throw new Error("invalid output, must be aligned");return e}function Ph(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 v2(t){return t.byteOffset%4===0}function Mo(t){return Uint8Array.from(t)}function nn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}const Th=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),E2=Th("expand 16-byte k"),_2=Th("expand 32-byte k"),S2=ir(E2),x2=ir(_2);function J(t,e){return t<<e|t>>>32-e}function jo(t){return t.byteOffset%4===0}const Ki=64,I2=16,Rh=2**32-1,Ch=new Uint32Array;function D2(t,e,r,n,i,s,o,a){const c=i.length,u=new Uint8Array(Ki),l=ir(u),h=jo(i)&&jo(s),d=h?ir(i):Ch,p=h?ir(s):Ch;for(let f=0;f<c;o++){if(t(e,r,n,l,o,a),o>=Rh)throw new Error("arx: counter overflow");const y=Math.min(Ki,c-f);if(h&&y===Ki){const g=f/4;if(f%4!==0)throw new Error("arx: invalid block position");for(let w=0,m;w<I2;w++)m=g+w,p[m]=d[m]^l[w];f+=Ki;continue}for(let g=0,w;g<y;g++)w=f+g,s[w]=i[w]^u[g];f+=y}}function O2(t,e){const{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:s,rounds:o}=w2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Uo(i),Uo(o),$h(s),$h(r),(a,c,u,l,h=0)=>{et(a),et(c),et(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),et(l),Uo(h),h<0||h>=Rh)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const p=[];let f=a.length,y,g;if(f===32)p.push(y=Mo(a)),g=x2;else if(f===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),g=S2,p.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${f}`);jo(c)||p.push(c=Mo(c));const w=ir(y);if(n){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");n(g,w,ir(c.subarray(0,16)),w),c=c.subarray(16)}const m=16-i;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const E=new Uint8Array(12);E.set(c,s?0:12-c.length),c=E,p.push(c)}const b=ir(c);return D2(t,g,w,b,u,l,h,o),nn(...p),l}}const Te=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class $2{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=ko(e),et(e,32);const r=Te(e,0),n=Te(e,2),i=Te(e,4),s=Te(e,6),o=Te(e,8),a=Te(e,10),c=Te(e,12),u=Te(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]=Te(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],d=o[5],p=o[6],f=o[7],y=o[8],g=o[9],w=Te(e,r+0),m=Te(e,r+2),b=Te(e,r+4),E=Te(e,r+6),$=Te(e,r+8),D=Te(e,r+10),S=Te(e,r+12),A=Te(e,r+14);let x=s[0]+(w&8191),k=s[1]+((w>>>13|m<<3)&8191),C=s[2]+((m>>>10|b<<6)&8191),B=s[3]+((b>>>7|E<<9)&8191),j=s[4]+((E>>>4|$<<12)&8191),I=s[5]+($>>>1&8191),_=s[6]+(($>>>14|D<<2)&8191),v=s[7]+((D>>>11|S<<5)&8191),O=s[8]+((S>>>8|A<<8)&8191),T=s[9]+(A>>>5|i),P=0,N=P+x*a+k*(5*g)+C*(5*y)+B*(5*f)+j*(5*p);P=N>>>13,N&=8191,N+=I*(5*d)+_*(5*h)+v*(5*l)+O*(5*u)+T*(5*c),P+=N>>>13,N&=8191;let F=P+x*c+k*a+C*(5*g)+B*(5*y)+j*(5*f);P=F>>>13,F&=8191,F+=I*(5*p)+_*(5*d)+v*(5*h)+O*(5*l)+T*(5*u),P+=F>>>13,F&=8191;let M=P+x*u+k*c+C*a+B*(5*g)+j*(5*y);P=M>>>13,M&=8191,M+=I*(5*f)+_*(5*p)+v*(5*d)+O*(5*h)+T*(5*l),P+=M>>>13,M&=8191;let z=P+x*l+k*u+C*c+B*a+j*(5*g);P=z>>>13,z&=8191,z+=I*(5*y)+_*(5*f)+v*(5*p)+O*(5*d)+T*(5*h),P+=z>>>13,z&=8191;let q=P+x*h+k*l+C*u+B*c+j*a;P=q>>>13,q&=8191,q+=I*(5*g)+_*(5*y)+v*(5*f)+O*(5*p)+T*(5*d),P+=q>>>13,q&=8191;let V=P+x*d+k*h+C*l+B*u+j*c;P=V>>>13,V&=8191,V+=I*a+_*(5*g)+v*(5*y)+O*(5*f)+T*(5*p),P+=V>>>13,V&=8191;let K=P+x*p+k*d+C*h+B*l+j*u;P=K>>>13,K&=8191,K+=I*c+_*a+v*(5*g)+O*(5*y)+T*(5*f),P+=K>>>13,K&=8191;let ee=P+x*f+k*p+C*d+B*h+j*l;P=ee>>>13,ee&=8191,ee+=I*u+_*c+v*a+O*(5*g)+T*(5*y),P+=ee>>>13,ee&=8191;let G=P+x*y+k*f+C*p+B*d+j*h;P=G>>>13,G&=8191,G+=I*l+_*u+v*c+O*a+T*(5*g),P+=G>>>13,G&=8191;let W=P+x*g+k*y+C*f+B*p+j*d;P=W>>>13,W&=8191,W+=I*h+_*l+v*u+O*c+T*a,P+=W>>>13,W&=8191,P=(P<<2)+P|0,P=P+N|0,N=P&8191,P=P>>>13,F+=P,s[0]=N,s[1]=F,s[2]=M,s[3]=z,s[4]=q,s[5]=V,s[6]=K,s[7]=ee,s[8]=G,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;nn(n)}update(e){Oh(this);const{buffer:r,blockLen:n}=this;e=ko(e);const 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(){nn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Oh(this),p2(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 A2(t){const e=(n,i)=>t(i).update(ko(n)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=n=>t(n),e}const P2=A2(t=>new $2(t));function T2(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],d=e[2],p=e[3],f=e[4],y=e[5],g=e[6],w=e[7],m=i,b=r[0],E=r[1],$=r[2],D=o,S=a,A=c,x=u,k=l,C=h,B=d,j=p,I=f,_=y,v=g,O=w,T=m,P=b,N=E,F=$;for(let z=0;z<s;z+=2)D=D+k|0,T=J(T^D,16),I=I+T|0,k=J(k^I,12),D=D+k|0,T=J(T^D,8),I=I+T|0,k=J(k^I,7),S=S+C|0,P=J(P^S,16),_=_+P|0,C=J(C^_,12),S=S+C|0,P=J(P^S,8),_=_+P|0,C=J(C^_,7),A=A+B|0,N=J(N^A,16),v=v+N|0,B=J(B^v,12),A=A+B|0,N=J(N^A,8),v=v+N|0,B=J(B^v,7),x=x+j|0,F=J(F^x,16),O=O+F|0,j=J(j^O,12),x=x+j|0,F=J(F^x,8),O=O+F|0,j=J(j^O,7),D=D+C|0,F=J(F^D,16),v=v+F|0,C=J(C^v,12),D=D+C|0,F=J(F^D,8),v=v+F|0,C=J(C^v,7),S=S+B|0,T=J(T^S,16),O=O+T|0,B=J(B^O,12),S=S+B|0,T=J(T^S,8),O=O+T|0,B=J(B^O,7),A=A+j|0,P=J(P^A,16),I=I+P|0,j=J(j^I,12),A=A+j|0,P=J(P^A,8),I=I+P|0,j=J(j^I,7),x=x+k|0,N=J(N^x,16),_=_+N|0,k=J(k^_,12),x=x+k|0,N=J(N^x,8),_=_+N|0,k=J(k^_,7);let M=0;n[M++]=o+D|0,n[M++]=a+S|0,n[M++]=c+A|0,n[M++]=u+x|0,n[M++]=l+k|0,n[M++]=h+C|0,n[M++]=d+B|0,n[M++]=p+j|0,n[M++]=f+I|0,n[M++]=y+_|0,n[M++]=g+v|0,n[M++]=w+O|0,n[M++]=m+T|0,n[M++]=b+P|0,n[M++]=E+N|0,n[M++]=$+F|0}const R2=O2(T2,{counterRight:!1,counterLength:4,allowShortKeys:!1}),C2=new Uint8Array(16),Nh=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(C2.subarray(r))},N2=new Uint8Array(32);function Bh(t,e,r,n,i){const s=t(e,r,N2),o=P2.create(s);i&&Nh(o,i),Nh(o,n);const a=new Uint8Array(16),c=g2(a);Ph(c,0,BigInt(i?i.length:0),!0),Ph(c,8,BigInt(n.length),!0),o.update(a);const u=o.digest();return nn(s,a),u}const B2=t=>(e,r,n)=>({encrypt(i,s){const o=i.length;s=Ah(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Bh(t,e,r,a,n);return s.set(c,o),nn(c),s},decrypt(i,s){s=Ah(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Bh(t,e,r,o,n);if(!m2(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,r,s,s,1),nn(c),s}}),Fh=b2({blockSize:64,nonceLength:12,tagLength:16},B2(R2));class Lh extends No{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Ro(e);const n=tn(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),s.fill(0)}update(e){return Qr(this),this.iHash.update(e),this}digestInto(e){Qr(this),Fn(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}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Hi=(t,e,r)=>new Lh(t,e).update(r).digest();Hi.create=(t,e)=>new Lh(t,e);function F2(t,e,r){return Ro(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Hi(t,tn(r),tn(e))}const qo=new Uint8Array([0]),Uh=new Uint8Array;function L2(t,e,r,n=32){if(Ro(t),Bn(n),n>255*t.outputLen)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(n/t.outputLen);r===void 0&&(r=Uh);const s=new Uint8Array(i*t.outputLen),o=Hi.create(t,e),a=o._cloneInto(),c=new Uint8Array(o.outputLen);for(let u=0;u<i;u++)qo[0]=u+1,a.update(u===0?Uh:c).update(r).update(qo).digestInto(c),s.set(c,t.outputLen*u),o._cloneInto(a);return o.destroy(),a.destroy(),c.fill(0),qo.fill(0),s.slice(0,n)}const U2=(t,e,r,n,i)=>L2(t,F2(t,e,r),n,i);function k2(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 M2(t,e,r){return t&e^~t&r}function j2(t,e,r){return t&e^t&r^e&r}class q2 extends No{constructor(e,r,n,i){super(),this.blockLen=e,this.outputLen=r,this.padOffset=n,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){Qr(this);const{view:r,buffer:n,blockLen:i}=this;e=tn(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Co(e);for(;i<=s-o;o+=i)this.process(c,o);continue}n.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Qr(this),ch(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;k2(n,i-8,BigInt(this.length*8),s),this.process(n,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let 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 z2=new Uint32Array([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]),sr=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),or=new Uint32Array(64);class V2 extends q2{constructor(){super(64,32,8,!1),this.A=sr[0]|0,this.B=sr[1]|0,this.C=sr[2]|0,this.D=sr[3]|0,this.E=sr[4]|0,this.F=sr[5]|0,this.G=sr[6]|0,this.H=sr[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 d=or[h-15],p=or[h-2],f=_t(d,7)^_t(d,18)^d>>>3,y=_t(p,17)^_t(p,19)^p>>>10;or[h]=y+or[h-7]+f+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 d=_t(a,6)^_t(a,11)^_t(a,25),p=l+d+M2(a,c,u)+z2[h]+or[h]|0,f=(_t(n,2)^_t(n,13)^_t(n,22))+j2(n,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=n,n=p+f|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(){or.fill(0)}destroy(){this.set(0,0,0,0,0,0,0,0),this.buffer.fill(0)}}const kn=dh(()=>new V2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wi=BigInt(0),Gi=BigInt(1),K2=BigInt(2);function Sr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mn(t){if(!Sr(t))throw new Error("Uint8Array expected")}function sn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const H2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function on(t){Mn(t);let e="";for(let r=0;r<t.length;r++)e+=H2[t[r]];return e}function an(t){const e=t.toString(16);return e.length&1?"0"+e:e}function zo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Wi:BigInt("0x"+t)}const Lt={_0:48,_9:57,A:65,F:70,a:97,f:102};function kh(t){if(t>=Lt._0&&t<=Lt._9)return t-Lt._0;if(t>=Lt.A&&t<=Lt.F)return t-(Lt.A-10);if(t>=Lt.a&&t<=Lt.f)return t-(Lt.a-10)}function cn(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=kh(t.charCodeAt(s)),a=kh(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 xr(t){return zo(on(t))}function jn(t){return Mn(t),zo(on(Uint8Array.from(t).reverse()))}function un(t,e){return cn(t.toString(16).padStart(e*2,"0"))}function Yi(t,e){return un(t,e).reverse()}function W2(t){return cn(an(t))}function tt(t,e,r){let n;if(typeof e=="string")try{n=cn(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Sr(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 qn(...t){let e=0;for(let n=0;n<t.length;n++){const i=t[n];Mn(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 G2(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}function Y2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Vo=t=>typeof t=="bigint"&&Wi<=t;function Zi(t,e,r){return Vo(t)&&Vo(e)&&Vo(r)&&e<=t&&t<r}function Ut(t,e,r,n){if(!Zi(e,r,n))throw new Error("expected valid "+t+": "+r+" <= n < "+n+", got "+e)}function Mh(t){let e;for(e=0;t>Wi;t>>=Gi,e+=1);return e}function Z2(t,e){return t>>BigInt(e)&Gi}function J2(t,e,r){return t|(r?Gi:Wi)<<BigInt(e)}const Ko=t=>(K2<<BigInt(t-1))-Gi,Ho=t=>new Uint8Array(t),jh=t=>Uint8Array.from(t);function qh(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=Ho(t),i=Ho(t),s=0;const o=()=>{n.fill(1),i.fill(0),s=0},a=(...l)=>r(i,n,...l),c=(l=Ho())=>{i=a(jh([0]),l),n=a(),l.length!==0&&(i=a(jh([1]),l),n=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let l=0;const h=[];for(;l<e;){n=a();const d=n.slice();h.push(d),l+=n.length}return qn(...h)};return(l,h)=>{o(),c(l);let d;for(;!(d=h(u()));)c();return o(),d}}const X2={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"||Sr(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 ln(t,e,r={}){const n=(i,s,o)=>{const a=X2[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}const Q2=()=>{throw new Error("not implemented")};function Wo(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}}var e_=Object.freeze({__proto__:null,isBytes:Sr,abytes:Mn,abool:sn,bytesToHex:on,numberToHexUnpadded:an,hexToNumber:zo,hexToBytes:cn,bytesToNumberBE:xr,bytesToNumberLE:jn,numberToBytesBE:un,numberToBytesLE:Yi,numberToVarBytesBE:W2,ensureBytes:tt,concatBytes:qn,equalBytes:G2,utf8ToBytes:Y2,inRange:Zi,aInRange:Ut,bitLen:Mh,bitGet:Z2,bitSet:J2,bitMask:Ko,createHmacDrbg:qh,validateObject:ln,notImplemented:Q2,memoized:Wo});const Se=BigInt(0),fe=BigInt(1),Ir=BigInt(2),t_=BigInt(3),Go=BigInt(4),zh=BigInt(5),Vh=BigInt(8);function Ye(t,e){const r=t%e;return r>=Se?r:e+r}function Kh(t,e,r){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(r<=Se)throw new Error("invalid modulus");if(r===fe)return Se;let n=fe;for(;e>Se;)e&fe&&(n=n*t%r),t=t*t%r,e>>=fe;return n}function ht(t,e,r){let n=t;for(;e-- >Se;)n*=n,n%=r;return n}function Yo(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let r=Ye(t,e),n=e,i=Se,s=fe;for(;r!==Se;){const o=n/r,a=n%r,c=i-s*o;n=r,r=a,i=s,s=c}if(n!==fe)throw new Error("invert: does not exist");return Ye(i,e)}function r_(t){const e=(t-fe)/Ir;let r,n,i;for(r=t-fe,n=0;r%Ir===Se;r/=Ir,n++);for(i=Ir;i<t&&Kh(i,e,t)!==t-fe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(n===1){const o=(t+fe)/Go;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+fe)/Ir;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 d=1;for(let f=o.sqr(h);d<c&&!o.eql(f,o.ONE);d++)f=o.sqr(f);const p=o.pow(u,fe<<BigInt(c-d-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=d}return l}}function n_(t){if(t%Go===t_){const e=(t+fe)/Go;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%Vh===zh){const e=(t-zh)/Vh;return function(r,n){const i=r.mul(n,Ir),s=r.pow(i,e),o=r.mul(n,s),a=r.mul(r.mul(o,Ir),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 r_(t)}const i_=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function s_(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=i_.reduce((n,i)=>(n[i]="function",n),e);return ln(t,r)}function o_(t,e,r){if(r<Se)throw new Error("invalid exponent, negatives unsupported");if(r===Se)return t.ONE;if(r===fe)return e;let n=t.ONE,i=e;for(;r>Se;)r&fe&&(n=t.mul(n,i)),i=t.sqr(i),r>>=fe;return n}function a_(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 Hh(t,e){const r=e!==void 0?e:t.toString(2).length,n=Math.ceil(r/8);return{nBitLength:r,nByteLength:n}}function Wh(t,e,r=!1,n={}){if(t<=Se)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Hh(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:Ko(i),ZERO:Se,ONE:fe,create:c=>Ye(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<t},is0:c=>c===Se,isOdd:c=>(c&fe)===fe,neg:c=>Ye(-c,t),eql:(c,u)=>c===u,sqr:c=>Ye(c*c,t),add:(c,u)=>Ye(c+u,t),sub:(c,u)=>Ye(c-u,t),mul:(c,u)=>Ye(c*u,t),pow:(c,u)=>o_(a,c,u),div:(c,u)=>Ye(c*Yo(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Yo(c,t),sqrt:n.sqrt||(c=>(o||(o=n_(t)),o(a,c))),invertBatch:c=>a_(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Yi(c,s):un(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?jn(c):xr(c)}});return Object.freeze(a)}function Gh(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 Yh(t){const e=Gh(t);return e+Math.ceil(e/2)}function c_(t,e,r=!1){const n=t.length,i=Gh(e),s=Yh(e);if(n<16||n<s||n>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+n);const o=r?jn(t):xr(t),a=Ye(o,e-fe)+fe;return r?Yi(a,i):un(a,i)}const Zh=BigInt(0),Ji=BigInt(1);function Zo(t,e){const r=e.negate();return t?r:e}function Jh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Jo(t,e){Jh(t,e);const r=Math.ceil(e/t)+1,n=2**(t-1);return{windows:r,windowSize:n}}function u_(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 l_(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 Xo=new WeakMap,Xh=new WeakMap;function Qo(t){return Xh.get(t)||1}function h_(t,e){return{constTimeNegate:Zo,hasPrecomputes(r){return Qo(r)!==1},unsafeLadder(r,n,i=t.ZERO){let s=r;for(;n>Zh;)n&Ji&&(i=i.add(s)),s=s.double(),n>>=Ji;return i},precomputeWindow(r,n){const{windows:i,windowSize:s}=Jo(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}=Jo(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let d=0;d<s;d++){const p=d*o;let f=Number(i&u);i>>=h,f>o&&(f-=l,i+=Ji);const y=p,g=p+Math.abs(f)-1,w=d%2!==0,m=f<0;f===0?c=c.add(Zo(w,n[y])):a=a.add(Zo(m,n[g]))}return{p:a,f:c}},wNAFUnsafe(r,n,i,s=t.ZERO){const{windows:o,windowSize:a}=Jo(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const d=h*a;if(i===Zh)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=Ji),p===0)continue;let f=n[d+Math.abs(p)-1];p<0&&(f=f.negate()),s=s.add(f)}return s},getPrecomputes(r,n,i){let s=Xo.get(n);return s||(s=this.precomputeWindow(n,r),r!==1&&Xo.set(n,i(s))),s},wNAFCached(r,n,i){const s=Qo(r);return this.wNAF(s,this.getPrecomputes(s,r,i),n)},wNAFCachedUnsafe(r,n,i,s){const o=Qo(r);return o===1?this.unsafeLadder(r,n,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,i),n,s)},setWindowSize(r,n){Jh(n,e),Xh.set(r,n),Xo.delete(r)}}}function d_(t,e,r,n){if(u_(r,t),l_(n,e),r.length!==n.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Mh(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 f=n[p],y=Number(f>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let d=i;for(let p=c.length-1,f=i;p>0;p--)f=f.add(c[p]),d=d.add(f);if(l=l.add(d),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function Qh(t){return s_(t.Fp),ln(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Hh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const hn=BigInt(0),ea=BigInt(1);function f_(t){return ln(t,{a:"bigint"},{montgomeryBits:"isSafeInteger",nByteLength:"isSafeInteger",adjustScalarBytes:"function",domain:"function",powPminus2:"function",Gu:"bigint"}),Object.freeze({...t})}function p_(t){const e=f_(t),{P:r}=e,n=m=>Ye(m,r),i=e.montgomeryBits,s=Math.ceil(i/8),o=e.nByteLength,a=e.adjustScalarBytes||(m=>m),c=e.powPminus2||(m=>Kh(m,r-BigInt(2),r));function u(m,b,E){const $=n(m*(b-E));return b=n(b-$),E=n(E+$),[b,E]}const l=(e.a-BigInt(2))/BigInt(4);function h(m,b){Ut("u",m,hn,r),Ut("scalar",b,hn,r);const E=b,$=m;let D=ea,S=hn,A=m,x=ea,k=hn,C;for(let j=BigInt(i-1);j>=hn;j--){const I=E>>j&ea;k^=I,C=u(k,D,A),D=C[0],A=C[1],C=u(k,S,x),S=C[0],x=C[1],k=I;const _=D+S,v=n(_*_),O=D-S,T=n(O*O),P=v-T,N=A+x,F=A-x,M=n(F*_),z=n(N*O),q=M+z,V=M-z;A=n(q*q),x=n($*n(V*V)),D=n(v*T),S=n(P*(v+n(l*P)))}C=u(k,D,A),D=C[0],A=C[1],C=u(k,S,x),S=C[0],x=C[1];const B=c(S);return n(D*B)}function d(m){return Yi(n(m),s)}function p(m){const b=tt("u coordinate",m,s);return o===32&&(b[31]&=127),jn(b)}function f(m){const b=tt("scalar",m),E=b.length;if(E!==s&&E!==o){let $=""+s+" or "+o;throw new Error("invalid scalar, expected "+$+" bytes, got "+E)}return jn(a(b))}function y(m,b){const E=p(b),$=f(m),D=h(E,$);if(D===hn)throw new Error("invalid private or public key received");return d(D)}const g=d(e.Gu);function w(m){return y(m,g)}return{scalarMult:y,scalarMultBase:w,getSharedSecret:(m,b)=>y(m,b),getPublicKey:m=>w(m),utils:{randomPrivateKey:()=>e.randomBytes(e.nByteLength)},GuBytes:g}}const ta=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949");BigInt(0);const g_=BigInt(1),ed=BigInt(2),y_=BigInt(3),w_=BigInt(5);BigInt(8);function m_(t){const e=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),s=ta,o=t*t%s*t%s,a=ht(o,ed,s)*o%s,c=ht(a,g_,s)*t%s,u=ht(c,w_,s)*c%s,l=ht(u,e,s)*u%s,h=ht(l,r,s)*l%s,d=ht(h,n,s)*h%s,p=ht(d,i,s)*d%s,f=ht(p,i,s)*d%s,y=ht(f,e,s)*u%s;return{pow_p_5_8:ht(y,ed,s)*t%s,b2:o}}function b_(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ra=p_({P:ta,a:BigInt(486662),montgomeryBits:255,nByteLength:32,Gu:BigInt(9),powPminus2:t=>{const e=ta,{pow_p_5_8:r,b2:n}=m_(t);return Ye(ht(r,y_,e)*n,e)},adjustScalarBytes:b_,randomBytes:rn});function td(t){t.lowS!==void 0&&sn("lowS",t.lowS),t.prehash!==void 0&&sn("prehash",t.prehash)}function v_(t){const e=Qh(t);ln(e,{a:"field",b:"field"},{allowedPrivateKeyLengths:"array",wrapPrivateKey:"boolean",isTorsionFree:"function",clearCofactor:"function",allowInfinityPoint:"boolean",fromBytes:"function",toBytes:"function"});const{endo:r,Fp:n,a:i}=e;if(r){if(!n.eql(i,n.ZERO))throw new Error("invalid endomorphism, can only be defined for Koblitz curves that have a=0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error("invalid endomorphism, expected beta: bigint and splitScalar: function")}return Object.freeze({...e})}const{bytesToNumberBE:E_,hexToBytes:__}=e_;class S_ extends Error{constructor(e=""){super(e)}}const kt={Err:S_,_tlv:{encode:(t,e)=>{const{Err:r}=kt;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=an(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");const s=n>127?an(i.length/2|128):"";return an(t)+s+i+e},decode(t,e){const{Err:r}=kt;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}=kt;if(t<Mt)throw new e("integer: negative integers are not allowed");let r=an(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}=kt;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 E_(t)}},toSig(t){const{Err:e,_int:r,_tlv:n}=kt,i=typeof t=="string"?__(t):t;Mn(i);const{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}=kt,n=e.encode(2,r.encode(t.r)),i=e.encode(2,r.encode(t.s)),s=n+i;return e.encode(48,s)}},Mt=BigInt(0),xe=BigInt(1);BigInt(2);const rd=BigInt(3);BigInt(4);function x_(t){const e=v_(t),{Fp:r}=e,n=Wh(e.n,e.nBitLength),i=e.toBytes||((y,g,w)=>{const m=g.toAffine();return qn(Uint8Array.from([4]),r.toBytes(m.x),r.toBytes(m.y))}),s=e.fromBytes||(y=>{const g=y.subarray(1),w=r.fromBytes(g.subarray(0,r.BYTES)),m=r.fromBytes(g.subarray(r.BYTES,2*r.BYTES));return{x:w,y:m}});function o(y){const{a:g,b:w}=e,m=r.sqr(y),b=r.mul(m,y);return r.add(r.add(b,r.mul(y,g)),w)}if(!r.eql(r.sqr(e.Gy),o(e.Gx)))throw new Error("bad generator point: equation left != right");function a(y){return Zi(y,xe,e.n)}function c(y){const{allowedPrivateKeyLengths:g,nByteLength:w,wrapPrivateKey:m,n:b}=e;if(g&&typeof y!="bigint"){if(Sr(y)&&(y=on(y)),typeof y!="string"||!g.includes(y.length))throw new Error("invalid private key");y=y.padStart(w*2,"0")}let E;try{E=typeof y=="bigint"?y:xr(tt("private key",y,w))}catch{throw new Error("invalid private key, expected hex or "+w+" bytes, got "+typeof y)}return m&&(E=Ye(E,b)),Ut("private key",E,xe,b),E}function u(y){if(!(y instanceof d))throw new Error("ProjectivePoint expected")}const l=Wo((y,g)=>{const{px:w,py:m,pz:b}=y;if(r.eql(b,r.ONE))return{x:w,y:m};const E=y.is0();g==null&&(g=E?r.ONE:r.inv(b));const $=r.mul(w,g),D=r.mul(m,g),S=r.mul(b,g);if(E)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:$,y:D}}),h=Wo(y=>{if(y.is0()){if(e.allowInfinityPoint&&!r.is0(y.py))return;throw new Error("bad point: ZERO")}const{x:g,y:w}=y.toAffine();if(!r.isValid(g)||!r.isValid(w))throw new Error("bad point: x or y not FE");const m=r.sqr(w),b=o(g);if(!r.eql(m,b))throw new Error("bad point: equation left != right");if(!y.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class d{constructor(g,w,m){if(this.px=g,this.py=w,this.pz=m,g==null||!r.isValid(g))throw new Error("x required");if(w==null||!r.isValid(w))throw new Error("y required");if(m==null||!r.isValid(m))throw new Error("z required");Object.freeze(this)}static fromAffine(g){const{x:w,y:m}=g||{};if(!g||!r.isValid(w)||!r.isValid(m))throw new Error("invalid affine point");if(g instanceof d)throw new Error("projective point not allowed");const b=E=>r.eql(E,r.ZERO);return b(w)&&b(m)?d.ZERO:new d(w,m,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(g){const w=r.invertBatch(g.map(m=>m.pz));return g.map((m,b)=>m.toAffine(w[b])).map(d.fromAffine)}static fromHex(g){const w=d.fromAffine(s(tt("pointHex",g)));return w.assertValidity(),w}static fromPrivateKey(g){return d.BASE.multiply(c(g))}static msm(g,w){return d_(d,n,g,w)}_setWindowSize(g){f.setWindowSize(this,g)}assertValidity(){h(this)}hasEvenY(){const{y:g}=this.toAffine();if(r.isOdd)return!r.isOdd(g);throw new Error("Field doesn't support isOdd")}equals(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g,S=r.eql(r.mul(w,D),r.mul(E,b)),A=r.eql(r.mul(m,D),r.mul($,b));return S&&A}negate(){return new d(this.px,r.neg(this.py),this.pz)}double(){const{a:g,b:w}=e,m=r.mul(w,rd),{px:b,py:E,pz:$}=this;let D=r.ZERO,S=r.ZERO,A=r.ZERO,x=r.mul(b,b),k=r.mul(E,E),C=r.mul($,$),B=r.mul(b,E);return B=r.add(B,B),A=r.mul(b,$),A=r.add(A,A),D=r.mul(g,A),S=r.mul(m,C),S=r.add(D,S),D=r.sub(k,S),S=r.add(k,S),S=r.mul(D,S),D=r.mul(B,D),A=r.mul(m,A),C=r.mul(g,C),B=r.sub(x,C),B=r.mul(g,B),B=r.add(B,A),A=r.add(x,x),x=r.add(A,x),x=r.add(x,C),x=r.mul(x,B),S=r.add(S,x),C=r.mul(E,$),C=r.add(C,C),x=r.mul(C,B),D=r.sub(D,x),A=r.mul(C,k),A=r.add(A,A),A=r.add(A,A),new d(D,S,A)}add(g){u(g);const{px:w,py:m,pz:b}=this,{px:E,py:$,pz:D}=g;let S=r.ZERO,A=r.ZERO,x=r.ZERO;const k=e.a,C=r.mul(e.b,rd);let B=r.mul(w,E),j=r.mul(m,$),I=r.mul(b,D),_=r.add(w,m),v=r.add(E,$);_=r.mul(_,v),v=r.add(B,j),_=r.sub(_,v),v=r.add(w,b);let O=r.add(E,D);return v=r.mul(v,O),O=r.add(B,I),v=r.sub(v,O),O=r.add(m,b),S=r.add($,D),O=r.mul(O,S),S=r.add(j,I),O=r.sub(O,S),x=r.mul(k,v),S=r.mul(C,I),x=r.add(S,x),S=r.sub(j,x),x=r.add(j,x),A=r.mul(S,x),j=r.add(B,B),j=r.add(j,B),I=r.mul(k,I),v=r.mul(C,v),j=r.add(j,I),I=r.sub(B,I),I=r.mul(k,I),v=r.add(v,I),B=r.mul(j,v),A=r.add(A,B),B=r.mul(O,v),S=r.mul(_,S),S=r.sub(S,B),B=r.mul(_,j),x=r.mul(O,x),x=r.add(x,B),new d(S,A,x)}subtract(g){return this.add(g.negate())}is0(){return this.equals(d.ZERO)}wNAF(g){return f.wNAFCached(this,g,d.normalizeZ)}multiplyUnsafe(g){const{endo:w,n:m}=e;Ut("scalar",g,Mt,m);const b=d.ZERO;if(g===Mt)return b;if(this.is0()||g===xe)return this;if(!w||f.hasPrecomputes(this))return f.wNAFCachedUnsafe(this,g,d.normalizeZ);let{k1neg:E,k1:$,k2neg:D,k2:S}=w.splitScalar(g),A=b,x=b,k=this;for(;$>Mt||S>Mt;)$&xe&&(A=A.add(k)),S&xe&&(x=x.add(k)),k=k.double(),$>>=xe,S>>=xe;return E&&(A=A.negate()),D&&(x=x.negate()),x=new d(r.mul(x.px,w.beta),x.py,x.pz),A.add(x)}multiply(g){const{endo:w,n:m}=e;Ut("scalar",g,xe,m);let b,E;if(w){const{k1neg:$,k1:D,k2neg:S,k2:A}=w.splitScalar(g);let{p:x,f:k}=this.wNAF(D),{p:C,f:B}=this.wNAF(A);x=f.constTimeNegate($,x),C=f.constTimeNegate(S,C),C=new d(r.mul(C.px,w.beta),C.py,C.pz),b=x.add(C),E=k.add(B)}else{const{p:$,f:D}=this.wNAF(g);b=$,E=D}return d.normalizeZ([b,E])[0]}multiplyAndAddUnsafe(g,w,m){const b=d.BASE,E=(D,S)=>S===Mt||S===xe||!D.equals(b)?D.multiplyUnsafe(S):D.multiply(S),$=E(this,w).add(E(g,m));return $.is0()?void 0:$}toAffine(g){return l(this,g)}isTorsionFree(){const{h:g,isTorsionFree:w}=e;if(g===xe)return!0;if(w)return w(d,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:g,clearCofactor:w}=e;return g===xe?this:w?w(d,this):this.multiplyUnsafe(e.h)}toRawBytes(g=!0){return sn("isCompressed",g),this.assertValidity(),i(d,this,g)}toHex(g=!0){return sn("isCompressed",g),on(this.toRawBytes(g))}}d.BASE=new d(e.Gx,e.Gy,r.ONE),d.ZERO=new d(r.ZERO,r.ONE,r.ZERO);const p=e.nBitLength,f=h_(d,e.endo?Math.ceil(p/2):p);return{CURVE:e,ProjectivePoint:d,normPrivateKeyToScalar:c,weierstrassEquation:o,isWithinCurveOrder:a}}function I_(t){const e=Qh(t);return ln(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function D_(t){const e=I_(t),{Fp:r,n}=e,i=r.BYTES+1,s=2*r.BYTES+1;function o(I){return Ye(I,n)}function a(I){return Yo(I,n)}const{ProjectivePoint:c,normPrivateKeyToScalar:u,weierstrassEquation:l,isWithinCurveOrder:h}=x_({...e,toBytes(I,_,v){const O=_.toAffine(),T=r.toBytes(O.x),P=qn;return sn("isCompressed",v),v?P(Uint8Array.from([_.hasEvenY()?2:3]),T):P(Uint8Array.from([4]),T,r.toBytes(O.y))},fromBytes(I){const _=I.length,v=I[0],O=I.subarray(1);if(_===i&&(v===2||v===3)){const T=xr(O);if(!Zi(T,xe,r.ORDER))throw new Error("Point is not on curve");const P=l(T);let N;try{N=r.sqrt(P)}catch(M){const z=M instanceof Error?": "+M.message:"";throw new Error("Point is not on curve"+z)}const F=(N&xe)===xe;return(v&1)===1!==F&&(N=r.neg(N)),{x:T,y:N}}else if(_===s&&v===4){const T=r.fromBytes(O.subarray(0,r.BYTES)),P=r.fromBytes(O.subarray(r.BYTES,2*r.BYTES));return{x:T,y:P}}else{const T=i,P=s;throw new Error("invalid Point, expected length of "+T+", or uncompressed "+P+", got "+_)}}}),d=I=>on(un(I,e.nByteLength));function p(I){const _=n>>xe;return I>_}function f(I){return p(I)?o(-I):I}const y=(I,_,v)=>xr(I.slice(_,v));class g{constructor(_,v,O){this.r=_,this.s=v,this.recovery=O,this.assertValidity()}static fromCompact(_){const v=e.nByteLength;return _=tt("compactSignature",_,v*2),new g(y(_,0,v),y(_,v,2*v))}static fromDER(_){const{r:v,s:O}=kt.toSig(tt("DER",_));return new g(v,O)}assertValidity(){Ut("r",this.r,xe,n),Ut("s",this.s,xe,n)}addRecoveryBit(_){return new g(this.r,this.s,_)}recoverPublicKey(_){const{r:v,s:O,recovery:T}=this,P=D(tt("msgHash",_));if(T==null||![0,1,2,3].includes(T))throw new Error("recovery id invalid");const N=T===2||T===3?v+e.n:v;if(N>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const F=T&1?"03":"02",M=c.fromHex(F+d(N)),z=a(N),q=o(-P*z),V=o(O*z),K=c.BASE.multiplyAndAddUnsafe(M,q,V);if(!K)throw new Error("point at infinify");return K.assertValidity(),K}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new g(this.r,o(-this.s),this.recovery):this}toDERRawBytes(){return cn(this.toDERHex())}toDERHex(){return kt.hexFromSig({r:this.r,s:this.s})}toCompactRawBytes(){return cn(this.toCompactHex())}toCompactHex(){return d(this.r)+d(this.s)}}const w={isValidPrivateKey(I){try{return u(I),!0}catch{return!1}},normPrivateKeyToScalar:u,randomPrivateKey:()=>{const I=Yh(e.n);return c_(e.randomBytes(I),e.n)},precompute(I=8,_=c.BASE){return _._setWindowSize(I),_.multiply(BigInt(3)),_}};function m(I,_=!0){return c.fromPrivateKey(I).toRawBytes(_)}function b(I){const _=Sr(I),v=typeof I=="string",O=(_||v)&&I.length;return _?O===i||O===s:v?O===2*i||O===2*s:I instanceof c}function E(I,_,v=!0){if(b(I))throw new Error("first arg must be private key");if(!b(_))throw new Error("second arg must be public key");return c.fromHex(_).multiply(u(I)).toRawBytes(v)}const $=e.bits2int||function(I){if(I.length>8192)throw new Error("input is too large");const _=xr(I),v=I.length*8-e.nBitLength;return v>0?_>>BigInt(v):_},D=e.bits2int_modN||function(I){return o($(I))},S=Ko(e.nBitLength);function A(I){return Ut("num < 2^"+e.nBitLength,I,Mt,S),un(I,e.nByteLength)}function x(I,_,v=k){if(["recovered","canonical"].some(G=>G in v))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:T}=e;let{lowS:P,prehash:N,extraEntropy:F}=v;P==null&&(P=!0),I=tt("msgHash",I),td(v),N&&(I=tt("prehashed msgHash",O(I)));const M=D(I),z=u(_),q=[A(z),A(M)];if(F!=null&&F!==!1){const G=F===!0?T(r.BYTES):F;q.push(tt("extraEntropy",G))}const V=qn(...q),K=M;function ee(G){const W=$(G);if(!h(W))return;const ye=a(W),ue=c.BASE.multiply(W).toAffine(),le=o(ue.x);if(le===Mt)return;const $e=o(ye*o(K+le*z));if($e===Mt)return;let Me=(ue.x===le?0:2)|Number(ue.y&xe),Kt=$e;return P&&p($e)&&(Kt=f($e),Me^=1),new g(le,Kt,Me)}return{seed:V,k2sig:ee}}const k={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function B(I,_,v=k){const{seed:O,k2sig:T}=x(I,_,v),P=e;return qh(P.hash.outputLen,P.nByteLength,P.hmac)(O,T)}c.BASE._setWindowSize(8);function j(I,_,v,O=C){const T=I;_=tt("msgHash",_),v=tt("publicKey",v);const{lowS:P,prehash:N,format:F}=O;if(td(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(F!==void 0&&F!=="compact"&&F!=="der")throw new Error("format must be compact or der");const M=typeof T=="string"||Sr(T),z=!M&&!F&&typeof T=="object"&&T!==null&&typeof T.r=="bigint"&&typeof T.s=="bigint";if(!M&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,V;try{if(z&&(q=new g(T.r,T.s)),M){try{F!=="compact"&&(q=g.fromDER(T))}catch($e){if(!($e instanceof kt.Err))throw $e}!q&&F!=="der"&&(q=g.fromCompact(T))}V=c.fromHex(v)}catch{return!1}if(!q||P&&q.hasHighS())return!1;N&&(_=e.hash(_));const{r:K,s:ee}=q,G=D(_),W=a(ee),ye=o(G*W),ue=o(K*W),le=c.BASE.multiplyAndAddUnsafe(V,ye,ue)?.toAffine();return le?o(le.x)===K:!1}return{CURVE:e,getPublicKey:m,getSharedSecret:E,sign:B,verify:j,ProjectivePoint:c,Signature:g,utils:w}}function O_(t){return{hash:t,hmac:(e,...r)=>Hi(t,e,CE(...r)),randomBytes:rn}}function $_(t,e){const r=n=>D_({...t,...O_(n)});return{...r(e),create:r}}const nd=Wh(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),A_=nd.create(BigInt("-3")),P_=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),T_=$_({a:A_,b:P_,Fp:nd,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},kn),id="base10",ze="base16",dt="base64pad",ar="base64url",zn="utf8",sd=0,jt=1,Vn=2,R_=0,od=1,Kn=12,na=32;function C_(){const t=ra.utils.randomPrivateKey(),e=ra.getPublicKey(t);return{privateKey:Ge(t,ze),publicKey:Ge(e,ze)}}function ia(){const t=rn(na);return Ge(t,ze)}function N_(t,e){const r=ra.getSharedSecret(st(t,ze),st(e,ze)),n=U2(kn,r,void 0,void 0,na);return Ge(n,ze)}function Xi(t){const e=kn(st(t,ze));return Ge(e,ze)}function St(t){const e=kn(st(t,zn));return Ge(e,ze)}function ad(t){return st(`${t}`,id)}function Dr(t){return Number(Ge(t,id))}function cd(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function ud(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function B_(t){const e=ad(typeof t.type<"u"?t.type:sd);if(Dr(e)===jt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?st(t.senderPublicKey,ze):void 0,n=typeof t.iv<"u"?st(t.iv,ze):rn(Kn),i=st(t.symKey,ze),s=Fh(i,n).encrypt(st(t.message,zn)),o=ld({type:e,sealed:s,iv:n,senderPublicKey:r});return t.encoding===ar?cd(o):o}function F_(t){const e=st(t.symKey,ze),{sealed:r,iv:n}=Hn({encoded:t.encoded,encoding:t.encoding}),i=Fh(e,n).decrypt(r);if(i===null)throw new Error("Failed to decrypt");return Ge(i,zn)}function L_(t,e){const r=ad(Vn),n=rn(Kn),i=st(t,zn),s=ld({type:r,sealed:i,iv:n});return e===ar?cd(s):s}function U_(t,e){const{sealed:r}=Hn({encoded:t,encoding:e});return Ge(r,zn)}function ld(t){if(Dr(t.type)===Vn)return Ge(Rn([t.type,t.sealed]),dt);if(Dr(t.type)===jt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return Ge(Rn([t.type,t.senderPublicKey,t.iv,t.sealed]),dt)}return Ge(Rn([t.type,t.iv,t.sealed]),dt)}function Hn(t){const e=(t.encoding||dt)===ar?ud(t.encoded):t.encoded,r=st(e,dt),n=r.slice(R_,od),i=od;if(Dr(n)===jt){const c=i+na,u=c+Kn,l=r.slice(i,c),h=r.slice(c,u),d=r.slice(u);return{type:n,sealed:d,iv:h,senderPublicKey:l}}if(Dr(n)===Vn){const c=r.slice(i),u=rn(Kn);return{type:n,sealed:c,iv:u}}const s=i+Kn,o=r.slice(i,s),a=r.slice(s);return{type:n,sealed:a,iv:o}}function k_(t,e){const r=Hn({encoded:t,encoding:e?.encoding});return hd({type:Dr(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?Ge(r.senderPublicKey,ze):void 0,receiverPublicKey:e?.receiverPublicKey})}function hd(t){const e=t?.type||sd;if(e===jt){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 dd(t){return t.type===jt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function fd(t){return t.type===Vn}function M_(t){const e=Buffer.from(t.x,"base64"),r=Buffer.from(t.y,"base64");return Rn([new Uint8Array([4]),e,r])}function j_(t,e){const[r,n,i]=t.split("."),s=Buffer.from(ud(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=kn(c),l=M_(e);if(!T_.verify(Rn([o,a]),u,l))throw new Error("Invalid signature");return Hs(t).payload}const q_="irn";function Qi(t){return t?.relay||{protocol:q_}}function Wn(t){const e=Yv[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function z_(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 pd(t){if(!t.includes("wc:")){const u=ah(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:V_(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:z_(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function V_(t){return t.startsWith("//")?t.substring(2):t}function K_(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 gd(t){const e=new URLSearchParams,r=K_(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 es(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}function dn(t){const e=[];return t.forEach(r=>{const[n,i]=r.split(":");e.push(`${n}:${i}`)}),e}function H_(t){const e=[];return Object.values(t).forEach(r=>{e.push(...dn(r.accounts))}),e}function W_(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.methods)}),r}function G_(t,e){const r=[];return Object.values(t).forEach(n=>{dn(n.accounts).includes(e)&&r.push(...n.events)}),r}function Y_(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 yd(t,e){e=e.map(n=>n.replace("did:pkh:",""));const r=Y_(e);for(const[n,i]of Object.entries(r))i.methods?i.methods=pE(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return r}const Z_={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}},J_={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 U(t,e){const{message:r,code:n}=J_[t];return{message:e?`${r} ${e}`:r,code:n}}function oe(t,e){const{message:r,code:n}=Z_[t];return{message:e?`${r} ${e}`:r,code:n}}function Gn(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function ts(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Re(t){return typeof t>"u"}function pe(t,e){return e&&Re(t)?!0:typeof t=="string"&&!!t.trim().length}function sa(t,e){return e&&Re(t)?!0:typeof t=="number"&&!isNaN(t)}function X_(t,e){const{requiredNamespaces:r}=e,n=Object.keys(t.namespaces),i=Object.keys(r);let s=!0;return vr(i,n)?(n.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=dn(a),h=r[o];(!vr(Zl(o,h),l)||!vr(h.methods,c)||!vr(h.events,u))&&(s=!1)}),s):!1}function rs(t){return pe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function Q_(t){if(pe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&rs(r)}}return!1}function eS(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(pe(t,!1)){if(e(t))return!0;const r=ah(t);return e(r)}}catch{}return!1}function tS(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function rS(t){return t?.topic}function nS(t,e){let r=null;return pe(t?.publicKey,!1)||(r=U("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function wd(t){let e=!0;return Gn(t)?t.length&&(e=t.every(r=>pe(r,!1))):e=!1,e}function iS(t,e,r){let n=null;return Gn(e)&&e.length?e.forEach(i=>{n||rs(i)||(n=oe("UNSUPPORTED_CHAINS",`${r}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):rs(t)||(n=oe("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 sS(t,e,r){let n=null;return Object.entries(t).forEach(([i,s])=>{if(n)return;const o=iS(i,Zl(i,s),`${e} ${r}`);o&&(n=o)}),n}function oS(t,e){let r=null;return Gn(t)?t.forEach(n=>{r||Q_(n)||(r=oe("UNSUPPORTED_ACCOUNTS",`${e}, account ${n} should be a string and conform to "namespace:chainId:address" format`))}):r=oe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function aS(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=oS(n?.accounts,`${e} namespace`);i&&(r=i)}),r}function cS(t,e){let r=null;return wd(t?.methods)?wd(t?.events)||(r=oe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=oe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function md(t,e){let r=null;return Object.values(t).forEach(n=>{if(r)return;const i=cS(n,`${e}, namespace`);i&&(r=i)}),r}function uS(t,e,r){let n=null;if(t&&ts(t)){const i=md(t,e);i&&(n=i);const s=sS(t,e,r);s&&(n=s)}else n=U("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return n}function oa(t,e){let r=null;if(t&&ts(t)){const n=md(t,e);n&&(r=n);const i=aS(t,e);i&&(r=i)}else r=U("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function bd(t){return pe(t.protocol,!0)}function lS(t,e){let r=!1;return e&&!t?r=!0:t&&Gn(t)&&t.length&&t.forEach(n=>{r=bd(n)}),r}function hS(t){return typeof t=="number"}function Ze(t){return typeof t<"u"&&typeof t!==null}function dS(t){return!(!t||typeof t!="object"||!t.code||!sa(t.code,!1)||!t.message||!pe(t.message,!1))}function fS(t){return!(Re(t)||!pe(t.method,!1))}function pS(t){return!(Re(t)||Re(t.result)&&Re(t.error)||!sa(t.id,!1)||!pe(t.jsonrpc,!1))}function gS(t){return!(Re(t)||!pe(t.name,!1))}function vd(t,e){return!(!rs(e)||!H_(t).includes(e))}function yS(t,e,r){return pe(r,!1)?W_(t,e).includes(r):!1}function wS(t,e,r){return pe(r,!1)?G_(t,e).includes(r):!1}function Ed(t,e,r){let n=null;const i=mS(t),s=bS(e),o=Object.keys(i),a=Object.keys(s),c=_d(Object.keys(t)),u=_d(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
21
21
  Required: ${l.toString()}
22
- Received: ${Object.keys(e).toString()}`)),mr(o,a)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
22
+ Received: ${Object.keys(e).toString()}`)),vr(o,a)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
23
23
  Required: ${o.toString()}
24
- Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||n)return;const d=ln(e[h].accounts);d.includes(h)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
24
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||n)return;const d=dn(e[h].accounts);d.includes(h)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
25
25
  Required: ${h}
26
- Approved: ${d.toString()}`))}),o.forEach(h=>{n||(mr(i[h].methods,s[h].methods)?mr(i[h].events,s[h].events)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function mS(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 _d(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function bS(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:ln(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 vS(t,e){return sa(t,!1)&&t<=e.max&&t>=e.min}function Sd(){const t=Nn();return new Promise(e=>{switch(t){case Qe.browser:e(ES());break;case Qe.reactNative:e(_S());break;case Qe.node:e(SS());break;default:e(!0)}})}function ES(){return Cn()&&navigator?.onLine}async function _S(){return tr()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function SS(){return!0}function xS(t){switch(Nn()){case Qe.browser:IS(t);break;case Qe.reactNative:DS(t);break}}function IS(t){!tr()&&Cn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function DS(t){tr()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}const aa={};class Yn{static get(e){return aa[e]}static set(e,r){aa[e]=r}static delete(e){delete aa[e]}}const OS="PARSE_ERROR",$S="INVALID_REQUEST",AS="METHOD_NOT_FOUND",PS="INVALID_PARAMS",xd="INTERNAL_ERROR",ca="SERVER_ERROR",TS=[-32700,-32600,-32601,-32602,-32603],Zn={[OS]:{code:-32700,message:"Parse error"},[$S]:{code:-32600,message:"Invalid Request"},[AS]:{code:-32601,message:"Method not found"},[PS]:{code:-32602,message:"Invalid params"},[xd]:{code:-32603,message:"Internal error"},[ca]:{code:-32e3,message:"Server error"}},Id=ca;function RS(t){return TS.includes(t)}function Dd(t){return Object.keys(Zn).includes(t)?Zn[t]:Zn[Id]}function CS(t){const e=Object.values(Zn).find(r=>r.code===t);return e||Zn[Id]}function NS(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Od={};/*! *****************************************************************************
26
+ Approved: ${d.toString()}`))}),o.forEach(h=>{n||(vr(i[h].methods,s[h].methods)?vr(i[h].events,s[h].events)||(n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):n=U("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),n}function mS(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 _d(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function bS(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:dn(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 vS(t,e){return sa(t,!1)&&t<=e.max&&t>=e.min}function Sd(){const t=Nn();return new Promise(e=>{switch(t){case Qe.browser:e(ES());break;case Qe.reactNative:e(_S());break;case Qe.node:e(SS());break;default:e(!0)}})}function ES(){return Xr()&&navigator?.onLine}async function _S(){return tr()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function SS(){return!0}function xS(t){switch(Nn()){case Qe.browser:IS(t);break;case Qe.reactNative:DS(t);break}}function IS(t){!tr()&&Xr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function DS(t){tr()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function OS(){var t;return Xr()&&yr()?((t=yr())==null?void 0:t.visibilityState)==="visible":!0}const aa={};class Yn{static get(e){return aa[e]}static set(e,r){aa[e]=r}static delete(e){delete aa[e]}}const $S="PARSE_ERROR",AS="INVALID_REQUEST",PS="METHOD_NOT_FOUND",TS="INVALID_PARAMS",xd="INTERNAL_ERROR",ca="SERVER_ERROR",RS=[-32700,-32600,-32601,-32602,-32603],Zn={[$S]:{code:-32700,message:"Parse error"},[AS]:{code:-32600,message:"Invalid Request"},[PS]:{code:-32601,message:"Method not found"},[TS]:{code:-32602,message:"Invalid params"},[xd]:{code:-32603,message:"Internal error"},[ca]:{code:-32e3,message:"Server error"}},Id=ca;function CS(t){return RS.includes(t)}function Dd(t){return Object.keys(Zn).includes(t)?Zn[t]:Zn[Id]}function NS(t){const e=Object.values(Zn).find(r=>r.code===t);return e||Zn[Id]}function BS(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Od={};/*! *****************************************************************************
27
27
  Copyright (c) Microsoft Corporation.
28
28
 
29
29
  Permission to use, copy, modify, and/or distribute this software for any
@@ -36,5 +36,5 @@ ${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+Buffer.from(zE(r)).toStr
36
36
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
37
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
38
  PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var ua=function(t,e){return ua=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])},ua(t,e)};function BS(t,e){ua(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var la=function(){return la=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},la.apply(this,arguments)};function FS(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 LS(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 US(t,e){return function(r,n){e(r,n,t)}}function kS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function MS(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 jS(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 qS(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function zS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ha(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 $d(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 VS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($d(arguments[e]));return t}function KS(){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 Jn(t){return this instanceof Jn?(this.v=t,this):new Jn(t)}function HS(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof Jn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function WS(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:Jn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function GS(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 ha=="function"?ha(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 YS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ZS(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 JS(t){return t&&t.__esModule?t:{default:t}}function XS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function QS(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 ex=Object.freeze({__proto__:null,__extends:BS,get __assign(){return la},__rest:FS,__decorate:LS,__param:US,__metadata:kS,__awaiter:MS,__generator:jS,__createBinding:qS,__exportStar:zS,__values:ha,__read:$d,__spread:VS,__spreadArrays:KS,__await:Jn,__asyncGenerator:HS,__asyncDelegator:WS,__asyncValues:GS,__makeTemplateObject:YS,__importStar:ZS,__importDefault:JS,__classPrivateFieldGet:XS,__classPrivateFieldSet:QS}),tx=ka(ex),qt={},Ad;function rx(){if(Ad)return qt;Ad=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.isBrowserCryptoAvailable=qt.getSubtleCrypto=qt.getBrowerCrypto=void 0;function t(){return yt?.crypto||yt?.msCrypto||{}}qt.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qt.isBrowserCryptoAvailable=r,qt}var zt={},Pd;function nx(){if(Pd)return zt;Pd=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.isBrowser=zt.isNode=zt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zt.isNode=e;function r(){return!t()&&!e()}return zt.isBrowser=r,zt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=tx;e.__exportStar(rx(),t),e.__exportStar(nx(),t)})(Od);function xt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Ir(t=6){return BigInt(xt(t))}function Dr(t,e,r){return{id:r||xt(),jsonrpc:"2.0",method:t,params:e}}function da(t,e){return{id:t,jsonrpc:"2.0",result:e}}function fa(t,e,r){return{id:t,jsonrpc:"2.0",error:ix(e,r)}}function ix(t,e){return typeof t>"u"?Dd(xd):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dd(ca)),{message:t})),typeof e<"u"&&(t.data=e),RS(t.code)&&(t=CS(t.code)),t)}class sx{}class ox extends sx{constructor(){super()}}class ax extends ox{constructor(e){super()}}const cx="^wss?:";function ux(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function lx(t,e){const r=ux(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Td(t){return lx(t,cx)}function hx(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Rd(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pa(t){return Rd(t)&&"method"in t}function ns(t){return Rd(t)&&(It(t)||ot(t))}function It(t){return"result"in t}function ot(t){return"error"in t}class dx extends ax{constructor(e){super(e),this.events=new Le.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(Dr(e.method,e.params||[],e.id||Ir().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=>{ot(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),ns(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 fx=()=>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"),px=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Cd=t=>t.split("?")[0],Nd=10,gx=fx();class yx{constructor(e){if(this.url=e,this.events=new Le.exports.EventEmitter,this.registering=!1,!Td(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(dr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Td(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=Od.isReactNative()?void 0:{rejectUnauthorized:!hx(e)},s=new gx(e,[],i);px()?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"?Nr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=fa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return NS(e,Cd(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Nd&&this.events.setMaxListeners(Nd)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Cd(this.url)}`));return this.events.emit("register_error",r),r}}const Bd="wc",Fd=2,is="core",Dt=`${Bd}@2:${is}:`,wx={name:is,logger:"error"},mx={database:":memory:"},bx="crypto",Ld="client_ed25519_seed",vx=L.ONE_DAY,Ex="keychain",_x="0.3",Sx="messages",xx="0.3",Ud=L.SIX_HOURS,Ix="publisher",kd="irn",Dx="error",Md="wss://relay.walletconnect.org",Ox="relayer",Ie={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"},$x="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Ax=.1,ga="2.19.2",ce={link_mode:"link_mode",relay:"relay"},ss={inbound:"inbound",outbound:"outbound"},Px="0.3",Tx="WALLETCONNECT_CLIENT_ID",jd="WALLETCONNECT_LINK_MODE_APPS",rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Rx="subscription",Cx="0.3",Nx="pairing",Bx="0.3",Xn={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Or={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ft={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Fx="history",Lx="0.3",Ux="expirer",ct={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},kx="0.3",Mx="verify-api",jx="https://verify.walletconnect.com",qd="https://verify.walletconnect.org",Qn=qd,qx=`${Qn}/v3`,zx=[jx,qd],Vx="echo",Kx="https://echo.walletconnect.com",Ot={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"},Vt={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"},pt={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"},$r={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"},Ar={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"},ei={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"},Hx=.1,Wx="event-client",Gx=86400,Yx="https://pulse.walletconnect.org/batch";function Zx(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Jx=Zx,Xx=Jx;const zd=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")},Qx=t=>new TextEncoder().encode(t),e3=t=>new TextDecoder().decode(t);class t3{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 r3{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 Vd(this,e)}}class n3{constructor(e){this.decoders=e}or(e){return Vd(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 Vd=(t,e)=>new n3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class i3{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new t3(e,r,n),this.decoder=new r3(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const os=({name:t,prefix:e,encode:r,decode:n})=>new i3(t,e,r,n),ti=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Xx(r,e);return os({prefix:t,name:e,encode:n,decode:s=>zd(i(s))})},s3=(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},o3=(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},Ce=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>os({prefix:e,name:t,encode(i){return o3(i,n,r)},decode(i){return s3(i,n,r,t)}}),a3=os({prefix:"\0",name:"identity",encode:t=>e3(t),decode:t=>Qx(t)});var c3=Object.freeze({__proto__:null,identity:a3});const u3=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var l3=Object.freeze({__proto__:null,base2:u3});const h3=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var d3=Object.freeze({__proto__:null,base8:h3});const f3=ti({prefix:"9",name:"base10",alphabet:"0123456789"});var p3=Object.freeze({__proto__:null,base10:f3});const g3=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),y3=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var w3=Object.freeze({__proto__:null,base16:g3,base16upper:y3});const m3=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),b3=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),v3=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),E3=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),_3=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),S3=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),x3=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),I3=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),D3=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var O3=Object.freeze({__proto__:null,base32:m3,base32upper:b3,base32pad:v3,base32padupper:E3,base32hex:_3,base32hexupper:S3,base32hexpad:x3,base32hexpadupper:I3,base32z:D3});const $3=ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),A3=ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var P3=Object.freeze({__proto__:null,base36:$3,base36upper:A3});const T3=ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),R3=ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var C3=Object.freeze({__proto__:null,base58btc:T3,base58flickr:R3});const N3=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),B3=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),F3=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),L3=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var U3=Object.freeze({__proto__:null,base64:N3,base64pad:B3,base64url:F3,base64urlpad:L3});const Kd=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}"),k3=Kd.reduce((t,e,r)=>(t[r]=e,t),[]),M3=Kd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function j3(t){return t.reduce((e,r)=>(e+=k3[r],e),"")}function q3(t){const e=[];for(const r of t){const n=M3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const z3=os({prefix:"\u{1F680}",name:"base256emoji",encode:j3,decode:q3});var V3=Object.freeze({__proto__:null,base256emoji:z3}),K3=Wd,Hd=128,H3=127,W3=~H3,G3=Math.pow(2,31);function Wd(t,e,r){e=e||[],r=r||0;for(var n=r;t>=G3;)e[r++]=t&255|Hd,t/=128;for(;t&W3;)e[r++]=t&255|Hd,t>>>=7;return e[r]=t|0,Wd.bytes=r-n+1,e}var Y3=ya,Z3=128,Gd=127;function ya(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Gd)<<i:(o&Gd)*Math.pow(2,i),i+=7}while(o>=Z3);return ya.bytes=s-n,r}var J3=Math.pow(2,7),X3=Math.pow(2,14),Q3=Math.pow(2,21),eI=Math.pow(2,28),tI=Math.pow(2,35),rI=Math.pow(2,42),nI=Math.pow(2,49),iI=Math.pow(2,56),sI=Math.pow(2,63),oI=function(t){return t<J3?1:t<X3?2:t<Q3?3:t<eI?4:t<tI?5:t<rI?6:t<nI?7:t<iI?8:t<sI?9:10},aI={encode:K3,decode:Y3,encodingLength:oI},Yd=aI;const Zd=(t,e,r=0)=>(Yd.encode(t,e,r),e),Jd=t=>Yd.encodingLength(t),wa=(t,e)=>{const r=e.byteLength,n=Jd(t),i=n+Jd(r),s=new Uint8Array(i+r);return Zd(t,s,0),Zd(r,s,n),s.set(e,i),new cI(t,r,e,s)};class cI{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Xd=({name:t,code:e,encode:r})=>new uI(t,e,r);class uI{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?wa(this.code,r):r.then(n=>wa(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Qd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),lI=Xd({name:"sha2-256",code:18,encode:Qd("SHA-256")}),hI=Xd({name:"sha2-512",code:19,encode:Qd("SHA-512")});var dI=Object.freeze({__proto__:null,sha256:lI,sha512:hI});const ef=0,fI="identity",tf=zd;var pI=Object.freeze({__proto__:null,identity:{code:ef,name:fI,encode:tf,digest:t=>wa(ef,tf(t))}});new TextEncoder,new TextDecoder;const rf={...c3,...l3,...d3,...p3,...w3,...O3,...P3,...C3,...U3,...V3};({...dI,...pI});function gI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const sf=nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=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=gI(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),yI={utf8:sf,"utf-8":sf,hex:rf.base16,latin1:ma,ascii:ma,binary:ma,...rf};function wI(t,e="utf8"){const r=yI[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,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var mI=Object.defineProperty,bI=(t,e,r)=>e in t?mI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e,r)=>bI(t,typeof e!="symbol"?e+"":e,r);class vI{constructor(e,r){this.core=e,this.logger=r,$t(this,"keychain",new Map),$t(this,"name",Ex),$t(this,"version",_x),$t(this,"initialized",!1),$t(this,"storagePrefix",Dt),$t(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$t(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$t(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$t(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=U("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$t(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ao(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var EI=Object.defineProperty,_I=(t,e,r)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>_I(t,typeof e!="symbol"?e+"":e,r);class SI{constructor(e,r,n){this.core=e,this.logger=r,Ne(this,"name",bx),Ne(this,"keychain"),Ne(this,"randomSessionIdentifier",ia()),Ne(this,"initialized",!1),Ne(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ne(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ne(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=wu(i);return yu(s.publicKey)}),Ne(this,"generateKeyPair",()=>{this.isInitialized();const i=C_();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ne(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=wu(s),a=this.randomSessionIdentifier;return await Mm(a,i,vx,o)}),Ne(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=N_(a,s);return this.setSymKey(c,o)}),Ne(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Xi(i);return await this.keychain.set(o,i),o}),Ne(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"encode",async(i,s,o)=>{this.isInitialized();const a=hd(o),c=dr(s);if(fd(a))return L_(c,o?.encoding);if(dd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return B_({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ne(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k_(s,o);if(fd(a)){const c=U_(s,o?.encoding);return Nr(c)}if(dd(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=F_({symKey:c,encoded:s,encoding:o?.encoding});return Nr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ne(this,"getPayloadType",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return xr(o.type)}),Ne(this,"getPayloadSenderPublicKey",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return o.senderPublicKey?Ge(o.senderPublicKey,ze):void 0}),this.core=e,this.logger=je(r,this.name),this.keychain=n||new vI(this.core,this.logger)}get context(){return He(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(Ld)}catch{e=ia(),await this.keychain.set(Ld,e)}return wI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xI=Object.defineProperty,II=Object.defineProperties,DI=Object.getOwnPropertyDescriptors,of=Object.getOwnPropertySymbols,OI=Object.prototype.hasOwnProperty,$I=Object.prototype.propertyIsEnumerable,ba=(t,e,r)=>e in t?xI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,AI=(t,e)=>{for(var r in e||(e={}))OI.call(e,r)&&ba(t,r,e[r]);if(of)for(var r of of(e))$I.call(e,r)&&ba(t,r,e[r]);return t},PI=(t,e)=>II(t,DI(e)),nt=(t,e,r)=>ba(t,typeof e!="symbol"?e+"":e,r);class TI extends kg{constructor(e,r){super(e,r),this.logger=e,this.core=r,nt(this,"messages",new Map),nt(this,"messagesWithoutClientAck",new Map),nt(this,"name",Sx),nt(this,"version",xx),nt(this,"initialized",!1),nt(this,"storagePrefix",Dt),nt(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}}}),nt(this,"set",async(n,i,s)=>{this.isInitialized();const o=St(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===ss.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,PI(AI({},c),{[o]:i}))}return await this.persist(),o}),nt(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),nt(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}),nt(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=St(i);return typeof s[o]<"u"}),nt(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),nt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=je(e,this.name),this.core=r}get context(){return He(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,Ao(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ao(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Po(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var RI=Object.defineProperty,CI=Object.defineProperties,NI=Object.getOwnPropertyDescriptors,af=Object.getOwnPropertySymbols,BI=Object.prototype.hasOwnProperty,FI=Object.prototype.propertyIsEnumerable,va=(t,e,r)=>e in t?RI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))BI.call(e,r)&&va(t,r,e[r]);if(af)for(var r of af(e))FI.call(e,r)&&va(t,r,e[r]);return t},Ea=(t,e)=>CI(t,NI(e)),gt=(t,e,r)=>va(t,typeof e!="symbol"?e+"":e,r);class LI extends Mg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,gt(this,"events",new Le.exports.EventEmitter),gt(this,"name",Ix),gt(this,"queue",new Map),gt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),gt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),gt(this,"needsTransportRestart",!1),gt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||Ud,c=Qi(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||Ir().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Ie.publish,g),y(d))};this.relayer.events.on(Ie.publish,g);const w=rr(new Promise((m,b)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(E=>{this.logger.warn(E,E?.message),b(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await w,this.events.removeListener(Ie.publish,g)}catch(m){this.queue.set(h,Ea(as({},d),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await rr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),gt(this,"on",(n,i)=>{this.events.on(n,i)}),gt(this,"once",(n,i)=>{this.events.once(n,i)}),gt(this,"off",(n,i)=>{this.events.off(n,i)}),gt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=je(r,this.name),this.registerEventListeners()}get context(){return He(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=Ud,prompt:u,tag:l,id:h,attestation:d,tvf:p}=e,f={method:Wn(Qi().protocol).publish,params:as({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},p),id:h};Re((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Re((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,Ea(as({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(Ea(as({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Cr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var UI=Object.defineProperty,kI=(t,e,r)=>e in t?UI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,hn=(t,e,r)=>kI(t,typeof e!="symbol"?e+"":e,r);class MI{constructor(){hn(this,"map",new Map),hn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),hn(this,"get",e=>this.map.get(e)||[]),hn(this,"exists",(e,r)=>this.get(e).includes(r)),hn(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)}),hn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var jI=Object.defineProperty,qI=Object.defineProperties,zI=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,VI=Object.prototype.hasOwnProperty,KI=Object.prototype.propertyIsEnumerable,_a=(t,e,r)=>e in t?jI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ri=(t,e)=>{for(var r in e||(e={}))VI.call(e,r)&&_a(t,r,e[r]);if(cf)for(var r of cf(e))KI.call(e,r)&&_a(t,r,e[r]);return t},Sa=(t,e)=>qI(t,zI(e)),ne=(t,e,r)=>_a(t,typeof e!="symbol"?e+"":e,r);class HI extends zg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ne(this,"subscriptions",new Map),ne(this,"topicMap",new MI),ne(this,"events",new Le.exports.EventEmitter),ne(this,"name",Rx),ne(this,"version",Cx),ne(this,"pending",new Map),ne(this,"cached",[]),ne(this,"initialized",!1),ne(this,"storagePrefix",Dt),ne(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ne(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"clientId"),ne(this,"batchSubscribeTopicsLimit",500),ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ne(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Qi(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),ne(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ne(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ne(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ne(this,"on",(n,i)=>{this.events.on(n,i)}),ne(this,"once",(n,i)=>{this.events.once(n,i)}),ne(this,"off",(n,i)=>{this.events.off(n,i)}),ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),ne(this,"start",async()=>{await this.onConnect()}),ne(this,"stop",async()=>{await this.onDisconnect()}),ne(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ne(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)}),ne(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Cr.pulse,async()=>{await this.checkPending()}),this.events.on(rt.created,async n=>{const i=rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(rt.deleted,async n=>{const i=rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=je(r,this.name),this.clientId=""}get context(){return He(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=Qi(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=oe("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;(!n||n?.transportType===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Wn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},L.toMiliseconds(L.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(rt.created,h),l(d.id))};this.events.on(rt.created,h);try{const d=await rr(new Promise((p,f)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),f(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rt.created,h),l(d)}catch{}}),u=await rr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(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 rr(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(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(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 rr(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(Ie.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Wn(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,Sa(ri({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ri({},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,ri({},r)),this.topicMap.set(r.topic,e),this.events.emit(rt.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}=U("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(rt.deleted,Sa(ri({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rt.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(rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=U("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=>Sa(ri({},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 _E(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("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 St(e+await this.getClientId())}}var WI=Object.defineProperty,uf=Object.getOwnPropertySymbols,GI=Object.prototype.hasOwnProperty,YI=Object.prototype.propertyIsEnumerable,xa=(t,e,r)=>e in t?WI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lf=(t,e)=>{for(var r in e||(e={}))GI.call(e,r)&&xa(t,r,e[r]);if(uf)for(var r of uf(e))YI.call(e,r)&&xa(t,r,e[r]);return t},X=(t,e,r)=>xa(t,typeof e!="symbol"?e+"":e,r);class ZI extends jg{constructor(e){super(e),X(this,"protocol","wc"),X(this,"version",2),X(this,"core"),X(this,"logger"),X(this,"events",new Le.exports.EventEmitter),X(this,"provider"),X(this,"messages"),X(this,"subscriber"),X(this,"publisher"),X(this,"name",Ox),X(this,"transportExplicitlyClosed",!1),X(this,"initialized",!1),X(this,"connectionAttemptInProgress",!1),X(this,"relayUrl"),X(this,"projectId"),X(this,"packageName"),X(this,"bundleId"),X(this,"hasExperiencedNetworkDisruption",!1),X(this,"pingTimeout"),X(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),X(this,"reconnectTimeout"),X(this,"connectPromise"),X(this,"reconnectInProgress",!1),X(this,"requestsInFlight",[]),X(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),X(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Ir().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}}),X(this,"resetPingTimeout",()=>{ji()&&(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))}),X(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),X(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Ie.connect)}),X(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),X(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Ie.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),X(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je(e.logger,this.name):Pt(Is({level:e.logger||Dx})),this.messages=new TI(this.logger,e.core),this.subscriber=new HI(this,this.logger),this.publisher=new LI(this,this.logger),this.relayUrl=e?.relayUrl||Md,this.projectId=e.projectId,sE()?this.packageName=eh():oE()&&(this.bundleId=eh()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return He(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:ce.relay},ss.outbound)}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(rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(rt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,lf({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||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 rr(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.warn("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 Sd())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(L.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,ss.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 subscribe"))};this.provider.once(at.disconnect,s),await rr(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(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.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,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(ji())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 dx(new yx(hE({sdkVersion:ga,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,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}),pa(e)){if(!e.method.endsWith($x))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(lf({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ns(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ss.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const r=da(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Sd();xS(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))})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},L.toMiliseconds(Ax)))))}isInitialized(){if(!this.initialized){const{message:e}=U("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 JI(){}function hf(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 df(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ff(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const XI="[object RegExp]",QI="[object String]",e8="[object Number]",t8="[object Boolean]",pf="[object Arguments]",r8="[object Symbol]",n8="[object Date]",i8="[object Map]",s8="[object Set]",o8="[object Array]",a8="[object Function]",c8="[object ArrayBuffer]",Ia="[object Object]",u8="[object Error]",l8="[object DataView]",h8="[object Uint8Array]",d8="[object Uint8ClampedArray]",f8="[object Uint16Array]",p8="[object Uint32Array]",g8="[object BigUint64Array]",y8="[object Int8Array]",w8="[object Int16Array]",m8="[object Int32Array]",b8="[object BigInt64Array]",v8="[object Float32Array]",E8="[object Float64Array]";function _8(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function S8(t,e,r){return ni(t,e,void 0,void 0,void 0,void 0,r)}function ni(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 ii(t,e,s,o)}return ii(t,e,s,o)}function ii(t,e,r,n){if(Object.is(t,e))return!0;let i=ff(t),s=ff(e);if(i===pf&&(i=Ia),s===pf&&(s=Ia),i!==s)return!1;switch(i){case QI:return t.toString()===e.toString();case e8:{const c=t.valueOf(),u=e.valueOf();return _8(c,u)}case t8:case n8:case r8:return Object.is(t.valueOf(),e.valueOf());case XI:return t.source===e.source&&t.flags===e.flags;case a8: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 i8:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ni(u,e.get(c),c,t,e,r,n))return!1;return!0}case s8:{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],d=u.findIndex(p=>ni(h,p,void 0,t,e,r,n));if(d===-1)return!1;u.splice(d,1)}return!0}case o8:case h8:case d8:case f8:case p8:case g8:case y8:case w8:case m8:case b8:case v8:case E8:{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(!ni(t[c],e[c],c,t,e,r,n))return!1;return!0}case c8:return t.byteLength!==e.byteLength?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case l8:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case u8:return t.name===e.name&&t.message===e.message;case Ia:{if(!(ii(t.constructor,e.constructor,r,n)||hf(t)&&hf(e)))return!1;const c=[...Object.keys(t),...df(t)],u=[...Object.keys(e),...df(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!ni(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function x8(t,e){return S8(t,e,JI)}var I8=Object.defineProperty,gf=Object.getOwnPropertySymbols,D8=Object.prototype.hasOwnProperty,O8=Object.prototype.propertyIsEnumerable,Da=(t,e,r)=>e in t?I8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))D8.call(e,r)&&Da(t,r,e[r]);if(gf)for(var r of gf(e))O8.call(e,r)&&Da(t,r,e[r]);return t},Je=(t,e,r)=>Da(t,typeof e!="symbol"?e+"":e,r);class Pr extends qg{constructor(e,r,n,i=Dt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Je(this,"map",new Map),Je(this,"version",Px),Je(this,"cached",[]),Je(this,"initialized",!1),Je(this,"getKey"),Je(this,"storagePrefix",Dt),Je(this,"recentlyDeleted",[]),Je(this,"recentlyDeletedLimit",200),Je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):tS(o)?this.map.set(o.id,o):rS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Je(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())}),Je(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Je(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>x8(a[c],o[c]))):this.values)),Je(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=yf(yf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Je(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=je(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return He(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}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=U("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}=U("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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var $8=Object.defineProperty,A8=(t,e,r)=>e in t?$8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y=(t,e,r)=>A8(t,typeof e!="symbol"?e+"":e,r);class P8{constructor(e,r){this.core=e,this.logger=r,Y(this,"name",Nx),Y(this,"version",Bx),Y(this,"events",new Le.exports),Y(this,"pairings"),Y(this,"initialized",!1),Y(this,"storagePrefix",Dt),Y(this,"ignoredPayloadTypes",[jt]),Y(this,"registeredMethods",[]),Y(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Y(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Y(this,"create",async n=>{this.isInitialized();const i=ia(),s=await this.core.crypto.setSymKey(i),o=me(L.FIVE_MINUTES),a={protocol:kd},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=gd({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Or.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),Y(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Ot.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=pd(n.uri);i.props.properties.topic=s,i.addTrace(Ot.pairing_uri_validation_success),i.addTrace(Ot.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Ot.existing_pairing),l.active)throw i.setError(Vt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Ot.pairing_not_expired)}const h=c||me(L.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(Ot.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Or.create,d),i.addTrace(Ot.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Ot.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Vt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Vt.subscribe_pairing_topic_failure),p}return i.addTrace(Ot.subscribe_pairing_topic_success),d}),Y(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(L.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Y(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}=br();this.events.once(Q("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Y(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Y(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Y(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Y(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",oe("USER_DISCONNECTED")),await this.deletePairing(i))}),Y(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return gd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Y(this,"sendRequest",async(n,i,s)=>{const o=Dr(i,s),a=await this.core.crypto.encode(n,o),c=Xn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Y(this,"sendResult",async(n,i,s)=>{const o=da(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"sendError",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c]?Xn[c].res:Xn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,oe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Y(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>nr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Y(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)}}),Y(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)}}),Y(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Or.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{It(i)?this.events.emit(Q("pairing_ping",s),{}):ot(i)&&this.events.emit(Q("pairing_ping",s),{error:i.error})},500)}),Y(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Or.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=oe("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)}}),Y(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(oe("WC_METHOD_UNSUPPORTED",n))}),Y(this,"isValidPair",(n,i)=>{var s;if(!Ze(n)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!eS(n.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}const o=pd(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Vt.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Y(this,"isValidPing",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidDisconnect",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidPairingTopic",async n=>{if(!pe(n,!1)){const{message:i}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(nr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=U("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=je(r,this.name),this.pairings=new Pr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return He(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);pa(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ns(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(ct.expired,async e=>{const{topic:r}=ih(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Or.expire,{topic:r}))})}}var T8=Object.defineProperty,R8=(t,e,r)=>e in t?T8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>R8(t,typeof e!="symbol"?e+"":e,r);class C8 extends Ug{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new Le.exports.EventEmitter),Be(this,"name",Fx),Be(this,"version",Lx),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Dt),Be(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)}),Be(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(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ft.created,o)}),Be(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=ot(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ft.updated,i))}),Be(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))),Be(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(ft.deleted,s)}}),this.persist()}),Be(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Be(this,"on",(n,i)=>{this.events.on(n,i)}),Be(this,"once",(n,i)=>{this.events.once(n,i)}),Be(this,"off",(n,i)=>{this.events.off(n,i)}),Be(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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:Dr(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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ft.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=U("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(ft.created,e=>{const r=ft.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.updated,e=>{const r=ft.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.deleted,e=>{const r=ft.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Cr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ft.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var N8=Object.defineProperty,B8=(t,e,r)=>e in t?N8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ke=(t,e,r)=>B8(t,typeof e!="symbol"?e+"":e,r);class F8 extends Vg{constructor(e,r){super(e,r),this.core=e,this.logger=r,ke(this,"expirations",new Map),ke(this,"events",new Le.exports.EventEmitter),ke(this,"name",Ux),ke(this,"version",kx),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"storagePrefix",Dt),ke(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)}),ke(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ke(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(ct.created,{target:s,expiration:o})}),ke(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),ke(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(ct.deleted,{target:i,expiration:s})}}),ke(this,"on",(n,i)=>{this.events.on(n,i)}),ke(this,"once",(n,i)=>{this.events.once(n,i)}),ke(this,"off",(n,i)=>{this.events.off(n,i)}),ke(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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 dE(e);if(typeof e=="number")return fE(e);const{message:r}=U("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(ct.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=U("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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;L.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ct.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Cr.pulse,()=>this.checkExpirations()),this.events.on(ct.created,e=>{const r=ct.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.expired,e=>{const r=ct.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.deleted,e=>{const r=ct.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var L8=Object.defineProperty,U8=(t,e,r)=>e in t?L8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e,r)=>U8(t,typeof e!="symbol"?e+"":e,r);class k8 extends Kg{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,ge(this,"name",Mx),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",qx),ge(this,"storagePrefix",Dt),ge(this,"version",Fd),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async i=>{if(!Cn()||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=_n(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",g),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(Hs(m.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};u.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),ge(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(Hs(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)}),ge(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(L.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}),ge(this,"getVerifyUrl",i=>{let s=i||Qn;return zx.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Qn}`),s=Qn),s}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(L.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)}}),ge(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(this,"isValidJwtAttestation",async 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")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),ge(this,"validateAttestation",(i,s)=>{const o=j_(i,s.publicKey),a={hasExpired:L.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=je(r,this.name),this.abortController=new AbortController,this.isDevEnv=To(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return He(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var M8=Object.defineProperty,j8=(t,e,r)=>e in t?M8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wf=(t,e,r)=>j8(t,typeof e!="symbol"?e+"":e,r);class q8 extends Hg{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,wf(this,"context",Vx),wf(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${Kx}/${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=je(r,this.context)}}var z8=Object.defineProperty,mf=Object.getOwnPropertySymbols,V8=Object.prototype.hasOwnProperty,K8=Object.prototype.propertyIsEnumerable,Oa=(t,e,r)=>e in t?z8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,si=(t,e)=>{for(var r in e||(e={}))V8.call(e,r)&&Oa(t,r,e[r]);if(mf)for(var r of mf(e))K8.call(e,r)&&Oa(t,r,e[r]);return t},De=(t,e,r)=>Oa(t,typeof e!="symbol"?e+"":e,r);class H8 extends Wg{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,De(this,"context",Wx),De(this,"storagePrefix",Dt),De(this,"storageVersion",Hx),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!To())try{const i={eventId:oh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rh(this.core.relayer.protocol,this.core.relayer.version,ga)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),De(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=oh(),l=this.core.projectId||"",h=Date.now(),d=si({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,d),this.shouldPersist=!0),d}),De(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 si(si({},a),this.setMethods(a.eventId))}),De(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),De(this,"setEventListeners",()=>{this.core.heartbeat.on(Cr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(i.timestamp)>Gx&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),De(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),De(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)}),De(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)}),De(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),De(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,si(si({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),De(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)}}),De(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Yx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ga}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>th().url),this.logger=je(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 W8=Object.defineProperty,bf=Object.getOwnPropertySymbols,G8=Object.prototype.hasOwnProperty,Y8=Object.prototype.propertyIsEnumerable,$a=(t,e,r)=>e in t?W8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vf=(t,e)=>{for(var r in e||(e={}))G8.call(e,r)&&$a(t,r,e[r]);if(bf)for(var r of bf(e))Y8.call(e,r)&&$a(t,r,e[r]);return t},ae=(t,e,r)=>$a(t,typeof e!="symbol"?e+"":e,r);class Aa extends Ng{constructor(e){var r;super(e),ae(this,"protocol",Bd),ae(this,"version",Fd),ae(this,"name",is),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new Le.exports.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ce.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||Md,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Is({level:typeof e?.logger=="string"&&e.logger?e.logger:wx.logger,name:is}),{logger:s,chunkLoggerController:o}=Tg({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=je(s,this.name),this.heartbeat=new ms,this.crypto=new SI(this,this.logger,e?.keychain),this.history=new C8(this,this.logger),this.expirer=new F8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ng(vf(vf({},mx),e?.storageOptions)),this.relayer=new ZI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new P8(this,this.logger),this.verify=new k8(this,this.logger,this.storage),this.echoClient=new q8(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new H8(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Aa(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(Tx,n),r}get context(){return He(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(jd,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(jd)||[],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 Pa=Aa,Ef="wc",_f=2,Sf="client",Ta=`${Ef}@${_f}:${Sf}:`,Ra={name:Sf,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xf="WALLETCONNECT_DEEPLINK_CHOICE",Z8="proposal",If="Proposal expired",J8="session",dn=L.SEVEN_DAYS,X8="engine",Oe={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},Ca={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},At={idle:"IDLE",active:"ACTIVE"},Df={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},Q8="request",eD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],tD="wc",rD="auth",nD="authKeys",iD="pairingTopics",sD="requests",cs=`${tD}@${1.5}:${rD}:`,us=`${cs}:PUB_KEY`;var oD=Object.defineProperty,aD=Object.defineProperties,cD=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,uD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,Na=(t,e,r)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))uD.call(e,r)&&Na(t,r,e[r]);if(Of)for(var r of Of(e))lD.call(e,r)&&Na(t,r,e[r]);return t},Ve=(t,e)=>aD(t,cD(e)),R=(t,e,r)=>Na(t,typeof e!="symbol"?e+"":e,r);class hD extends Jg{constructor(e){super(e),R(this,"name",X8),R(this,"events",new Le.exports),R(this,"initialized",!1),R(this,"requestQueue",{state:At.idle,queue:[]}),R(this,"sessionRequestQueue",{state:At.idle,queue:[]}),R(this,"requestQueueDelay",L.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Oe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Ve(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,d=!1;try{if(l){const D=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."),d=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!d){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),f=Oe.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,y=me(f),g=Ve(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:kd}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:xt()}),w=Q("session_connect",g.id),{reject:m,resolve:b,done:E}=br(f,If),$=({id:D})=>{D===g.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(g.id),this.events.emit(w,{error:{message:If,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(w,({error:D,session:S})=>{this.client.events.off("proposal_expire",$),D?m(D):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{uri:h,approval:E}}),R(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}}),R(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:[pt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError($r.no_internet_connection),x}try{await this.isValidProposalId(r?.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError($r.proposal_not_found),x}try{await this.isValidApprove(r)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError($r.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:y,requiredNamespaces:g,optionalNamespaces:w}=p;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:pt.session_approve_started,properties:{topic:f,trace:[pt.session_approve_started,pt.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),E=y.publicKey,$=await this.client.core.crypto.generateSharedKey(b,E),D=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:me(dn)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),S=ce.relay;m.addTrace(pt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:S})}catch(x){throw m.setError($r.subscribe_session_topic_failure),x}m.addTrace(pt.subscribe_session_topic_success);const A=Ve(ie({},D),{topic:$,requiredNamespaces:g,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:b,transportType:ce.relay});await this.client.session.set($,A),m.addTrace(pt.store_session);try{m.addTrace(pt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_settle_publish_failure),x}),m.addTrace(pt.session_settle_publish_success),m.addTrace(pt.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(x=>{throw m?.setError($r.session_approve_publish_failure),x}),m.addTrace(pt.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete($,oe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),x}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,oe("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,me(dn)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),R(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:Oe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED")))}),R(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}=br(),c=xt(),u=Ir().toString(),l=this.client.session.get(n).namespaces;return this.events.once(Q("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}}),R(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=xt(),{done:s,resolve:o,reject:a}=br();return this.events.once(Q("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(dn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=Oe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const c=xt(),u=Ir().toString(),{done:l,resolve:h,reject:d}=br(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:w,result:m})=>{w?d(w):h(m)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},g=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async w=>{await this.sendRequest(ie({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},g&&{tvf:this.getTVFParams(c,y)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await mE(this.client.core.storage,xf);await gE({id:c,topic:s,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),R(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===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);It(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):ot(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(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=xt(),s=Ir().toString(),{done:o,resolve:a,reject:c}=br();this.events.once(Q("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}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Ir().toString(),a=xt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(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:oe("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}=U("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>X_(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(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?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:p,nbf:f,methods:y=[],expiry:g}=r,w=[...r.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const E=await this.client.core.crypto.generateKeyPair(),$=Xi(E);if(await Promise.all([this.client.auth.authKeys.set(us,{responseTopic:$,publicKey:E}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:m})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:P}=Mi(a[0]);let N=u2(P,"request",y);Vi(w)&&(N=h2(N,w.pop())),w.push(N)}const D=g&&g>Oe.wc_sessionAuthenticate.req.ttl?g:Oe.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(D)},A={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:A,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(Oe.wc_sessionPropose.req.ttl),id:xt()},{done:k,resolve:C,reject:B}=br(D,"Request expired"),j=xt(),I=Q("session_connect",x.id),_=Q("session_request",j),v=async({error:P,session:N})=>{this.events.off(_,O),P?B(P):N&&C({session:N})},O=async P=>{var N,F,M;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),P.error){const W=oe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===W.code?void 0:(this.events.off(I,v),B(P.error.message))}await this.deleteProposal(x.id),this.events.off(I,v);const{cacaos:z,responder:q}=P.result,V=[],K=[];for(const W of z){await Eh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(oe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ye}=W,ue=Vi(ye.resources),le=[Lo(ye.iss)],$e=zi(ye.iss);if(ue){const Me=xh(ue),Kt=Ih(ue);V.push(...Me),le.push(...Kt)}for(const Me of le)K.push(`${Me}:${$e}`)}const ee=await this.client.core.crypto.generateSharedKey(E,q.publicKey);let G;V.length>0&&(G={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:me(dn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:yd([...new Set(V)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(ee,{transportType:o}),await this.client.session.set(ee,G),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),G=this.client.session.get(ee)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(F=q.metadata.redirect)!=null&&F.linkMode&&(M=q.metadata.redirect)!=null&&M.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ee,{transportType:ce.link_mode})),C({auths:z,session:G})};this.events.once(I,v),this.events.once(_,O);let T;try{if(s){const P=Dr("wc_sessionAuthenticate",S,j);this.client.core.history.set(m,P);const N=await this.client.core.crypto.encode("",P,{type:Vn,encoding:ar});T=es(n,m,N)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:x,expiry:Oe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(P){throw this.events.off(I,v),this.events.off(_,O),P}return await this.setProposal(x.id,x),await this.setAuthRequest(j,{request:Ve(ie({},S),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:T??b,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Ar.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw s.setError(ei.no_internet_connection),g}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ei.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Xi(c),h={type:jt,receiverPublicKey:c,senderPublicKey:u},d=[],p=[];for(const g of i){if(!await Eh({cacao:g,projectId:this.client.core.projectId})){s.setError(ei.invalid_cacao);const $=oe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:$,encodeOpts:h}),new Error($.message)}s.addTrace(Ar.cacaos_verified);const{p:w}=g,m=Vi(w.resources),b=[Lo(w.iss)],E=zi(w.iss);if(m){const $=xh(m),D=Ih(m);d.push(...$),b.push(...D)}for(const $ of b)p.push(`${$}:${E}`)}const f=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Ar.create_authenticated_session_topic);let y;if(d?.length>0){y={topic:f,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(dn),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:yd([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Ar.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw s.setError(ei.subscribe_authenticated_session_topic_failure),g}s.addTrace(Ar.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),s.addTrace(Ar.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Ar.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(g){throw s.setError(ei.authenticated_session_approve_publish_failure),g}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:y}}),R(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===ce.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Xi(o),u={type:jt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Oe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return _h(n,i)}),R(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)}),R(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)}}),R(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,oe("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(xf).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,oe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=At.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError($r.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,oe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(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=At.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(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)])}),R(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}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Oe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ce.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})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Oe.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})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=Dr(i,s,c);let p;const f=!!l;try{const w=f?ar:dt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let y;if(eD.includes(i)){const w=St(JSON.stringify(d)),m=St(p);y=await this.client.core.verify.register({id:m,decryptedId:w})}const g=Oe[i].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,d),f){const w=es(l,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=Oe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ve(ie({},h),{correlationId:d.id}),u?(w.internal=Ve(ie({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(m=>this.client.logger.error(m))}return d.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=da(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=es(c,i,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,y=Oe[f].res;y.tvf=Ve(ie({},p),{correlationId:n}),o?(y.internal=Ve(ie({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(g=>this.client.logger.error(g))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=fa(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=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=es(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||Oe[p].res;this.client.core.relayer.publish(i,l,f)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;nr(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=>{nr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===At.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=At.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=At.idle}),R(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}`)}}),R(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}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=U("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(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)}),R(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(Vt.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||me(Oe.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Ot.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Oe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(It(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(ot(n)){await this.client.proposal.delete(s,oe("USER_DISCONNECTED"));const o=Q("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})}}),R(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:d}=n.params,p=[...this.pendingSessions.values()].find(g=>g.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),y=Ve(ie(ie(ie({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.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}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Q("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;It(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Q("session_approve",i),{})):ot(n)&&(await this.client.session.delete(r,oe("USER_DISCONNECTED")),this.events.emit(Q("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Yn.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:oe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},i));try{Yn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Yn.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)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=Q("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_update",i),{}):ot(n)&&this.events.emit(Q("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(dn)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!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)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=Q("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_extend",i),{}):ot(n)&&this.events.emit(Q("session_extend",i),{error:n.error})}),R(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)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=Q("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);It(n)?this.events.emit(Q("session_ping",i),{}):ot(n)&&this.events.emit(Q("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Ie.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:oe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(ie({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify(Dr("wc_sessionRequest",d,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(y),l===ce.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(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=Q("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Yn.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}),Yn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(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,d=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ce.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:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:jt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Oe.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=At.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),R(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=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===At.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.sessionRequestQueue.state=At.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(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:Dr("wc_sessionPropose",Ve(ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:u}=U("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(Re(n)||await this.isValidPairingTopic(n),!lS(c,!0)){const{message:u}=U("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Re(i)&&ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Re(s)&&ts(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=uS(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(U("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=oa(i,"approve()");if(u)throw new Error(u.message);const l=Ed(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!pe(s,!0)){const{message:h}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ze(r)){const{message:s}=U("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!dS(i)){const{message:s}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!bd(n)){const{message:u}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=nS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=oa(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(nr(o)){const{message:u}=U("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=U("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=oa(i,"update()");if(o)throw new Error(o.message);const a=Ed(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=U("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(!vd(a,s)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!fS(i)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!yS(a,s,i.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!vS(o,Ca)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ca.min} and ${Ca.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ze(r)){const{message:o}=U("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(!pS(s)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=U("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(!vd(o,s)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!gS(i)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!wS(o,s,i.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(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(!pe(i,!1))throw new Error("uri is required parameter");if(!pe(s,!1))throw new Error("domain is required parameter");if(!pe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Mi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Mi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Qn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.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}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=U("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(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)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,d;return!r||n!==ce.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)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=sh(r,"topic")||"",i=decodeURIComponent(sh(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(To()||tr()&&(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)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Df).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return Ve(ie({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(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}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Df[r];if(typeof n=="string")return[n];const s=n[i.key];if(Gn(s))return r==="solana_signAllTransactions"?s.map(o=>YE(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.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(us)?this.client.auth.authKeys.get(us):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ce.link_mode?ar:dt});pa(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:St(n)})):ns(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(ct.expired,async e=>{const{topic:r,id:n}=ih(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,U("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,U("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(Or.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Or.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!pe(e,!1)){const{message:r}=U("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}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pe(e,!1)){const{message:r}=U("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}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=U("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=U("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(pe(e,!1)){const{message:r}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!hS(e)){const{message:r}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=U("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class dD extends Pr{constructor(e,r){super(e,r,Z8,Ta),this.core=e,this.logger=r}}class $f extends Pr{constructor(e,r){super(e,r,J8,Ta),this.core=e,this.logger=r}}class fD extends Pr{constructor(e,r){super(e,r,Q8,Ta,n=>n.id),this.core=e,this.logger=r}}class pD extends Pr{constructor(e,r){super(e,r,nD,cs,()=>us),this.core=e,this.logger=r}}class gD extends Pr{constructor(e,r){super(e,r,iD,cs),this.core=e,this.logger=r}}class yD extends Pr{constructor(e,r){super(e,r,sD,cs,n=>n.id),this.core=e,this.logger=r}}var wD=Object.defineProperty,mD=(t,e,r)=>e in t?wD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ba=(t,e,r)=>mD(t,typeof e!="symbol"?e+"":e,r);class bD{constructor(e,r){this.core=e,this.logger=r,Ba(this,"authKeys"),Ba(this,"pairingTopics"),Ba(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,r)=>e in t?vD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z=(t,e,r)=>ED(t,typeof e!="symbol"?e+"":e,r);class Fa extends Zg{constructor(e){super(e),Z(this,"protocol",Ef),Z(this,"version",_f),Z(this,"name",Ra.name),Z(this,"metadata"),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Le.exports.EventEmitter),Z(this,"engine"),Z(this,"session"),Z(this,"proposal"),Z(this,"pendingRequest"),Z(this,"auth"),Z(this,"signConfig"),Z(this,"on",(n,i)=>this.events.on(n,i)),Z(this,"once",(n,i)=>this.events.once(n,i)),Z(this,"off",(n,i)=>this.events.off(n,i)),Z(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Z(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Z(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Z(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Z(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ra.name,this.metadata=cE(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Pt(Is({level:e?.logger||Ra.logger}));this.core=e?.core||new Pa(e),this.logger=je(r,this.name),this.session=new $f(this.core,this.logger),this.proposal=new dD(this.core,this.logger),this.pendingRequest=new fD(this.core,this.logger),this.engine=new hD(this),this.auth=new bD(this.core,this.logger)}static async init(e){const r=new Fa(e);return await r.initialize(),r}get context(){return He(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},L.toMiliseconds(L.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const _D=$f,SD=Fa;class xD extends Le.exports{constructor(){super()}}class Af{constructor(e){this.opts=e}}class Pf{constructor(e){this.client=e}}var ID=Object.defineProperty,DD=Object.defineProperties,OD=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,$D=Object.prototype.hasOwnProperty,AD=Object.prototype.propertyIsEnumerable,Rf=(t,e,r)=>e in t?ID(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PD=(t,e)=>{for(var r in e||(e={}))$D.call(e,r)&&Rf(t,r,e[r]);if(Tf)for(var r of Tf(e))AD.call(e,r)&&Rf(t,r,e[r]);return t},TD=(t,e)=>DD(t,OD(e));class RD extends Pf{constructor(e){super(e),this.init=async()=>{this.signClient=await SD.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(TD(PD({},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 CD={decryptMessage:async t=>{const e={core:new Pa({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 Pa({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new _D(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}},Cf=class extends Af{constructor(t){super(t),this.events=new Le.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||ls,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new RD(this)}static async init(t){const e=new Cf(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 La=Cf;La.notifications=CD;const ND=La;Fe.CLIENT_CONTEXT=ls,Fe.CLIENT_STORAGE_OPTIONS=Yf,Fe.CLIENT_STORAGE_PREFIX=Gf,Fe.IWalletKit=Af,Fe.IWalletKitEngine=Pf,Fe.IWalletKitEvents=xD,Fe.PROTOCOL=Za,Fe.PROTOCOL_VERSION=Wf,Fe.REQUEST_CONTEXT=Zf,Fe.WalletKit=ND,Fe.default=La,Object.defineProperty(Fe,"__esModule",{value:!0})});
39
+ ***************************************************************************** */var ua=function(t,e){return ua=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])},ua(t,e)};function FS(t,e){ua(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var la=function(){return la=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},la.apply(this,arguments)};function LS(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 US(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 kS(t,e){return function(r,n){e(r,n,t)}}function MS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function jS(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 qS(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 zS(t,e,r,n){n===void 0&&(n=r),t[n]=e[r]}function VS(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ha(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 $d(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 KS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($d(arguments[e]));return t}function HS(){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 Jn(t){return this instanceof Jn?(this.v=t,this):new Jn(t)}function WS(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(d){n[d]&&(i[d]=function(p){return new Promise(function(f,y){s.push([d,p,f,y])>1||a(d,p)})})}function a(d,p){try{c(n[d](p))}catch(f){h(s[0][3],f)}}function c(d){d.value instanceof Jn?Promise.resolve(d.value.v).then(u,l):h(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function h(d,p){d(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function GS(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:Jn(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function YS(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 ha=="function"?ha(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 ZS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function JS(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 XS(t){return t&&t.__esModule?t:{default:t}}function QS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function ex(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 tx=Object.freeze({__proto__:null,__extends:FS,get __assign(){return la},__rest:LS,__decorate:US,__param:kS,__metadata:MS,__awaiter:jS,__generator:qS,__createBinding:zS,__exportStar:VS,__values:ha,__read:$d,__spread:KS,__spreadArrays:HS,__await:Jn,__asyncGenerator:WS,__asyncDelegator:GS,__asyncValues:YS,__makeTemplateObject:ZS,__importStar:JS,__importDefault:XS,__classPrivateFieldGet:QS,__classPrivateFieldSet:ex}),rx=ka(tx),qt={},Ad;function nx(){if(Ad)return qt;Ad=1,Object.defineProperty(qt,"__esModule",{value:!0}),qt.isBrowserCryptoAvailable=qt.getSubtleCrypto=qt.getBrowerCrypto=void 0;function t(){return yt?.crypto||yt?.msCrypto||{}}qt.getBrowerCrypto=t;function e(){const n=t();return n.subtle||n.webkitSubtle}qt.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return qt.isBrowserCryptoAvailable=r,qt}var zt={},Pd;function ix(){if(Pd)return zt;Pd=1,Object.defineProperty(zt,"__esModule",{value:!0}),zt.isBrowser=zt.isNode=zt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}zt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}zt.isNode=e;function r(){return!t()&&!e()}return zt.isBrowser=r,zt}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=rx;e.__exportStar(nx(),t),e.__exportStar(ix(),t)})(Od);function xt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Or(t=6){return BigInt(xt(t))}function $r(t,e,r){return{id:r||xt(),jsonrpc:"2.0",method:t,params:e}}function da(t,e){return{id:t,jsonrpc:"2.0",result:e}}function fa(t,e,r){return{id:t,jsonrpc:"2.0",error:sx(e,r)}}function sx(t,e){return typeof t>"u"?Dd(xd):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dd(ca)),{message:t})),typeof e<"u"&&(t.data=e),CS(t.code)&&(t=NS(t.code)),t)}class ox{}class ax extends ox{constructor(){super()}}class cx extends ax{constructor(e){super()}}const ux="^wss?:";function lx(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function hx(t,e){const r=lx(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Td(t){return hx(t,ux)}function dx(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Rd(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function pa(t){return Rd(t)&&"method"in t}function ns(t){return Rd(t)&&(It(t)||ot(t))}function It(t){return"result"in t}function ot(t){return"error"in t}class fx extends cx{constructor(e){super(e),this.events=new Le.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($r(e.method,e.params||[],e.id||Or().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=>{ot(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),ns(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 px=()=>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"),gx=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Cd=t=>t.split("?")[0],Nd=10,yx=px();class wx{constructor(e){if(this.url=e,this.events=new Le.exports.EventEmitter,this.registering=!1,!Td(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(fr(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Td(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=Od.isReactNative()?void 0:{rejectUnauthorized:!dx(e)},s=new yx(e,[],i);gx()?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"?Br(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const n=this.parseError(r),i=n.message||n.toString(),s=fa(e,i);this.events.emit("payload",s)}parseError(e,r=this.url){return BS(e,Cd(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Nd&&this.events.setMaxListeners(Nd)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Cd(this.url)}`));return this.events.emit("register_error",r),r}}const Bd="wc",Fd=2,is="core",Dt=`${Bd}@2:${is}:`,mx={name:is,logger:"error"},bx={database:":memory:"},vx="crypto",Ld="client_ed25519_seed",Ex=L.ONE_DAY,_x="keychain",Sx="0.3",xx="messages",Ix="0.3",Ud=L.SIX_HOURS,Dx="publisher",kd="irn",Ox="error",Md="wss://relay.walletconnect.org",$x="relayer",Ie={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"},Ax="_subscription",at={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Px=.1,ga="2.20.3",ce={link_mode:"link_mode",relay:"relay"},ss={inbound:"inbound",outbound:"outbound"},Tx="0.3",Rx="WALLETCONNECT_CLIENT_ID",jd="WALLETCONNECT_LINK_MODE_APPS",rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},Cx="subscription",Nx="0.3",Bx="pairing",Fx="0.3",Xn={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Ar={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},ft={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},Lx="history",Ux="0.3",kx="expirer",ct={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},Mx="0.3",jx="verify-api",qx="https://verify.walletconnect.com",qd="https://verify.walletconnect.org",Qn=qd,zx=`${Qn}/v3`,Vx=[qx,qd],Kx="echo",Hx="https://echo.walletconnect.com",Ot={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"},Vt={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"},pt={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"},Pr={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"},Tr={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"},ei={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"},Wx=.1,Gx="event-client",Yx=86400,Zx="https://pulse.walletconnect.org/batch";function Jx(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(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,g=0,w=0,m=f.length;w!==m&&f[w]===0;)w++,y++;for(var b=(m-w)*l+1>>>0,E=new Uint8Array(b);w!==m;){for(var $=f[w],D=0,S=b-1;($!==0||D<g)&&S!==-1;S--,D++)$+=256*E[S]>>>0,E[S]=$%a>>>0,$=$/a>>>0;if($!==0)throw new Error("Non-zero carry");g=D,w++}for(var A=b-g;A!==b&&E[A]===0;)A++;for(var x=c.repeat(y);A<b;++A)x+=t.charAt(E[A]);return x}function d(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var g=0,w=0;f[y]===c;)g++,y++;for(var m=(f.length-y)*u+1>>>0,b=new Uint8Array(m);f[y];){var E=r[f.charCodeAt(y)];if(E===255)return;for(var $=0,D=m-1;(E!==0||$<w)&&D!==-1;D--,$++)E+=a*b[D]>>>0,b[D]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");w=$,y++}if(f[y]!==" "){for(var S=m-w;S!==m&&b[S]===0;)S++;for(var A=new Uint8Array(g+(m-S)),x=g;S!==m;)A[x++]=b[S++];return A}}}function p(f){var y=d(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:d,decode:p}}var Xx=Jx,Qx=Xx;const zd=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")},e3=t=>new TextEncoder().encode(t),t3=t=>new TextDecoder().decode(t);class r3{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 n3{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 Vd(this,e)}}class i3{constructor(e){this.decoders=e}or(e){return Vd(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 Vd=(t,e)=>new i3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class s3{constructor(e,r,n,i){this.name=e,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new r3(e,r,n),this.decoder=new n3(e,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const os=({name:t,prefix:e,encode:r,decode:n})=>new s3(t,e,r,n),ti=({prefix:t,name:e,alphabet:r})=>{const{encode:n,decode:i}=Qx(r,e);return os({prefix:t,name:e,encode:n,decode:s=>zd(i(s))})},o3=(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},a3=(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},Ce=({name:t,prefix:e,bitsPerChar:r,alphabet:n})=>os({prefix:e,name:t,encode(i){return a3(i,n,r)},decode(i){return o3(i,n,r,t)}}),c3=os({prefix:"\0",name:"identity",encode:t=>t3(t),decode:t=>e3(t)});var u3=Object.freeze({__proto__:null,identity:c3});const l3=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var h3=Object.freeze({__proto__:null,base2:l3});const d3=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var f3=Object.freeze({__proto__:null,base8:d3});const p3=ti({prefix:"9",name:"base10",alphabet:"0123456789"});var g3=Object.freeze({__proto__:null,base10:p3});const y3=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),w3=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var m3=Object.freeze({__proto__:null,base16:y3,base16upper:w3});const b3=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),v3=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),E3=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),_3=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),S3=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),x3=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),I3=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),D3=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),O3=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var $3=Object.freeze({__proto__:null,base32:b3,base32upper:v3,base32pad:E3,base32padupper:_3,base32hex:S3,base32hexupper:x3,base32hexpad:I3,base32hexpadupper:D3,base32z:O3});const A3=ti({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),P3=ti({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var T3=Object.freeze({__proto__:null,base36:A3,base36upper:P3});const R3=ti({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),C3=ti({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var N3=Object.freeze({__proto__:null,base58btc:R3,base58flickr:C3});const B3=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),F3=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),L3=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),U3=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var k3=Object.freeze({__proto__:null,base64:B3,base64pad:F3,base64url:L3,base64urlpad:U3});const Kd=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}"),M3=Kd.reduce((t,e,r)=>(t[r]=e,t),[]),j3=Kd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function q3(t){return t.reduce((e,r)=>(e+=M3[r],e),"")}function z3(t){const e=[];for(const r of t){const n=j3[r.codePointAt(0)];if(n===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(n)}return new Uint8Array(e)}const V3=os({prefix:"\u{1F680}",name:"base256emoji",encode:q3,decode:z3});var K3=Object.freeze({__proto__:null,base256emoji:V3}),H3=Wd,Hd=128,W3=127,G3=~W3,Y3=Math.pow(2,31);function Wd(t,e,r){e=e||[],r=r||0;for(var n=r;t>=Y3;)e[r++]=t&255|Hd,t/=128;for(;t&G3;)e[r++]=t&255|Hd,t>>>=7;return e[r]=t|0,Wd.bytes=r-n+1,e}var Z3=ya,J3=128,Gd=127;function ya(t,n){var r=0,n=n||0,i=0,s=n,o,a=t.length;do{if(s>=a)throw ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=i<28?(o&Gd)<<i:(o&Gd)*Math.pow(2,i),i+=7}while(o>=J3);return ya.bytes=s-n,r}var X3=Math.pow(2,7),Q3=Math.pow(2,14),eI=Math.pow(2,21),tI=Math.pow(2,28),rI=Math.pow(2,35),nI=Math.pow(2,42),iI=Math.pow(2,49),sI=Math.pow(2,56),oI=Math.pow(2,63),aI=function(t){return t<X3?1:t<Q3?2:t<eI?3:t<tI?4:t<rI?5:t<nI?6:t<iI?7:t<sI?8:t<oI?9:10},cI={encode:H3,decode:Z3,encodingLength:aI},Yd=cI;const Zd=(t,e,r=0)=>(Yd.encode(t,e,r),e),Jd=t=>Yd.encodingLength(t),wa=(t,e)=>{const r=e.byteLength,n=Jd(t),i=n+Jd(r),s=new Uint8Array(i+r);return Zd(t,s,0),Zd(r,s,n),s.set(e,i),new uI(t,r,e,s)};class uI{constructor(e,r,n,i){this.code=e,this.size=r,this.digest=n,this.bytes=i}}const Xd=({name:t,code:e,encode:r})=>new lI(t,e,r);class lI{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?wa(this.code,r):r.then(n=>wa(this.code,n))}else throw Error("Unknown type, must be binary type")}}const Qd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),hI=Xd({name:"sha2-256",code:18,encode:Qd("SHA-256")}),dI=Xd({name:"sha2-512",code:19,encode:Qd("SHA-512")});var fI=Object.freeze({__proto__:null,sha256:hI,sha512:dI});const ef=0,pI="identity",tf=zd;var gI=Object.freeze({__proto__:null,identity:{code:ef,name:pI,encode:tf,digest:t=>wa(ef,tf(t))}});new TextEncoder,new TextDecoder;const rf={...u3,...h3,...f3,...g3,...m3,...$3,...T3,...N3,...k3,...K3};({...fI,...gI});function yI(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?globalThis.Buffer.allocUnsafe(t):new Uint8Array(t)}function nf(t,e,r,n){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:n}}}const sf=nf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ma=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=yI(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),wI={utf8:sf,"utf-8":sf,hex:rf.base16,latin1:ma,ascii:ma,binary:ma,...rf};function mI(t,e="utf8"){const r=wI[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,"utf8"):r.decoder.decode(`${r.prefix}${t}`)}var bI=Object.defineProperty,vI=(t,e,r)=>e in t?bI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$t=(t,e,r)=>vI(t,typeof e!="symbol"?e+"":e,r);class EI{constructor(e,r){this.core=e,this.logger=r,$t(this,"keychain",new Map),$t(this,"name",_x),$t(this,"version",Sx),$t(this,"initialized",!1),$t(this,"storagePrefix",Dt),$t(this,"init",async()=>{if(!this.initialized){const n=await this.getKeyChain();typeof n<"u"&&(this.keychain=n),this.initialized=!0}}),$t(this,"has",n=>(this.isInitialized(),this.keychain.has(n))),$t(this,"set",async(n,i)=>{this.isInitialized(),this.keychain.set(n,i),await this.persist()}),$t(this,"get",n=>{this.isInitialized();const i=this.keychain.get(n);if(typeof i>"u"){const{message:s}=U("NO_MATCHING_KEY",`${this.name}: ${n}`);throw new Error(s)}return i}),$t(this,"del",async n=>{this.isInitialized(),this.keychain.delete(n),await this.persist()}),this.core=e,this.logger=je(r,this.name)}get context(){return He(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ao(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var _I=Object.defineProperty,SI=(t,e,r)=>e in t?_I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ne=(t,e,r)=>SI(t,typeof e!="symbol"?e+"":e,r);class xI{constructor(e,r,n){this.core=e,this.logger=r,Ne(this,"name",vx),Ne(this,"keychain"),Ne(this,"randomSessionIdentifier",ia()),Ne(this,"initialized",!1),Ne(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Ne(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Ne(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=wu(i);return yu(s.publicKey)}),Ne(this,"generateKeyPair",()=>{this.isInitialized();const i=C_();return this.setPrivateKey(i.publicKey,i.privateKey)}),Ne(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=wu(s),a=this.randomSessionIdentifier;return await Mm(a,i,Ex,o)}),Ne(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=N_(a,s);return this.setSymKey(c,o)}),Ne(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||Xi(i);return await this.keychain.set(o,i),o}),Ne(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Ne(this,"encode",async(i,s,o)=>{this.isInitialized();const a=hd(o),c=fr(s);if(fd(a))return L_(c,o?.encoding);if(dd(a)){const d=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(d,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return B_({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Ne(this,"decode",async(i,s,o)=>{this.isInitialized();const a=k_(s,o);if(fd(a)){const c=U_(s,o?.encoding);return Br(c)}if(dd(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=F_({symKey:c,encoded:s,encoding:o?.encoding});return Br(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Ne(this,"getPayloadType",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return Dr(o.type)}),Ne(this,"getPayloadSenderPublicKey",(i,s=dt)=>{const o=Hn({encoded:i,encoding:s});return o.senderPublicKey?Ge(o.senderPublicKey,ze):void 0}),this.core=e,this.logger=je(r,this.name),this.keychain=n||new EI(this.core,this.logger)}get context(){return He(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(Ld)}catch{e=ia(),await this.keychain.set(Ld,e)}return mI(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var II=Object.defineProperty,DI=Object.defineProperties,OI=Object.getOwnPropertyDescriptors,of=Object.getOwnPropertySymbols,$I=Object.prototype.hasOwnProperty,AI=Object.prototype.propertyIsEnumerable,ba=(t,e,r)=>e in t?II(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,PI=(t,e)=>{for(var r in e||(e={}))$I.call(e,r)&&ba(t,r,e[r]);if(of)for(var r of of(e))AI.call(e,r)&&ba(t,r,e[r]);return t},TI=(t,e)=>DI(t,OI(e)),nt=(t,e,r)=>ba(t,typeof e!="symbol"?e+"":e,r);class RI extends kg{constructor(e,r){super(e,r),this.logger=e,this.core=r,nt(this,"messages",new Map),nt(this,"messagesWithoutClientAck",new Map),nt(this,"name",xx),nt(this,"version",Ix),nt(this,"initialized",!1),nt(this,"storagePrefix",Dt),nt(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}}}),nt(this,"set",async(n,i,s)=>{this.isInitialized();const o=St(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===ss.inbound){const c=this.messagesWithoutClientAck.get(n)||{};this.messagesWithoutClientAck.set(n,TI(PI({},c),{[o]:i}))}return await this.persist(),o}),nt(this,"get",n=>{this.isInitialized();let i=this.messages.get(n);return typeof i>"u"&&(i={}),i}),nt(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}),nt(this,"has",(n,i)=>{this.isInitialized();const s=this.get(n),o=St(i);return typeof s[o]<"u"}),nt(this,"ack",async(n,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(n);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(n):this.messagesWithoutClientAck.set(n,s),await this.persist()}),nt(this,"del",async n=>{this.isInitialized(),this.messages.delete(n),this.messagesWithoutClientAck.delete(n),await this.persist()}),this.logger=je(e,this.name),this.core=r}get context(){return He(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,Ao(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ao(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Po(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Po(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var CI=Object.defineProperty,NI=Object.defineProperties,BI=Object.getOwnPropertyDescriptors,af=Object.getOwnPropertySymbols,FI=Object.prototype.hasOwnProperty,LI=Object.prototype.propertyIsEnumerable,va=(t,e,r)=>e in t?CI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,as=(t,e)=>{for(var r in e||(e={}))FI.call(e,r)&&va(t,r,e[r]);if(af)for(var r of af(e))LI.call(e,r)&&va(t,r,e[r]);return t},Ea=(t,e)=>NI(t,BI(e)),gt=(t,e,r)=>va(t,typeof e!="symbol"?e+"":e,r);class UI extends Mg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,gt(this,"events",new Le.exports.EventEmitter),gt(this,"name",Dx),gt(this,"queue",new Map),gt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),gt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),gt(this,"needsTransportRestart",!1),gt(this,"publish",async(n,i,s)=>{var o;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:n,message:i,opts:s}});const a=s?.ttl||Ud,c=Qi(s),u=s?.prompt||!1,l=s?.tag||0,h=s?.id||Or().toString(),d={topic:n,message:i,opts:{ttl:a,relay:c,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}},p=`Failed to publish payload, please try again. id:${h} tag:${l}`;try{const f=new Promise(async y=>{const g=({id:m})=>{d.opts.id===m&&(this.removeRequestFromQueue(m),this.relayer.events.removeListener(Ie.publish,g),y(d))};this.relayer.events.on(Ie.publish,g);const w=rr(new Promise((m,b)=>{this.rpcPublish({topic:n,message:i,ttl:a,prompt:u,tag:l,id:h,attestation:s?.attestation,tvf:s?.tvf}).then(m).catch(E=>{this.logger.warn(E,E?.message),b(E)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${h} tag:${l}`);try{await w,this.events.removeListener(Ie.publish,g)}catch(m){this.queue.set(h,Ea(as({},d),{attempt:1})),this.logger.warn(m,m?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:h,topic:n,message:i,opts:s}}),await rr(f,this.publishTimeout,p)}catch(f){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(f),(o=s?.internal)!=null&&o.throwOnFailedPublish)throw f}finally{this.queue.delete(h)}}),gt(this,"on",(n,i)=>{this.events.on(n,i)}),gt(this,"once",(n,i)=>{this.events.once(n,i)}),gt(this,"off",(n,i)=>{this.events.off(n,i)}),gt(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.relayer=e,this.logger=je(r,this.name),this.registerEventListeners()}get context(){return He(this.logger)}async rpcPublish(e){var r,n,i,s;const{topic:o,message:a,ttl:c=Ud,prompt:u,tag:l,id:h,attestation:d,tvf:p}=e,f={method:Wn(Qi().protocol).publish,params:as({topic:o,message:a,ttl:c,prompt:u,tag:l,attestation:d},p),id:h};Re((r=f.params)==null?void 0:r.prompt)&&((n=f.params)==null||delete n.prompt),Re((i=f.params)==null?void 0:i.tag)&&((s=f.params)==null||delete s.tag),this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:f});const y=await this.relayer.request(f);return this.relayer.events.emit(Ie.publish,e),this.logger.debug("Successfully Published Payload"),y}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{const n=e.attempt+1;this.queue.set(r,Ea(as({},e),{attempt:n}));const{topic:i,message:s,opts:o,attestation:a}=e;this.logger.warn({},`Publisher: queue->publishing: ${e.opts.id}, tag: ${e.opts.tag}, attempt: ${n}`),await this.rpcPublish(Ea(as({},e),{topic:i,message:s,ttl:o.ttl,prompt:o.prompt,tag:o.tag,id:o.id,attestation:a,tvf:o.tvf})),this.logger.warn({},`Publisher: queue->published: ${e.opts.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Ie.connection_stalled);return}this.checkQueue()}),this.relayer.on(Ie.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var kI=Object.defineProperty,MI=(t,e,r)=>e in t?kI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fn=(t,e,r)=>MI(t,typeof e!="symbol"?e+"":e,r);class jI{constructor(){fn(this,"map",new Map),fn(this,"set",(e,r)=>{const n=this.get(e);this.exists(e,r)||this.map.set(e,[...n,r])}),fn(this,"get",e=>this.map.get(e)||[]),fn(this,"exists",(e,r)=>this.get(e).includes(r)),fn(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)}),fn(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var qI=Object.defineProperty,zI=Object.defineProperties,VI=Object.getOwnPropertyDescriptors,cf=Object.getOwnPropertySymbols,KI=Object.prototype.hasOwnProperty,HI=Object.prototype.propertyIsEnumerable,_a=(t,e,r)=>e in t?qI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ri=(t,e)=>{for(var r in e||(e={}))KI.call(e,r)&&_a(t,r,e[r]);if(cf)for(var r of cf(e))HI.call(e,r)&&_a(t,r,e[r]);return t},Sa=(t,e)=>zI(t,VI(e)),ne=(t,e,r)=>_a(t,typeof e!="symbol"?e+"":e,r);class WI extends zg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ne(this,"subscriptions",new Map),ne(this,"topicMap",new jI),ne(this,"events",new Le.exports.EventEmitter),ne(this,"name",Cx),ne(this,"version",Nx),ne(this,"pending",new Map),ne(this,"cached",[]),ne(this,"initialized",!1),ne(this,"storagePrefix",Dt),ne(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ne(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"clientId"),ne(this,"batchSubscribeTopicsLimit",500),ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ne(this,"subscribe",async(n,i)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}});try{const s=Qi(i),o={topic:n,relay:s,transportType:i?.transportType};this.pending.set(n,o);const a=await this.rpcSubscribe(n,s,i);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:n,opts:i}})),a}catch(s){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(s),s}}),ne(this,"unsubscribe",async(n,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(n,i.id,i):await this.unsubscribeByTopic(n,i)}),ne(this,"isSubscribed",n=>new Promise(i=>{i(this.topicMap.topics.includes(n))})),ne(this,"isKnownTopic",n=>new Promise(i=>{i(this.topicMap.topics.includes(n)||this.pending.has(n)||this.cached.some(s=>s.topic===n))})),ne(this,"on",(n,i)=>{this.events.on(n,i)}),ne(this,"once",(n,i)=>{this.events.once(n,i)}),ne(this,"off",(n,i)=>{this.events.off(n,i)}),ne(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),ne(this,"start",async()=>{await this.onConnect()}),ne(this,"stop",async()=>{await this.onDisconnect()}),ne(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ne(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)}),ne(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hr.pulse,async()=>{await this.checkPending()}),this.events.on(rt.created,async n=>{const i=rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()}),this.events.on(rt.deleted,async n=>{const i=rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:n}),await this.persist()})}),this.relayer=e,this.logger=je(r,this.name),this.clientId=""}get context(){return He(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=Qi(n);await this.restartToComplete({topic:e,id:r,relay:i}),await this.rpcUnsubscribe(e,r,i);const s=oe("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;(!n||n?.transportType===ce.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const s={method:Wn(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s});const o=(i=n?.internal)==null?void 0:i.throwOnFailedPublish;try{const a=await this.getSubscriptionId(e);if(n?.transportType===ce.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(s).catch(l=>this.logger.warn(l))},L.toMiliseconds(L.ONE_SECOND)),a;const c=new Promise(async l=>{const h=d=>{d.topic===e&&(this.events.removeListener(rt.created,h),l(d.id))};this.events.on(rt.created,h);try{const d=await rr(new Promise((p,f)=>{this.relayer.request(s).catch(y=>{this.logger.warn(y,y?.message),f(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(rt.created,h),l(d)}catch{}}),u=await rr(c,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return u?a:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(Ie.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(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 rr(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(Ie.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,n={method:Wn(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 rr(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(Ie.connection_stalled)}return i}rpcUnsubscribe(e,r,n){const i={method:Wn(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,Sa(ri({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,ri({},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,ri({},r)),this.topicMap.set(r.topic,e),this.events.emit(rt.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}=U("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(rt.deleted,Sa(ri({},n),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(rt.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(rt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size){const{message:r}=U("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=>Sa(ri({},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 _E(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=U("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 St(e+await this.getClientId())}}var GI=Object.defineProperty,uf=Object.getOwnPropertySymbols,YI=Object.prototype.hasOwnProperty,ZI=Object.prototype.propertyIsEnumerable,xa=(t,e,r)=>e in t?GI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,lf=(t,e)=>{for(var r in e||(e={}))YI.call(e,r)&&xa(t,r,e[r]);if(uf)for(var r of uf(e))ZI.call(e,r)&&xa(t,r,e[r]);return t},X=(t,e,r)=>xa(t,typeof e!="symbol"?e+"":e,r);class JI extends jg{constructor(e){super(e),X(this,"protocol","wc"),X(this,"version",2),X(this,"core"),X(this,"logger"),X(this,"events",new Le.exports.EventEmitter),X(this,"provider"),X(this,"messages"),X(this,"subscriber"),X(this,"publisher"),X(this,"name",$x),X(this,"transportExplicitlyClosed",!1),X(this,"initialized",!1),X(this,"connectionAttemptInProgress",!1),X(this,"relayUrl"),X(this,"projectId"),X(this,"packageName"),X(this,"bundleId"),X(this,"hasExperiencedNetworkDisruption",!1),X(this,"pingTimeout"),X(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),X(this,"reconnectTimeout"),X(this,"connectPromise"),X(this,"reconnectInProgress",!1),X(this,"requestsInFlight",[]),X(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),X(this,"request",async r=>{var n,i;this.logger.debug("Publishing Request Payload");const s=r.id||Or().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}}),X(this,"resetPingTimeout",()=>{ji()&&(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))}),X(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),X(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Ie.connect)}),X(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),X(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Ie.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),X(this,"registerProviderListeners",()=>{this.provider.on(at.payload,this.onPayloadHandler),this.provider.on(at.connect,this.onConnectHandler),this.provider.on(at.disconnect,this.onDisconnectHandler),this.provider.on(at.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?je(e.logger,this.name):Pt(Is({level:e.logger||Ox})),this.messages=new RI(this.logger,e.core),this.subscriber=new WI(this,this.logger),this.publisher=new UI(this,this.logger),this.relayUrl=e?.relayUrl||Md,this.projectId=e.projectId,sE()?this.packageName=eh():oE()&&(this.bundleId=eh()),this.provider={}}async init(){if(this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.subscriber.hasAnyTopics)try{await this.transportOpen()}catch(e){this.logger.warn(e,e?.message)}}get context(){return He(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:ce.relay},ss.outbound)}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(rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(rt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,lf({internal:{throwOnFailedPublish:o}},r)).catch(d=>{o&&h(d)})||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 rr(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.warn("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 Sd())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(L.FIVE_MINUTES),s={topic:n,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(n,s)}this.events.emit(Ie.message,e),await this.recordMessageEvent(e,ss.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 subscribe"))};this.provider.once(at.disconnect,s),await rr(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(at.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{a(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(at.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(at.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,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,n,i,s;if(ji())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 fx(new wx(hE({sdkVersion:ga,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,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}),pa(e)){if(!e.method.endsWith(Ax))return;const r=e.params,{topic:n,message:i,publishedAt:s,attestation:o}=r.data,a={topic:n,message:i,publishedAt:s,transportType:ce.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(lf({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ns(e)&&this.events.emit(Ie.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ss.inbound),this.events.emit(Ie.message,e))}async acknowledgePayload(e){const r=da(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(at.payload,this.onPayloadHandler),this.provider.off(at.connect,this.onConnectHandler),this.provider.off(at.disconnect,this.onDisconnectHandler),this.provider.off(at.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Sd();xS(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(hr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&OS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Ie.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},L.toMiliseconds(Px)))))}isInitialized(){if(!this.initialized){const{message:e}=U("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 XI(){}function hf(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 df(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ff(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const QI="[object RegExp]",e8="[object String]",t8="[object Number]",r8="[object Boolean]",pf="[object Arguments]",n8="[object Symbol]",i8="[object Date]",s8="[object Map]",o8="[object Set]",a8="[object Array]",c8="[object Function]",u8="[object ArrayBuffer]",Ia="[object Object]",l8="[object Error]",h8="[object DataView]",d8="[object Uint8Array]",f8="[object Uint8ClampedArray]",p8="[object Uint16Array]",g8="[object Uint32Array]",y8="[object BigUint64Array]",w8="[object Int8Array]",m8="[object Int16Array]",b8="[object Int32Array]",v8="[object BigInt64Array]",E8="[object Float32Array]",_8="[object Float64Array]";function S8(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function x8(t,e,r){return ni(t,e,void 0,void 0,void 0,void 0,r)}function ni(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 ii(t,e,s,o)}return ii(t,e,s,o)}function ii(t,e,r,n){if(Object.is(t,e))return!0;let i=ff(t),s=ff(e);if(i===pf&&(i=Ia),s===pf&&(s=Ia),i!==s)return!1;switch(i){case e8:return t.toString()===e.toString();case t8:{const c=t.valueOf(),u=e.valueOf();return S8(c,u)}case r8:case i8:case n8:return Object.is(t.valueOf(),e.valueOf());case QI:return t.source===e.source&&t.flags===e.flags;case c8: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 s8:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!ni(u,e.get(c),c,t,e,r,n))return!1;return!0}case o8:{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],d=u.findIndex(p=>ni(h,p,void 0,t,e,r,n));if(d===-1)return!1;u.splice(d,1)}return!0}case a8:case d8:case f8:case p8:case g8:case y8:case w8:case m8:case b8:case v8:case E8:case _8:{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(!ni(t[c],e[c],c,t,e,r,n))return!1;return!0}case u8:return t.byteLength!==e.byteLength?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case h8:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ii(new Uint8Array(t),new Uint8Array(e),r,n);case l8:return t.name===e.name&&t.message===e.message;case Ia:{if(!(ii(t.constructor,e.constructor,r,n)||hf(t)&&hf(e)))return!1;const c=[...Object.keys(t),...df(t)],u=[...Object.keys(e),...df(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],d=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!ni(d,p,h,t,e,r,n))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function I8(t,e){return x8(t,e,XI)}var D8=Object.defineProperty,gf=Object.getOwnPropertySymbols,O8=Object.prototype.hasOwnProperty,$8=Object.prototype.propertyIsEnumerable,Da=(t,e,r)=>e in t?D8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,yf=(t,e)=>{for(var r in e||(e={}))O8.call(e,r)&&Da(t,r,e[r]);if(gf)for(var r of gf(e))$8.call(e,r)&&Da(t,r,e[r]);return t},Je=(t,e,r)=>Da(t,typeof e!="symbol"?e+"":e,r);class Rr extends qg{constructor(e,r,n,i=Dt,s=void 0){super(e,r,n,i),this.core=e,this.logger=r,this.name=n,Je(this,"map",new Map),Je(this,"version",Tx),Je(this,"cached",[]),Je(this,"initialized",!1),Je(this,"getKey"),Je(this,"storagePrefix",Dt),Je(this,"recentlyDeleted",[]),Je(this,"recentlyDeletedLimit",200),Je(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):tS(o)?this.map.set(o.id,o):rS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Je(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())}),Je(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Je(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>I8(a[c],o[c]))):this.values)),Je(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=yf(yf({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Je(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=je(r,this.name),this.storagePrefix=i,this.getKey=s}get context(){return He(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}=U("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:n}=U("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}=U("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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var A8=Object.defineProperty,P8=(t,e,r)=>e in t?A8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Y=(t,e,r)=>P8(t,typeof e!="symbol"?e+"":e,r);class T8{constructor(e,r){this.core=e,this.logger=r,Y(this,"name",Bx),Y(this,"version",Fx),Y(this,"events",new Le.exports),Y(this,"pairings"),Y(this,"initialized",!1),Y(this,"storagePrefix",Dt),Y(this,"ignoredPayloadTypes",[jt]),Y(this,"registeredMethods",[]),Y(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Y(this,"register",({methods:n})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...n])]}),Y(this,"create",async n=>{this.isInitialized();const i=ia(),s=await this.core.crypto.setSymKey(i),o=me(L.FIVE_MINUTES),a={protocol:kd},c={topic:s,expiry:o,relay:a,active:!1,methods:n?.methods},u=gd({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:n?.methods});return this.events.emit(Ar.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:n?.transportType}),{topic:s,uri:u}}),Y(this,"pair",async n=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:n?.uri,trace:[Ot.pairing_started]}});this.isValidPair(n,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=pd(n.uri);i.props.properties.topic=s,i.addTrace(Ot.pairing_uri_validation_success),i.addTrace(Ot.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Ot.existing_pairing),l.active)throw i.setError(Vt.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Ot.pairing_not_expired)}const h=c||me(L.FIVE_MINUTES),d={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,d),i.addTrace(Ot.store_new_pairing),n.activatePairing&&await this.activate({topic:s}),this.events.emit(Ar.create,d),i.addTrace(Ot.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Ot.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(Vt.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(Vt.subscribe_pairing_topic_failure),p}return i.addTrace(Ot.subscribe_pairing_topic_success),d}),Y(this,"activate",async({topic:n})=>{this.isInitialized();const i=me(L.FIVE_MINUTES);this.core.expirer.set(n,i),await this.pairings.update(n,{active:!0,expiry:i})}),Y(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}=Er();this.events.once(Q("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Y(this,"updateExpiry",async({topic:n,expiry:i})=>{this.isInitialized(),await this.pairings.update(n,{expiry:i})}),Y(this,"updateMetadata",async({topic:n,metadata:i})=>{this.isInitialized(),await this.pairings.update(n,{peerMetadata:i})}),Y(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Y(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",oe("USER_DISCONNECTED")),await this.deletePairing(i))}),Y(this,"formatUriFromPairing",n=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=n,c=this.core.crypto.keychain.get(i);return gd({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Y(this,"sendRequest",async(n,i,s)=>{const o=$r(i,s),a=await this.core.crypto.encode(n,o),c=Xn[i].req;return this.core.history.set(n,o),this.core.relayer.publish(n,a,c),o.id}),Y(this,"sendResult",async(n,i,s)=>{const o=da(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"sendError",async(n,i,s)=>{const o=fa(n,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,n)).request.method,u=Xn[c]?Xn[c].res:Xn.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Y(this,"deletePairing",async(n,i)=>{await this.core.relayer.unsubscribe(n),await Promise.all([this.pairings.delete(n,oe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(n),i?Promise.resolve():this.core.expirer.del(n)])}),Y(this,"cleanup",async()=>{const n=this.pairings.getAll().filter(i=>nr(i.expiry));await Promise.all(n.map(i=>this.deletePairing(i.topic)))}),Y(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)}}),Y(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)}}),Y(this,"onPairingPingRequest",async(n,i)=>{const{id:s}=i;try{this.isValidPing({topic:n}),await this.sendResult(s,n,!0),this.events.emit(Ar.ping,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onPairingPingResponse",(n,i)=>{const{id:s}=i;setTimeout(()=>{It(i)?this.events.emit(Q("pairing_ping",s),{}):ot(i)&&this.events.emit(Q("pairing_ping",s),{error:i.error})},500)}),Y(this,"onPairingDeleteRequest",async(n,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:n}),await this.deletePairing(n),this.events.emit(Ar.delete,{id:s,topic:n})}catch(o){await this.sendError(s,n,o),this.logger.error(o)}}),Y(this,"onUnknownRpcMethodRequest",async(n,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=oe("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)}}),Y(this,"onUnknownRpcMethodResponse",n=>{this.registeredMethods.includes(n)||this.logger.error(oe("WC_METHOD_UNSUPPORTED",n))}),Y(this,"isValidPair",(n,i)=>{var s;if(!Ze(n)){const{message:a}=U("MISSING_OR_INVALID",`pair() params: ${n}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!eS(n.uri)){const{message:a}=U("MISSING_OR_INVALID",`pair() uri: ${n.uri}`);throw i.setError(Vt.malformed_pairing_uri),new Error(a)}const o=pd(n?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=U("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(Vt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(Vt.pairing_expired);const{message:a}=U("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Y(this,"isValidPing",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidDisconnect",async n=>{if(!Ze(n)){const{message:s}=U("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:i}=n;await this.isValidPairingTopic(i)}),Y(this,"isValidPairingTopic",async n=>{if(!pe(n,!1)){const{message:i}=U("MISSING_OR_INVALID",`pairing topic should be a string: ${n}`);throw new Error(i)}if(!this.pairings.keys.includes(n)){const{message:i}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${n}`);throw new Error(i)}if(nr(this.pairings.get(n).expiry)){await this.deletePairing(n);const{message:i}=U("EXPIRED",`pairing topic: ${n}`);throw new Error(i)}}),this.core=e,this.logger=je(r,this.name),this.pairings=new Rr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return He(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Ie.message,async e=>{const{topic:r,message:n,transportType:i}=e;if(this.pairings.keys.includes(r)&&i!==ce.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(n)))try{const s=await this.core.crypto.decode(r,n);pa(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ns(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(ct.expired,async e=>{const{topic:r}=ih(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ar.expire,{topic:r}))})}}var R8=Object.defineProperty,C8=(t,e,r)=>e in t?R8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>C8(t,typeof e!="symbol"?e+"":e,r);class N8 extends Ug{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new Le.exports.EventEmitter),Be(this,"name",Lx),Be(this,"version",Ux),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Dt),Be(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)}),Be(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(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(ft.created,o)}),Be(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=ot(n)?{error:n.error}:{result:n.result},this.records.set(i.id,i),this.persist(),this.events.emit(ft.updated,i))}),Be(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))),Be(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(ft.deleted,s)}}),this.persist()}),Be(this,"exists",async(n,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===n:!1)),Be(this,"on",(n,i)=>{this.events.on(n,i)}),Be(this,"once",(n,i)=>{this.events.once(n,i)}),Be(this,"off",(n,i)=>{this.events.off(n,i)}),Be(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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:$r(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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(n)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(ft.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=U("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(ft.created,e=>{const r=ft.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.updated,e=>{const r=ft.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(ft.deleted,e=>{const r=ft.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(hr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(ft.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var B8=Object.defineProperty,F8=(t,e,r)=>e in t?B8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ke=(t,e,r)=>F8(t,typeof e!="symbol"?e+"":e,r);class L8 extends Vg{constructor(e,r){super(e,r),this.core=e,this.logger=r,ke(this,"expirations",new Map),ke(this,"events",new Le.exports.EventEmitter),ke(this,"name",kx),ke(this,"version",Mx),ke(this,"cached",[]),ke(this,"initialized",!1),ke(this,"storagePrefix",Dt),ke(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)}),ke(this,"has",n=>{try{const i=this.formatTarget(n);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ke(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(ct.created,{target:s,expiration:o})}),ke(this,"get",n=>{this.isInitialized();const i=this.formatTarget(n);return this.getExpiration(i)}),ke(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(ct.deleted,{target:i,expiration:s})}}),ke(this,"on",(n,i)=>{this.events.on(n,i)}),ke(this,"once",(n,i)=>{this.events.once(n,i)}),ke(this,"off",(n,i)=>{this.events.off(n,i)}),ke(this,"removeListener",(n,i)=>{this.events.removeListener(n,i)}),this.logger=je(r,this.name)}get context(){return He(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 dE(e);if(typeof e=="number")return fE(e);const{message:r}=U("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(ct.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=U("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}=U("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(n),new Error(n)}return r}checkExpiry(e,r){const{expiry:n}=r;L.toMiliseconds(n)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(ct.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(hr.pulse,()=>this.checkExpirations()),this.events.on(ct.created,e=>{const r=ct.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.expired,e=>{const r=ct.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(ct.deleted,e=>{const r=ct.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}}var U8=Object.defineProperty,k8=(t,e,r)=>e in t?U8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ge=(t,e,r)=>k8(t,typeof e!="symbol"?e+"":e,r);class M8 extends Kg{constructor(e,r,n){super(e,r,n),this.core=e,this.logger=r,this.store=n,ge(this,"name",jx),ge(this,"abortController"),ge(this,"isDevEnv"),ge(this,"verifyUrlV3",zx),ge(this,"storagePrefix",Dt),ge(this,"version",Fd),ge(this,"publicKey"),ge(this,"fetchPromise"),ge(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ge(this,"register",async i=>{if(!Xr()||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=yr(),l=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((d,p)=>{const f=()=>{window.removeEventListener("message",g),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",f);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",f,{signal:this.abortController.signal});const g=w=>{if(w.data&&typeof w.data=="string")try{const m=JSON.parse(w.data);if(m.type==="verify_attestation"){if(Hs(m.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",f),window.removeEventListener("message",g),d(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};u.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),ge(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(Hs(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)}),ge(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(L.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}),ge(this,"getVerifyUrl",i=>{let s=i||Qn;return Vx.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Qn}`),s=Qn),s}),ge(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(L.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)}}),ge(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ge(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ge(this,"isValidJwtAttestation",async 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")}}),ge(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ge(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),ge(this,"validateAttestation",(i,s)=>{const o=j_(i,s.publicKey),a={hasExpired:L.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=je(r,this.name),this.abortController=new AbortController,this.isDevEnv=To(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return He(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var j8=Object.defineProperty,q8=(t,e,r)=>e in t?j8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,wf=(t,e,r)=>q8(t,typeof e!="symbol"?e+"":e,r);class z8 extends Hg{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,wf(this,"context",Kx),wf(this,"registerDeviceToken",async n=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=n,c=`${Hx}/${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=je(r,this.context)}}var V8=Object.defineProperty,mf=Object.getOwnPropertySymbols,K8=Object.prototype.hasOwnProperty,H8=Object.prototype.propertyIsEnumerable,Oa=(t,e,r)=>e in t?V8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,si=(t,e)=>{for(var r in e||(e={}))K8.call(e,r)&&Oa(t,r,e[r]);if(mf)for(var r of mf(e))H8.call(e,r)&&Oa(t,r,e[r]);return t},De=(t,e,r)=>Oa(t,typeof e!="symbol"?e+"":e,r);class W8 extends Wg{constructor(e,r,n=!0){super(e,r,n),this.core=e,this.logger=r,De(this,"context",Gx),De(this,"storagePrefix",Dt),De(this,"storageVersion",Wx),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!To())try{const i={eventId:oh(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:rh(this.core.relayer.protocol,this.core.relayer.version,ga)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),De(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=oh(),l=this.core.projectId||"",h=Date.now(),d=si({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,d),this.shouldPersist=!0),d}),De(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 si(si({},a),this.setMethods(a.eventId))}),De(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),De(this,"setEventListeners",()=>{this.core.heartbeat.on(hr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(i.timestamp)>Yx&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),De(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),De(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)}),De(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)}),De(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),De(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,si(si({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),De(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)}}),De(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${Zx}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${ga}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>th().url),this.logger=je(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 G8=Object.defineProperty,bf=Object.getOwnPropertySymbols,Y8=Object.prototype.hasOwnProperty,Z8=Object.prototype.propertyIsEnumerable,$a=(t,e,r)=>e in t?G8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vf=(t,e)=>{for(var r in e||(e={}))Y8.call(e,r)&&$a(t,r,e[r]);if(bf)for(var r of bf(e))Z8.call(e,r)&&$a(t,r,e[r]);return t},ae=(t,e,r)=>$a(t,typeof e!="symbol"?e+"":e,r);class Aa extends Ng{constructor(e){var r;super(e),ae(this,"protocol",Bd),ae(this,"version",Fd),ae(this,"name",is),ae(this,"relayUrl"),ae(this,"projectId"),ae(this,"customStoragePrefix"),ae(this,"events",new Le.exports.EventEmitter),ae(this,"logger"),ae(this,"heartbeat"),ae(this,"relayer"),ae(this,"crypto"),ae(this,"storage"),ae(this,"history"),ae(this,"expirer"),ae(this,"pairing"),ae(this,"verify"),ae(this,"echoClient"),ae(this,"linkModeSupportedApps"),ae(this,"eventClient"),ae(this,"initialized",!1),ae(this,"logChunkController"),ae(this,"on",(a,c)=>this.events.on(a,c)),ae(this,"once",(a,c)=>this.events.once(a,c)),ae(this,"off",(a,c)=>this.events.off(a,c)),ae(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ae(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ce.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||Md,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Is({level:typeof e?.logger=="string"&&e.logger?e.logger:mx.logger,name:is}),{logger:s,chunkLoggerController:o}=Tg({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=je(s,this.name),this.heartbeat=new ms,this.crypto=new xI(this,this.logger,e?.keychain),this.history=new N8(this,this.logger),this.expirer=new L8(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new ng(vf(vf({},bx),e?.storageOptions)),this.relayer=new JI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new T8(this,this.logger),this.verify=new M8(this,this.logger,this.storage),this.echoClient=new z8(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new W8(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new Aa(e);await r.initialize();const n=await r.crypto.getClientId();return await r.storage.setItem(Rx,n),r}get context(){return He(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(jd,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(jd)||[],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 Pa=Aa,Ef="wc",_f=2,Sf="client",Ta=`${Ef}@${_f}:${Sf}:`,Ra={name:Sf,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},xf="WALLETCONNECT_DEEPLINK_CHOICE",J8="proposal",If="Proposal expired",X8="session",pn=L.SEVEN_DAYS,Q8="engine",Oe={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},Ca={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},At={idle:"IDLE",active:"ACTIVE"},Df={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"}},eD="request",tD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],rD="wc",nD="auth",iD="authKeys",sD="pairingTopics",oD="requests",cs=`${rD}@${1.5}:${nD}:`,us=`${cs}:PUB_KEY`;var aD=Object.defineProperty,cD=Object.defineProperties,uD=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,lD=Object.prototype.hasOwnProperty,hD=Object.prototype.propertyIsEnumerable,Na=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ie=(t,e)=>{for(var r in e||(e={}))lD.call(e,r)&&Na(t,r,e[r]);if(Of)for(var r of Of(e))hD.call(e,r)&&Na(t,r,e[r]);return t},Ve=(t,e)=>cD(t,uD(e)),R=(t,e,r)=>Na(t,typeof e!="symbol"?e+"":e,r);class dD extends Jg{constructor(e){super(e),R(this,"name",Q8),R(this,"events",new Le.exports),R(this,"initialized",!1),R(this,"requestQueue",{state:At.idle,queue:[]}),R(this,"sessionRequestQueue",{state:At.idle,queue:[]}),R(this,"requestQueueDelay",L.ONE_SECOND),R(this,"expectedPairingMethodMap",new Map),R(this,"recentlyDeletedMap",new Map),R(this,"recentlyDeletedLimit",200),R(this,"relayMessageCache",[]),R(this,"pendingSessions",new Map),R(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Oe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),R(this,"connect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Ve(ie({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n);const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=n;let l=i,h,d=!1;try{if(l){const D=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."),d=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),D}if(!l||!d){const{topic:D,uri:S}=await this.client.core.pairing.create();l=D,h=S}if(!l){const{message:D}=U("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(D)}const p=await this.client.core.crypto.generateKeyPair(),f=Oe.wc_sessionPropose.req.ttl||L.FIVE_MINUTES,y=me(f),g=Ve(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:kd}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:y,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:xt()}),w=Q("session_connect",g.id),{reject:m,resolve:b,done:E}=Er(f,If),$=({id:D})=>{D===g.id&&(this.client.events.off("proposal_expire",$),this.pendingSessions.delete(g.id),this.events.emit(w,{error:{message:If,code:0}}))};return this.client.events.on("proposal_expire",$),this.events.once(w,({error:D,session:S})=>{this.client.events.off("proposal_expire",$),D?m(D):S&&b(S)}),await this.sendRequest({topic:l,method:"wc_sessionPropose",params:g,throwOnFailedPublish:!0,clientRpcId:g.id}),await this.setProposal(g.id,g),{uri:h,approval:E}}),R(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}}),R(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:[pt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(x){throw o.setError(Pr.no_internet_connection),x}try{await this.isValidProposalId(r?.id)}catch(x){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(Pr.proposal_not_found),x}try{await this.isValidApprove(r)}catch(x){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Pr.session_approve_namespace_validation_failure),x}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:f,proposer:y,requiredNamespaces:g,optionalNamespaces:w}=p;let m=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:f});m||(m=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:pt.session_approve_started,properties:{topic:f,trace:[pt.session_approve_started,pt.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),E=y.publicKey,$=await this.client.core.crypto.generateSharedKey(b,E),D=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:me(pn)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),d&&{sessionConfig:d}),S=ce.relay;m.addTrace(pt.subscribing_session_topic);try{await this.client.core.relayer.subscribe($,{transportType:S})}catch(x){throw m.setError(Pr.subscribe_session_topic_failure),x}m.addTrace(pt.subscribe_session_topic_success);const A=Ve(ie({},D),{topic:$,requiredNamespaces:g,optionalNamespaces:w,pairingTopic:f,acknowledged:!1,self:D.controller,peer:{publicKey:y.publicKey,metadata:y.metadata},controller:b,transportType:ce.relay});await this.client.session.set($,A),m.addTrace(pt.store_session);try{m.addTrace(pt.publishing_session_settle),await this.sendRequest({topic:$,method:"wc_sessionSettle",params:D,throwOnFailedPublish:!0}).catch(x=>{throw m?.setError(Pr.session_settle_publish_failure),x}),m.addTrace(pt.session_settle_publish_success),m.addTrace(pt.publishing_session_approve),await this.sendResult({id:a,topic:f,result:{relay:{protocol:c??"irn"},responderPublicKey:b},throwOnFailedPublish:!0}).catch(x=>{throw m?.setError(Pr.session_approve_publish_failure),x}),m.addTrace(pt.session_approve_publish_success)}catch(x){throw this.client.logger.error(x),this.client.session.delete($,oe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe($),x}return this.client.core.eventClient.deleteEvent({eventId:m.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:y.metadata}),await this.client.proposal.delete(a,oe("USER_DISCONNECTED")),await this.client.core.pairing.activate({topic:f}),await this.setExpiry($,me(pn)),{topic:$,acknowledged:()=>Promise.resolve(this.client.session.get($))}}),R(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:Oe.wc_sessionPropose.reject}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED")))}),R(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}=Er(),c=xt(),u=Or().toString(),l=this.client.session.get(n).namespaces;return this.events.once(Q("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}}),R(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=xt(),{done:s,resolve:o,reject:a}=Er();return this.events.once(Q("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(n,me(pn)),this.sendRequest({topic:n,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),R(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:n,request:i,topic:s,expiry:o=Oe.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);a?.transportType===ce.relay&&await this.confirmOnlineStateOrThrow();const c=xt(),u=Or().toString(),{done:l,resolve:h,reject:d}=Er(o,"Request expired. Please try again.");this.events.once(Q("session_request",c),({error:w,result:m})=>{w?d(w):h(m)});const p="wc_sessionRequest",f=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(f)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},expiry:o,throwOnFailedPublish:!0,appLink:f}).catch(w=>d(w)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),await l();const y={request:Ve(ie({},i),{expiryTimestamp:me(o)}),chainId:n},g=this.shouldSetTVF(p,y);return await Promise.all([new Promise(async w=>{await this.sendRequest(ie({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:y,expiry:o,throwOnFailedPublish:!0},g&&{tvf:this.getTVFParams(c,y)})).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:n,id:c}),w()}),new Promise(async w=>{var m;if(!((m=a.sessionConfig)!=null&&m.disableDeepLink)){const b=await mE(this.client.core.storage,xf);await gE({id:c,topic:s,wcDeepLink:b})}w()}),l()]).then(w=>w[2])}),R(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===ce.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);It(i)?await this.sendResult({id:s,topic:n,result:i.result,throwOnFailedPublish:!0,appLink:a}):ot(i)&&await this.sendError({id:s,topic:n,error:i.error,appLink:a}),this.cleanupAfterResponse(r)}),R(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=xt(),s=Or().toString(),{done:o,resolve:a,reject:c}=Er();this.events.once(Q("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}))}),R(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:n,event:i,chainId:s}=r,o=Or().toString(),a=xt();await this.sendRequest({topic:n,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),R(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:oe("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}=U("MISMATCHED_TOPIC",`Session or pairing topic not found: ${n}`);throw new Error(i)}}),R(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(n=>X_(n,r)))),R(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),R(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?ce.link_mode:ce.relay;o===ce.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:d,exp:p,nbf:f,methods:y=[],expiry:g}=r,w=[...r.resources||[]],{topic:m,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:b}});const E=await this.client.core.crypto.generateKeyPair(),$=Xi(E);if(await Promise.all([this.client.auth.authKeys.set(us,{responseTopic:$,publicKey:E}),this.client.auth.pairingTopics.set($,{topic:$,pairingTopic:m})]),await this.client.core.relayer.subscribe($,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:P}=Mi(a[0]);let N=u2(P,"request",y);Vi(w)&&(N=h2(N,w.pop())),w.push(N)}const D=g&&g>Oe.wc_sessionAuthenticate.req.ttl?g:Oe.wc_sessionAuthenticate.req.ttl,S={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:f,resources:w},requester:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(D)},A={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},x={requiredNamespaces:{},optionalNamespaces:A,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:E,metadata:this.client.metadata},expiryTimestamp:me(Oe.wc_sessionPropose.req.ttl),id:xt()},{done:k,resolve:C,reject:B}=Er(D,"Request expired"),j=xt(),I=Q("session_connect",x.id),_=Q("session_request",j),v=async({error:P,session:N})=>{this.events.off(_,O),P?B(P):N&&C({session:N})},O=async P=>{var N,F,M;if(await this.deletePendingAuthRequest(j,{message:"fulfilled",code:0}),P.error){const W=oe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return P.error.code===W.code?void 0:(this.events.off(I,v),B(P.error.message))}await this.deleteProposal(x.id),this.events.off(I,v);const{cacaos:z,responder:q}=P.result,V=[],K=[];for(const W of z){await Eh({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(oe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ye}=W,ue=Vi(ye.resources),le=[Lo(ye.iss)],$e=zi(ye.iss);if(ue){const Me=xh(ue),Kt=Ih(ue);V.push(...Me),le.push(...Kt)}for(const Me of le)K.push(`${Me}:${$e}`)}const ee=await this.client.core.crypto.generateSharedKey(E,q.publicKey);let G;V.length>0&&(G={topic:ee,acknowledged:!0,self:{publicKey:E,metadata:this.client.metadata},peer:q,controller:q.publicKey,expiry:me(pn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:yd([...new Set(V)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(ee,{transportType:o}),await this.client.session.set(ee,G),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:q.metadata}),G=this.client.session.get(ee)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(F=q.metadata.redirect)!=null&&F.linkMode&&(M=q.metadata.redirect)!=null&&M.universal&&n&&(this.client.core.addLinkModeSupportedApp(q.metadata.redirect.universal),this.client.session.update(ee,{transportType:ce.link_mode})),C({auths:z,session:G})};this.events.once(I,v),this.events.once(_,O);let T;try{if(s){const P=$r("wc_sessionAuthenticate",S,j);this.client.core.history.set(m,P);const N=await this.client.core.crypto.encode("",P,{type:Vn,encoding:ar});T=es(n,m,N)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:S,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:j}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:x,expiry:Oe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:x.id})])}catch(P){throw this.events.off(I,v),this.events.off(_,O),P}return await this.setProposal(x.id,x),await this.setAuthRequest(j,{request:Ve(ie({},S),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:T??b,response:k}}),R(this,"approveSessionAuthenticate",async r=>{const{id:n,auths:i}=r,s=this.client.core.eventClient.createEvent({properties:{topic:n.toString(),trace:[Tr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw s.setError(ei.no_internet_connection),g}const o=this.getPendingAuthRequest(n);if(!o)throw s.setError(ei.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${n}`);const a=o.transportType||ce.relay;a===ce.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=Xi(c),h={type:jt,receiverPublicKey:c,senderPublicKey:u},d=[],p=[];for(const g of i){if(!await Eh({cacao:g,projectId:this.client.core.projectId})){s.setError(ei.invalid_cacao);const $=oe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:n,topic:l,error:$,encodeOpts:h}),new Error($.message)}s.addTrace(Tr.cacaos_verified);const{p:w}=g,m=Vi(w.resources),b=[Lo(w.iss)],E=zi(w.iss);if(m){const $=xh(m),D=Ih(m);d.push(...$),b.push(...D)}for(const $ of b)p.push(`${$}:${E}`)}const f=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Tr.create_authenticated_session_topic);let y;if(d?.length>0){y={topic:f,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:me(pn),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:yd([...new Set(d)],[...new Set(p)]),transportType:a},s.addTrace(Tr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(f,{transportType:a})}catch(g){throw s.setError(ei.subscribe_authenticated_session_topic_failure),g}s.addTrace(Tr.subscribe_authenticated_session_topic_success),await this.client.session.set(f,y),s.addTrace(Tr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Tr.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(g){throw s.setError(ei.authenticated_session_approve_publish_failure),g}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:y}}),R(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===ce.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Xi(o),u={type:jt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:n,topic:c,error:i,encodeOpts:u,rpcOpts:Oe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(n,{message:"rejected",code:0}),await this.client.proposal.delete(n,oe("USER_DISCONNECTED"))}),R(this,"formatAuthMessage",r=>{this.isInitialized();const{request:n,iss:i}=r;return _h(n,i)}),R(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)}),R(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)}}),R(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,oe("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(xf).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,oe("USER_DISCONNECTED"))}),i===((n=this.sessionRequestQueue.queue[0])==null?void 0:n.topic)&&(this.sessionRequestQueue.state=At.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),R(this,"deleteProposal",async(r,n)=>{if(n)try{const i=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(Pr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,oe("USER_DISCONNECTED")),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),R(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=At.idle,this.client.events.emit("session_request_expire",{id:r}))}),R(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)])}),R(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}))}),R(this,"setProposal",async(r,n)=>{this.client.core.expirer.set(r,me(Oe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,n)}),R(this,"setAuthRequest",async(r,n)=>{const{request:i,pairingTopic:s,transportType:o=ce.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})}),R(this,"setPendingSessionRequest",async r=>{const{id:n,topic:i,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||me(Oe.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})}),R(this,"sendRequest",async r=>{const{topic:n,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h}=r,d=$r(i,s,c);let p;const f=!!l;try{const w=f?ar:dt;p=await this.client.core.crypto.encode(n,d,{encoding:w})}catch(w){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${n} failed`),w}let y;if(tD.includes(i)){const w=St(JSON.stringify(d)),m=St(p);y=await this.client.core.verify.register({id:m,decryptedId:w})}const g=Oe[i].req;if(g.attestation=y,o&&(g.ttl=o),a&&(g.id=a),this.client.core.history.set(n,d),f){const w=es(l,n,p);await global.Linking.openURL(w,this.client.name)}else{const w=Oe[i].req;o&&(w.ttl=o),a&&(w.id=a),w.tvf=Ve(ie({},h),{correlationId:d.id}),u?(w.internal=Ve(ie({},w.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,p,w)):this.client.core.relayer.publish(n,p,w).catch(m=>this.client.logger.error(m))}return d.id}),R(this,"sendResult",async r=>{const{id:n,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=da(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const f=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},a||{}),{encoding:f}))}catch(f){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),f}let d,p;try{d=await this.client.core.history.get(i,n);const f=d.request;try{this.shouldSetTVF(f.method,f.params)&&(p=this.getTVFParams(n,f.params,s))}catch(y){this.client.logger.warn("sendResult() -> getTVFParams() failed",y)}}catch(f){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${n}) failed`),f}if(h){const f=es(c,i,l);await global.Linking.openURL(f,this.client.name)}else{const f=d.request.method,y=Oe[f].res;y.tvf=Ve(ie({},p),{correlationId:n}),o?(y.internal=Ve(ie({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,y)):this.client.core.relayer.publish(i,l,y).catch(g=>this.client.logger.error(g))}await this.client.core.history.resolve(u)}),R(this,"sendError",async r=>{const{id:n,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=fa(n,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?ar:dt;l=await this.client.core.crypto.encode(i,u,Ve(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let d;try{d=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=es(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,f=a||Oe[p].res;this.client.core.relayer.publish(i,l,f)}await this.client.core.history.resolve(u)}),R(this,"cleanup",async()=>{const r=[],n=[];this.client.session.getAll().forEach(i=>{let s=!1;nr(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=>{nr(i.expiryTimestamp)&&n.push(i.id)}),await Promise.all([...r.map(i=>this.deleteSession({topic:i})),...n.map(i=>this.deleteProposal(i))])}),R(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),R(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),R(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===At.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=At.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(n){this.client.logger.warn(n)}}this.requestQueue.state=At.idle}),R(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}`)}}),R(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}`)}}),R(this,"onRelayEventUnknownPayload",r=>{const{topic:n}=r,{message:i}=U("MISSING_OR_INVALID",`Decoded payload on topic ${n} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),R(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)}),R(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(Vt.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||me(Oe.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:n,expiryTimestamp:l},a);await this.setProposal(c,h);const d=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Ot.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:d})}catch(u){await this.sendError({id:c,topic:n,error:u,rpcOpts:Oe.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),R(this,"onSessionProposeResponse",async(r,n,i)=>{const{id:s}=n;if(It(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(ot(n)){await this.client.proposal.delete(s,oe("USER_DISCONNECTED"));const o=Q("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})}}),R(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:d}=n.params,p=[...this.pendingSessions.values()].find(g=>g.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const f=this.client.proposal.get(p.proposalId),y=Ve(ie(ie(ie({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:f.requiredNamespaces,optionalNamespaces:f.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}),d&&{sessionConfig:d}),{transportType:ce.relay});await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:y.peer.metadata}),this.client.events.emit("session_connect",{session:y}),this.events.emit(Q("session_connect",p.proposalId),{session:y}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:n.id,topic:r,result:!0,throwOnFailedPublish:!0})}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionSettleResponse",async(r,n)=>{const{id:i}=n;It(n)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(Q("session_approve",i),{})):ot(n)&&(await this.client.session.delete(r,oe("USER_DISCONNECTED")),this.events.emit(Q("session_approve",i),{error:n.error}))}),R(this,"onSessionUpdateRequest",async(r,n)=>{const{params:i,id:s}=n;try{const o=`${r}_session_update`,a=Yn.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:oe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:r},i));try{Yn.set(o,s),await this.client.session.update(r,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0})}catch(c){throw Yn.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)}}),R(this,"isRequestOutOfSync",(r,n)=>n.toString().slice(0,-3)<r.toString().slice(0,-3)),R(this,"onSessionUpdateResponse",(r,n)=>{const{id:i}=n,s=Q("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_update",i),{}):ot(n)&&this.events.emit(Q("session_update",i),{error:n.error})}),R(this,"onSessionExtendRequest",async(r,n)=>{const{id:i}=n;try{this.isValidExtend({topic:r}),await this.setExpiry(r,me(pn)),await this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!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)}}),R(this,"onSessionExtendResponse",(r,n)=>{const{id:i}=n,s=Q("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_extend",i),{}):ot(n)&&this.events.emit(Q("session_extend",i),{error:n.error})}),R(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)}}),R(this,"onSessionPingResponse",(r,n)=>{const{id:i}=n,s=Q("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);It(n)?this.events.emit(Q("session_ping",i),{}):ot(n)&&this.events.emit(Q("session_ping",i),{error:n.error})},500)}),R(this,"onSessionDeleteRequest",async(r,n)=>{const{id:i}=n;try{this.isValidDisconnect({topic:r,reason:n.params}),Promise.all([new Promise(s=>{this.client.core.relayer.once(Ie.publish,async()=>{s(await this.deleteSession({topic:r,id:i}))})}),this.sendResult({id:i,topic:r,result:!0,throwOnFailedPublish:!0}),this.cleanupPendingSentRequestsForTopic({topic:r,error:oe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),R(this,"onSessionRequest",async r=>{var n,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:d}=a;try{await this.isValidRequest(ie({topic:o},d));const p=this.client.session.get(o),f=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify($r("wc_sessionRequest",d,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:d,verifyContext:f};await this.setPendingSessionRequest(y),l===ce.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(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),R(this,"onSessionRequestResponse",(r,n)=>{const{id:i}=n,s=Q("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(this,"onSessionEventRequest",async(r,n)=>{const{id:i,params:s}=n;try{const o=`${r}_session_event_${s.event.name}`,a=Yn.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}),Yn.set(o,i)}catch(o){await this.sendError({id:i,topic:r,error:o}),this.client.logger.error(o)}}),R(this,"onSessionAuthenticateResponse",(r,n)=>{const{id:i}=n;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:n}),It(n)?this.events.emit(Q("session_request",i),{result:n.result}):ot(n)&&this.events.emit(Q("session_request",i),{error:n.error})}),R(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,d=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===ce.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:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:jt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Oe.wc_sessionAuthenticate.autoReject,appLink:d})}}),R(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),R(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=At.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),R(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=Q("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(Q("session_request",s.request.id),{error:n})})}),R(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===At.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.sessionRequestQueue.state=At.active,this.emitSessionRequest(r)}catch(n){this.client.logger.error(n)}}),R(this,"emitSessionRequest",r=>{this.client.events.emit("session_request",r)}),R(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:$r("wc_sessionPropose",Ve(ie({},n),{requiredNamespaces:n.requiredNamespaces,optionalNamespaces:n.optionalNamespaces,relays:n.relays,proposer:n.proposer,sessionProperties:n.sessionProperties,scopedProperties:n.scopedProperties}),n.id)})}),R(this,"isValidConnect",async r=>{if(!Ze(r)){const{message:u}=U("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(Re(n)||await this.isValidPairingTopic(n),!lS(c,!0)){const{message:u}=U("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!Re(i)&&ts(i)!==0&&this.validateNamespaces(i,"requiredNamespaces"),!Re(s)&&ts(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l)))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),R(this,"validateNamespaces",(r,n)=>{const i=uS(r,"connect()",n);if(i)throw new Error(i.message)}),R(this,"isValidApprove",async r=>{if(!Ze(r))throw new Error(U("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=oa(i,"approve()");if(u)throw new Error(u.message);const l=Ed(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!pe(s,!0)){const{message:h}=U("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(Re(o)||this.validateSessionProps(o,"sessionProperties"),!Re(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(d=>h.has(d)))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),R(this,"isValidReject",async r=>{if(!Ze(r)){const{message:s}=U("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:n,reason:i}=r;if(this.checkRecentlyDeleted(n),await this.isValidProposalId(n),!dS(i)){const{message:s}=U("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),R(this,"isValidSessionSettleRequest",r=>{if(!Ze(r)){const{message:u}=U("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:n,controller:i,namespaces:s,expiry:o}=r;if(!bd(n)){const{message:u}=U("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=nS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=oa(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(nr(o)){const{message:u}=U("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),R(this,"isValidUpdate",async r=>{if(!Ze(r)){const{message:c}=U("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=oa(i,"update()");if(o)throw new Error(o.message);const a=Ed(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),R(this,"isValidExtend",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(i)}const{topic:n}=r;this.checkRecentlyDeleted(n),await this.isValidSessionTopic(n)}),R(this,"isValidRequest",async r=>{if(!Ze(r)){const{message:c}=U("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(!vd(a,s)){const{message:c}=U("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!fS(i)){const{message:c}=U("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!yS(a,s,i.method)){const{message:c}=U("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!vS(o,Ca)){const{message:c}=U("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${Ca.min} and ${Ca.max}`);throw new Error(c)}}),R(this,"isValidRespond",async r=>{var n;if(!Ze(r)){const{message:o}=U("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(!pS(s)){const{message:o}=U("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),R(this,"isValidPing",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(this,"isValidEmit",async r=>{if(!Ze(r)){const{message:a}=U("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(!vd(o,s)){const{message:a}=U("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!gS(i)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!wS(o,s,i.name)){const{message:a}=U("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),R(this,"isValidDisconnect",async r=>{if(!Ze(r)){const{message:i}=U("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:n}=r;await this.isValidSessionOrPairingTopic(n)}),R(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(!pe(i,!1))throw new Error("uri is required parameter");if(!pe(s,!1))throw new Error("domain is required parameter");if(!pe(o,!1))throw new Error("nonce is required parameter");if([...new Set(n.map(c=>Mi(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Mi(n[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),R(this,"getVerifyContext",async r=>{const{attestationId:n,hash:i,encryptedId:s,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Qn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ce.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}),R(this,"validateSessionProps",(r,n)=>{Object.values(r).forEach((i,s)=>{if(i==null){const{message:o}=U("MISSING_OR_INVALID",`${n} must contain an existing value for each key. Received: ${i} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),R(this,"getPendingAuthRequest",r=>{const n=this.client.auth.requests.get(r);return typeof n=="object"?n:void 0}),R(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)}}}),R(this,"checkRecentlyDeleted",r=>{const n=this.recentlyDeletedMap.get(r);if(n){const{message:i}=U("MISSING_OR_INVALID",`Record was recently deleted - ${n}: ${r}`);throw new Error(i)}}),R(this,"isLinkModeEnabled",(r,n)=>{var i,s,o,a,c,u,l,h,d;return!r||n!==ce.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)!==""&&((d=r?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),R(this,"getAppLinkIfEnabled",(r,n)=>{var i;return this.isLinkModeEnabled(r,n)?(i=r?.redirect)==null?void 0:i.universal:void 0}),R(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const n=sh(r,"topic")||"",i=decodeURIComponent(sh(r,"wc_ev")||""),s=this.client.session.keys.includes(n);s&&this.client.session.update(n,{transportType:ce.link_mode}),this.client.core.dispatchEnvelope({topic:n,message:i,sessionExists:s})}),R(this,"registerLinkModeListeners",async()=>{var r;if(To()||tr()&&(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)}}}),R(this,"shouldSetTVF",(r,n)=>{if(!n||r!=="wc_sessionRequest")return!1;const{request:i}=n;return Object.keys(Df).includes(i.method)}),R(this,"getTVFParams",(r,n,i)=>{var s,o;try{const a=n.request.method,c=this.extractTxHashesFromResult(a,i);return Ve(ie({correlationId:r,rpcMethods:[a],chainId:n.chainId},this.isValidContractData(n.request.params)&&{contractAddresses:[(o=(s=n.request.params)==null?void 0:s[0])==null?void 0:o.to]}),{txHashes:c})}catch(a){this.client.logger.warn("Error getting TVF params",a)}return{}}),R(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}),R(this,"extractTxHashesFromResult",(r,n)=>{try{const i=Df[r];if(typeof n=="string")return[n];const s=n[i.key];if(Gn(s))return r==="solana_signAllTransactions"?s.map(o=>YE(o)):s;if(typeof s=="string")return[s]}catch(i){this.client.logger.warn("Error extracting tx hashes from result",i)}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}=U("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Ie.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(us)?this.client.auth.authKeys.get(us):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,n,{receiverPublicKey:o,encoding:s===ce.link_mode?ar:dt});pa(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:i,transportType:s,encryptedId:St(n)})):ns(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(ct.expired,async e=>{const{topic:r,id:n}=ih(e.target);if(n&&this.client.pendingRequest.keys.includes(n))return await this.deletePendingSessionRequest(n,U("EXPIRED"),!0);if(n&&this.client.auth.requests.keys.includes(n))return await this.deletePendingAuthRequest(n,U("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(Ar.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Ar.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!pe(e,!1)){const{message:r}=U("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}=U("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=U("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!pe(e,!1)){const{message:r}=U("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}=U("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=U("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=U("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(pe(e,!1)){const{message:r}=U("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=U("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!hS(e)){const{message:r}=U("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=U("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(nr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=U("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}}class fD extends Rr{constructor(e,r){super(e,r,J8,Ta),this.core=e,this.logger=r}}class $f extends Rr{constructor(e,r){super(e,r,X8,Ta),this.core=e,this.logger=r}}class pD extends Rr{constructor(e,r){super(e,r,eD,Ta,n=>n.id),this.core=e,this.logger=r}}class gD extends Rr{constructor(e,r){super(e,r,iD,cs,()=>us),this.core=e,this.logger=r}}class yD extends Rr{constructor(e,r){super(e,r,sD,cs),this.core=e,this.logger=r}}class wD extends Rr{constructor(e,r){super(e,r,oD,cs,n=>n.id),this.core=e,this.logger=r}}var mD=Object.defineProperty,bD=(t,e,r)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ba=(t,e,r)=>bD(t,typeof e!="symbol"?e+"":e,r);class vD{constructor(e,r){this.core=e,this.logger=r,Ba(this,"authKeys"),Ba(this,"pairingTopics"),Ba(this,"requests"),this.authKeys=new gD(this.core,this.logger),this.pairingTopics=new yD(this.core,this.logger),this.requests=new wD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var ED=Object.defineProperty,_D=(t,e,r)=>e in t?ED(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Z=(t,e,r)=>_D(t,typeof e!="symbol"?e+"":e,r);class Fa extends Zg{constructor(e){super(e),Z(this,"protocol",Ef),Z(this,"version",_f),Z(this,"name",Ra.name),Z(this,"metadata"),Z(this,"core"),Z(this,"logger"),Z(this,"events",new Le.exports.EventEmitter),Z(this,"engine"),Z(this,"session"),Z(this,"proposal"),Z(this,"pendingRequest"),Z(this,"auth"),Z(this,"signConfig"),Z(this,"on",(n,i)=>this.events.on(n,i)),Z(this,"once",(n,i)=>this.events.once(n,i)),Z(this,"off",(n,i)=>this.events.off(n,i)),Z(this,"removeListener",(n,i)=>this.events.removeListener(n,i)),Z(this,"removeAllListeners",n=>this.events.removeAllListeners(n)),Z(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"pair",async n=>{try{return await this.engine.pair(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approve",async n=>{try{return await this.engine.approve(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"reject",async n=>{try{return await this.engine.reject(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"update",async n=>{try{return await this.engine.update(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"extend",async n=>{try{return await this.engine.extend(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"request",async n=>{try{return await this.engine.request(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"respond",async n=>{try{return await this.engine.respond(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"ping",async n=>{try{return await this.engine.ping(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"emit",async n=>{try{return await this.engine.emit(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"find",n=>{try{return this.engine.find(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(n){throw this.logger.error(n.message),n}}),Z(this,"authenticate",async(n,i)=>{try{return await this.engine.authenticate(n,i)}catch(s){throw this.logger.error(s.message),s}}),Z(this,"formatAuthMessage",n=>{try{return this.engine.formatAuthMessage(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"approveSessionAuthenticate",async n=>{try{return await this.engine.approveSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),Z(this,"rejectSessionAuthenticate",async n=>{try{return await this.engine.rejectSessionAuthenticate(n)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ra.name,this.metadata=cE(e?.metadata),this.signConfig=e?.signConfig;const r=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Pt(Is({level:e?.logger||Ra.logger}));this.core=e?.core||new Pa(e),this.logger=je(r,this.name),this.session=new $f(this.core,this.logger),this.proposal=new fD(this.core,this.logger),this.pendingRequest=new pD(this.core,this.logger),this.engine=new dD(this),this.auth=new vD(this.core,this.logger)}static async init(e){const r=new Fa(e);return await r.initialize(),r}get context(){return He(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"),setTimeout(()=>{this.engine.processRelayMessageCache()},L.toMiliseconds(L.ONE_SECOND))}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const SD=$f,xD=Fa;class ID extends Le.exports{constructor(){super()}}class Af{constructor(e){this.opts=e}}class Pf{constructor(e){this.client=e}}var DD=Object.defineProperty,OD=Object.defineProperties,$D=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,AD=Object.prototype.hasOwnProperty,PD=Object.prototype.propertyIsEnumerable,Rf=(t,e,r)=>e in t?DD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,TD=(t,e)=>{for(var r in e||(e={}))AD.call(e,r)&&Rf(t,r,e[r]);if(Tf)for(var r of Tf(e))PD.call(e,r)&&Rf(t,r,e[r]);return t},RD=(t,e)=>OD(t,$D(e));class CD extends Pf{constructor(e){super(e),this.init=async()=>{this.signClient=await xD.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(RD(TD({},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 ND={decryptMessage:async t=>{const e={core:new Pa({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 Pa({storageOptions:t.storageOptions,storage:t.storage}),sessionStore:null};e.sessionStore=new SD(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}},Cf=class extends Af{constructor(t){super(t),this.events=new Le.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||ls,this.signConfig=t.signConfig,this.core=t.core,this.logger=this.core.logger,this.engine=new CD(this)}static async init(t){const e=new Cf(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 La=Cf;La.notifications=ND;const BD=La;Fe.CLIENT_CONTEXT=ls,Fe.CLIENT_STORAGE_OPTIONS=Yf,Fe.CLIENT_STORAGE_PREFIX=Gf,Fe.IWalletKit=Af,Fe.IWalletKitEngine=Pf,Fe.IWalletKitEvents=ID,Fe.PROTOCOL=Za,Fe.PROTOCOL_VERSION=Wf,Fe.REQUEST_CONTEXT=Zf,Fe.WalletKit=BD,Fe.default=La,Object.defineProperty(Fe,"__esModule",{value:!0})});
40
40
  //# sourceMappingURL=index.umd.js.map