@walletconnect/pos-client 0.0.0-canary.1 → 0.0.0-canary.2

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(Ce,kt){typeof exports=="object"&&typeof module<"u"?kt(exports):typeof define=="function"&&define.amd?define(["exports"],kt):(Ce=typeof globalThis<"u"?globalThis:Ce||self,kt(Ce["@walletconnect/pos-client"]={}))})(this,function(Ce){"use strict";var kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function mu(t){var e=t.default;if(typeof e=="function"){var n=function(){return e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var He={exports:{}},wr=typeof Reflect=="object"?Reflect:null,vu=wr&&typeof wr.apply=="function"?wr.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},Qi;wr&&typeof wr.ownKeys=="function"?Qi=wr.ownKeys:Object.getOwnPropertySymbols?Qi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Qi=function(e){return Object.getOwnPropertyNames(e)};function R0(t){console&&console.warn&&console.warn(t)}var Eu=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}He.exports=oe,He.exports.once=F0,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var _u=10;function es(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return _u},set:function(t){if(typeof t!="number"||t<0||Eu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");_u=t}}),oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Eu(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 xu(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return xu(this)},oe.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")vu(c,this,n);else for(var u=c.length,l=Ou(c,u),r=0;r<u;++r)vu(l[r],this,n);return!0};function Iu(t,e,n,r){var i,s,o;if(es(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),o=s[e]),o===void 0)o=s[e]=n,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=xu(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,R0(a)}return t}oe.prototype.addListener=function(e,n){return Iu(this,e,n,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(e,n){return Iu(this,e,n,!0)};function C0(){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 Su(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=C0.bind(r);return i.listener=n,r.wrapFn=i,i}oe.prototype.once=function(e,n){return es(n),this.on(e,Su(this,e,n)),this},oe.prototype.prependOnceListener=function(e,n){return es(n),this.prependListener(e,Su(this,e,n)),this},oe.prototype.removeListener=function(e,n){var r,i,s,o,a;if(es(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(s=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,s=o;break}if(s<0)return this;s===0?r.shift():N0(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},oe.prototype.off=oe.prototype.removeListener,oe.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var s=Object.keys(r),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Du(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?U0(i):Ou(i,i.length)}oe.prototype.listeners=function(e){return Du(this,e,!0)},oe.prototype.rawListeners=function(e){return Du(this,e,!1)},oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Au.call(t,e)},oe.prototype.listenerCount=Au;function Au(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?Qi(this._events):[]};function Ou(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function N0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function U0(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function F0(t,e){return new Promise(function(n,r){function i(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}$u(t,e,s,{once:!0}),e!=="error"&&k0(t,i,{once:!0})})}function k0(t,e,n){typeof t.on=="function"&&$u(t,"error",e,n)}function $u(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const Bu="wc",L0=2,Io="POSClient",M0=`${Bu}@2:${Io}:`,Tu={database:":memory:"},Pu="1.0.0",Ru=10;var M={};/*! *****************************************************************************
1
+ (function(be,Ft){typeof exports=="object"&&typeof module<"u"?Ft(exports):typeof define=="function"&&define.amd?define(["exports"],Ft):(be=typeof globalThis<"u"?globalThis:be||self,Ft(be["@walletconnect/pos-client"]={}))})(this,function(be){"use strict";var Ft=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fu(t){var e=t.default;if(typeof e=="function"){var n=function(){return e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var Ve={exports:{}},dr=typeof Reflect=="object"?Reflect:null,du=dr&&typeof dr.apply=="function"?dr.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},Zi;dr&&typeof dr.ownKeys=="function"?Zi=dr.ownKeys:Object.getOwnPropertySymbols?Zi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Zi=function(e){return Object.getOwnPropertyNames(e)};function c0(t){console&&console.warn&&console.warn(t)}var pu=Number.isNaN||function(e){return e!==e};function se(){se.init.call(this)}Ve.exports=se,Ve.exports.once=f0,se.EventEmitter=se,se.prototype._events=void 0,se.prototype._eventsCount=0,se.prototype._maxListeners=void 0;var gu=10;function Ji(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return gu},set:function(t){if(typeof t!="number"||t<0||pu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");gu=t}}),se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},se.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||pu(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 yu(t){return t._maxListeners===void 0?se.defaultMaxListeners:t._maxListeners}se.prototype.getMaxListeners=function(){return yu(this)},se.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")du(c,this,n);else for(var u=c.length,l=Eu(c,u),r=0;r<u;++r)du(l[r],this,n);return!0};function wu(t,e,n,r){var i,s,o;if(Ji(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),o=s[e]),o===void 0)o=s[e]=n,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=yu(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,c0(a)}return t}se.prototype.addListener=function(e,n){return wu(this,e,n,!1)},se.prototype.on=se.prototype.addListener,se.prototype.prependListener=function(e,n){return wu(this,e,n,!0)};function u0(){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 mu(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=u0.bind(r);return i.listener=n,r.wrapFn=i,i}se.prototype.once=function(e,n){return Ji(n),this.on(e,mu(this,e,n)),this},se.prototype.prependOnceListener=function(e,n){return Ji(n),this.prependListener(e,mu(this,e,n)),this},se.prototype.removeListener=function(e,n){var r,i,s,o,a;if(Ji(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(s=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,s=o;break}if(s<0)return this;s===0?r.shift():l0(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var s=Object.keys(r),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function bu(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?h0(i):Eu(i,i.length)}se.prototype.listeners=function(e){return bu(this,e,!0)},se.prototype.rawListeners=function(e){return bu(this,e,!1)},se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):vu.call(t,e)},se.prototype.listenerCount=vu;function vu(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Zi(this._events):[]};function Eu(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function l0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function h0(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function f0(t,e){return new Promise(function(n,r){function i(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}xu(t,e,s,{once:!0}),e!=="error"&&d0(t,i,{once:!0})})}function d0(t,e,n){typeof t.on=="function"&&xu(t,"error",e,n)}function xu(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const _u="wc",p0=2,yo="POSClient",g0=`${_u}@2:${yo}:`,Iu={database:":memory:"},Su="1.0.0",Au=10,Du=[{assetNamespaces:["erc20","slip44"],capabilities:null,events:[],methods:["eth_sendTransaction"],name:"eip155"},{assetNamespaces:["token","slip44"],capabilities:null,events:[],methods:["solana_signAndSendTransaction"],name:"solana"},{assetNamespaces:["trc20","slip44"],capabilities:null,events:[],methods:["tron_signTransaction"],name:"tron"}],Ou=({projectId:t})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${t}&st=node&sv=js-pos-${Su}`,wo={"-18901":"ValidationError.InvalidAsset","-18902":"ValidationError.InvalidRecipient","-18903":"ValidationError.InvalidSender","-18904":"ValidationError.InvalidAmount","-18905":"ValidationError.InvalidAddress","-18906":"ValidationError.InvalidWalletResponse","-18907":"ValidationError.InvalidTransactionId","-18920":"ExecutionError.GasEstimation","-18940":"InternalError.InvalidProviderUrl","-18941":"InternalError.RpcError","-18942":"InternalError.Internal","-18970":"TransactionIdError.InvalidFormat","-18971":"TransactionIdError.InvalidChainId"};var M={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -11,21 +11,21 @@
11
11
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */var So=function(t,e){return So=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},So(t,e)};function j0(t,e){So(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Do=function(){return Do=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Do.apply(this,arguments)};function q0(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function z0(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function K0(t,e){return function(n,r){e(n,r,t)}}function V0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function H0(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function W0(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function G0(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function Z0(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Ao(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Cu(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function Y0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Cu(arguments[e]));return t}function X0(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Xr(t){return this instanceof Xr?(this.v=t,this):new Xr(t)}function J0(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(r[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof Xr?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Q0(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Xr(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function ey(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Ao=="function"?Ao(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function ty(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ny(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function ry(t){return t&&t.__esModule?t:{default:t}}function iy(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function sy(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var oy=Object.freeze({__proto__:null,__extends:j0,get __assign(){return Do},__rest:q0,__decorate:z0,__param:K0,__metadata:V0,__awaiter:H0,__generator:W0,__createBinding:G0,__exportStar:Z0,__values:Ao,__read:Cu,__spread:Y0,__spreadArrays:X0,__await:Xr,__asyncGenerator:J0,__asyncDelegator:Q0,__asyncValues:ey,__makeTemplateObject:ty,__importStar:ny,__importDefault:ry,__classPrivateFieldGet:iy,__classPrivateFieldSet:sy}),ts=mu(oy),Oo={},Jr={},Nu;function ay(){if(Nu)return Jr;Nu=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return Jr.delay=t,Jr}var zn={},$o={},Kn={},Uu;function cy(){return Uu||(Uu=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.ONE_THOUSAND=Kn.ONE_HUNDRED=void 0,Kn.ONE_HUNDRED=100,Kn.ONE_THOUSAND=1e3),Kn}var Bo={},Fu;function uy(){return Fu||(Fu=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}(Bo)),Bo}var ku;function Lu(){return ku||(ku=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(cy(),t),e.__exportStar(uy(),t)}($o)),$o}var Mu;function ly(){if(Mu)return zn;Mu=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.fromMiliseconds=zn.toMiliseconds=void 0;const t=Lu();function e(r){return r*t.ONE_THOUSAND}zn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return zn.fromMiliseconds=n,zn}var ju;function hy(){return ju||(ju=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(ay(),t),e.__exportStar(ly(),t)}(Oo)),Oo}var br={},qu;function fy(){if(qu)return br;qu=1,Object.defineProperty(br,"__esModule",{value:!0}),br.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const i=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:i})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return br.Watch=t,br.default=t,br}var To={},Qr={},zu;function dy(){if(zu)return Qr;zu=1,Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.IWatch=void 0;class t{}return Qr.IWatch=t,Qr}var Ku;function py(){return Ku||(Ku=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ts.__exportStar(dy(),t)}(To)),To}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(hy(),t),e.__exportStar(fy(),t),e.__exportStar(py(),t),e.__exportStar(Lu(),t)})(M);class Vn{}class gy extends Vn{constructor(e){super()}}const Vu=M.FIVE_SECONDS,Hn={pulse:"heartbeat_pulse"};class Po extends gy{constructor(e){super(e),this.events=new He.exports.EventEmitter,this.interval=Vu,this.interval=e?.interval||Vu}static async init(e){const n=new Po(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(Hn.pulse)}}const yy=/"(?:_|\\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*:/,wy=/"(?: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*:/,by=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function my(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){vy(t);return}return e}function vy(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function ns(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const n=t.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!by.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(yy.test(t)||wy.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,my)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Ey(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return Ey(t(...e))}catch(n){return Promise.reject(n)}}function _y(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function xy(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function rs(t){if(_y(t))return String(t);if(xy(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return rs(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ro="base64:";function Iy(t){return typeof t=="string"?t:Ro+Ay(t)}function Sy(t){return typeof t!="string"||!t.startsWith(Ro)?t:Dy(t.slice(Ro.length))}function Dy(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Ay(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Qe(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Oy(...t){return Qe(t.join(":"))}function is(t){return t=Qe(t),t?t+":":""}function $y(t,e){if(e===void 0)return!0;let n=0,r=t.indexOf(":");for(;r>-1;)n++,r=t.indexOf(":",r+1);return n<=e}function By(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function x$(t){return t}const Ty="memory",Py=()=>{const t=new Map;return{name:Ty,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,n){t.set(e,n)},setItemRaw(e,n){t.set(e,n)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Ry(t={}){const e={mounts:{"":t.driver||Py()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},r=(u,l)=>e.mountpoints.filter(f=>f.startsWith(u)||l&&u.startsWith(f)).map(f=>({relativeBase:u.length>f.length?u.slice(f.length):void 0,mountpoint:f,driver:e.mounts[f]})),i=(u,l)=>{if(e.watching){l=Qe(l);for(const f of e.watchListeners)f(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Hu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,f)=>{const h=new Map,d=p=>{let g=h.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},h.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",y=Qe(g?p:p.key),I=g?void 0:p.value,D=g||!p.options?l:{...l,...p.options},E=n(y);d(E).items.push({key:y,value:I,relativeKey:E.relativeKey,options:D})}return Promise.all([...h.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return xe(h.hasItem,f,l)},getItem(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return xe(h.getItem,f,l).then(d=>ns(d))},getItems(u,l={}){return a(u,l,f=>f.driver.getItems?xe(f.driver.getItems,f.items.map(h=>({key:h.relativeKey,options:h.options})),l).then(h=>h.map(d=>({key:Oy(f.base,d.key),value:ns(d.value)}))):Promise.all(f.items.map(h=>xe(f.driver.getItem,h.relativeKey,h.options).then(d=>({key:h.key,value:ns(d)})))))},getItemRaw(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return h.getItemRaw?xe(h.getItemRaw,f,l):xe(h.getItem,f,l).then(d=>Sy(d))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=Qe(u);const{relativeKey:h,driver:d}=n(u);d.setItem&&(await xe(d.setItem,h,rs(l),f),d.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return xe(f.driver.setItems,f.items.map(h=>({key:h.relativeKey,value:rs(h.value),options:h.options})),l);f.driver.setItem&&await Promise.all(f.items.map(h=>xe(f.driver.setItem,h.relativeKey,rs(h.value),h.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=Qe(u);const{relativeKey:h,driver:d}=n(u);if(d.setItemRaw)await xe(d.setItemRaw,h,l,f);else if(d.setItem)await xe(d.setItem,h,Iy(l),f);else return;d.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Qe(u);const{relativeKey:f,driver:h}=n(u);h.removeItem&&(await xe(h.removeItem,f,l),(l.removeMeta||l.removeMata)&&await xe(h.removeItem,f+"$",l),h.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Qe(u);const{relativeKey:f,driver:h}=n(u),d=Object.create(null);if(h.getMeta&&Object.assign(d,await xe(h.getMeta,f,l)),!l.nativeOnly){const p=await xe(h.getItem,f+"$",l).then(g=>ns(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=is(u);const f=r(u,!0);let h=[];const d=[];let p=!0;for(const y of f){y.driver.flags?.maxDepth||(p=!1);const I=await xe(y.driver.getKeys,y.relativeBase,l);for(const D of I){const E=y.mountpoint+Qe(D);h.some($=>E.startsWith($))||d.push(E)}h=[y.mountpoint,...h.filter(D=>!D.startsWith(y.mountpoint))]}const g=l.maxDepth!==void 0&&!p;return d.filter(y=>(!g||$y(y,l.maxDepth))&&By(y,u))},async clear(u,l={}){u=is(u),await Promise.all(r(u,!1).map(async f=>{if(f.driver.clear)return xe(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const h=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(h.map(d=>f.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Wu(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=is(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,h)=>h.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(Hu(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=is(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await Wu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=Qe(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Qe(u),r(u,l.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,f={})=>c.setItem(u,l,f),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function Hu(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function Wu(t){typeof t.dispose=="function"&&await xe(t.dispose)}function Wn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function Gu(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Wn(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let Co;function ei(){return Co||(Co=Gu("keyval-store","keyval")),Co}function Zu(t,e=ei()){return e("readonly",n=>Wn(n.get(t)))}function Cy(t,e,n=ei()){return n("readwrite",r=>(r.put(e,t),Wn(r.transaction)))}function Ny(t,e=ei()){return e("readwrite",n=>(n.delete(t),Wn(n.transaction)))}function Uy(t=ei()){return t("readwrite",e=>(e.clear(),Wn(e.transaction)))}function Fy(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Wn(t.transaction)}function ky(t=ei()){return t("readonly",e=>{if(e.getAllKeys)return Wn(e.getAllKeys());const n=[];return Fy(e,r=>n.push(r.key)).then(()=>n)})}const Ly=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),My=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function mr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return My(t)}catch{return t}}function Gn(t){return typeof t=="string"?t:Ly(t)||""}const jy="idb-keyval";var qy=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=Gu(t.dbName,t.storeName)),{name:jy,options:t,async hasItem(i){return!(typeof await Zu(n(i),r)>"u")},async getItem(i){return await Zu(n(i),r)??null},setItem(i,s){return Cy(n(i),s,r)},removeItem(i){return Ny(n(i),r)},getKeys(){return ky(r)},clear(){return Uy(r)}}};const zy="WALLET_CONNECT_V2_INDEXED_DB",Ky="keyvaluestorage";class Vy{constructor(){this.indexedDb=Ry({driver:qy({dbName:zy,storeName:Ky})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Gn(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var No=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ss={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof No<"u"&&No.localStorage?ss.exports=No.localStorage:typeof window<"u"&&window.localStorage?ss.exports=window.localStorage:ss.exports=new e})();function Hy(t){var e;return[t[0],mr((e=t[1])!=null?e:"")]}class Wy{constructor(){this.localStorage=ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Hy)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return mr(n)}async setItem(e,n){this.localStorage.setItem(e,Gn(n))}async removeItem(e){this.localStorage.removeItem(e)}}const Gy="wc_storage_version",Yu=1,Zy=async(t,e,n)=>{const r=Gy,i=await e.getItem(r);if(i&&i>=Yu){n(e);return}const s=await t.getKeys();if(!s.length){n(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(r,Yu),n(e),Yy(t,o)},Yy=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class Xy{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new Wy;this.storage=e;try{const n=new Vy;Zy(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}function Jy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Qy=ew;function ew(t,e,n){var r=n&&n.stringify||Jy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,f=-1,h=t&&t.length||0,d=0;d<h;){if(t.charCodeAt(d)===37&&d+1<h){switch(f=f>-1?f:0,t.charCodeAt(d+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Number(e[l]),f=d+2,d++;break;case 105:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Math.floor(Number(e[l])),f=d+2,d++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<d&&(u+=t.slice(f,d));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=d+2,d++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=d+2,d++;break}u+=r(e[l]),f=d+2,d++;break;case 115:if(l>=c)break;f<d&&(u+=t.slice(f,d)),u+=String(e[l]),f=d+2,d++;break;case 37:f<d&&(u+=t.slice(f,d)),u+="%",f=d+2,d++,l--;break}++l}++d}return f===-1?t:(f<h&&(u+=t.slice(f)),u)}const Xu=Qy;var Lt=Mt;const ti=lw().console||{},tw={mapHttpRequest:as,mapHttpResponse:as,wrapRequestSerializer:Fo,wrapResponseSerializer:Fo,wrapErrorSerializer:Fo,req:as,res:as,err:ow};function nw(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Mt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const n=t.browser.write||ti;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=nw(t.browser.serialize,r);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=ni),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:f,set:h});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:aw(t)};c.levels=Mt.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=ni,c.serializers=r,c._serialize=i,c._stdErrSerialize=s,c.child=d,e&&(c._logEvent=Uo());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function f(){return this._level}function h(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,vr(u,c,"error","log"),vr(u,c,"fatal","error"),vr(u,c,"warn","error"),vr(u,c,"info","log"),vr(u,c,"debug","log"),vr(u,c,"trace","log")}function d(p,g){if(!p)throw new Error("missing bindings for child Pino");g=g||{},i&&p.serializers&&(g.serializers=p.serializers);const y=g.serializers;if(i&&y){var I=Object.assign({},r,y),D=t.browser.serialize===!0?Object.keys(I):i;delete p.serializers,os([p],D,I,this._stdErrSerialize)}function E($){this._childLevel=($._childLevel|0)+1,this.error=Er($,p,"error"),this.fatal=Er($,p,"fatal"),this.warn=Er($,p,"warn"),this.info=Er($,p,"info"),this.debug=Er($,p,"debug"),this.trace=Er($,p,"trace"),I&&(this.serializers=I,this._serialize=D),e&&(this._logEvent=Uo([].concat($._logEvent.bindings,p)))}return E.prototype=this,new E(this)}return c}Mt.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"}},Mt.stdSerializers=tw,Mt.stdTimeFunctions=Object.assign({},{nullTime:Ju,epochTime:Qu,unixTime:cw,isoTime:uw});function vr(t,e,n,r){const i=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?ni:i[n]?i[n]:ti[n]||ti[r]||ni,rw(t,e,n)}function rw(t,e,n){!t.transmit&&e[n]===ni||(e[n]=function(r){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ti?ti:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&os(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,iw(this,n,o,s)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Mt.levels.values[u],f=Mt.levels.values[n];if(f<l)return;sw(this,{ts:s,methodLevel:n,methodValue:f,transmitLevel:u,transmitValue:Mt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[n]))}function iw(t,e,n,r){t._serialize&&os(n,t._serialize,t.serializers,t._stdErrSerialize);const i=n.slice();let s=i[0];const o={};r&&(o.time=r),o.level=Mt.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?Xu(i.shift(),i):void 0}else typeof s=="string"&&(s=Xu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function os(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=Mt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function Er(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var i=1;i<r.length;i++)r[i]=arguments[i-1];return t[n].apply(this,r)}}function sw(t,e,n){const r=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;os(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=n.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,r(s,t._logEvent,a),t._logEvent=Uo(c)}function Uo(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function ow(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function aw(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ju:Qu}function as(){return{}}function Fo(t){return t}function ni(){}function Ju(){return!1}function Qu(){return Date.now()}function cw(){return Math.round(Date.now()/1e3)}function uw(){return new Date(Date.now()).toISOString()}function lw(){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 hw={level:"info"},ri="custom_context",ko=1e3*1024;class fw{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 el{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new fw(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}class tl{constructor(e,n=ko){this.level=e??"error",this.levelValue=Lt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new el(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===Lt.levels.values.error?console.error(e):n===Lt.levels.values.warn?console.warn(e):n===Lt.levels.values.debug?console.debug(e):n===Lt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Gn({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new el(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Gn({extraMetadata:e})),new Blob(n,{type:"application/json"})}}class dw{constructor(e,n=ko){this.baseChunkLogger=new tl(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}class pw{constructor(e,n=ko){this.baseChunkLogger=new tl(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var gw=Object.defineProperty,yw=Object.defineProperties,ww=Object.getOwnPropertyDescriptors,nl=Object.getOwnPropertySymbols,bw=Object.prototype.hasOwnProperty,mw=Object.prototype.propertyIsEnumerable,rl=(t,e,n)=>e in t?gw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cs=(t,e)=>{for(var n in e||(e={}))bw.call(e,n)&&rl(t,n,e[n]);if(nl)for(var n of nl(e))mw.call(e,n)&&rl(t,n,e[n]);return t},us=(t,e)=>yw(t,ww(e));function Lo(t){return us(cs({},t),{level:t?.level||hw.level})}function vw(t,e=ri){return t[e]||""}function Ew(t,e,n=ri){return t[n]=e,t}function et(t,e=ri){let n="";return typeof t.bindings>"u"?n=vw(t,e):n=t.bindings().context||"",n}function _w(t,e,n=ri){const r=et(t,n);return r.trim()?`${r}/${e}`:e}function We(t,e,n=ri){const r=_w(t,e,n),i=t.child({context:r});return Ew(i,r,n)}function xw(t){var e,n;const r=new dw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Lt(us(cs({},t.opts),{level:"trace",browser:us(cs({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Iw(t){var e;const n=new pw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Lt(us(cs({},t.opts),{level:"trace"})),chunkLoggerController:n}}function Sw(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?xw(t):Iw(t)}var Dw=Object.defineProperty,Aw=(t,e,n)=>e in t?Dw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,il=(t,e,n)=>Aw(t,typeof e!="symbol"?e+"":e,n);class Ow extends Vn{constructor(e){super(),this.opts=e,il(this,"protocol","wc"),il(this,"version",2)}}var $w=Object.defineProperty,Bw=(t,e,n)=>e in t?$w(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Tw=(t,e,n)=>Bw(t,typeof e!="symbol"?e+"":e,n);class Pw extends Vn{constructor(e,n){super(),this.core=e,this.logger=n,Tw(this,"records",new Map)}}class Rw{constructor(e,n){this.logger=e,this.core=n}}class Cw extends Vn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class Nw extends Vn{constructor(e){super()}}class Uw{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class Fw extends Vn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class kw extends Vn{constructor(e,n){super(),this.core=e,this.logger=n}}class Lw{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class Mw{constructor(e,n){this.projectId=e,this.logger=n}}class jw{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var qw=Object.defineProperty,zw=(t,e,n)=>e in t?qw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,sl=(t,e,n)=>zw(t,typeof e!="symbol"?e+"":e,n);class Kw{constructor(e){this.opts=e,sl(this,"protocol","wc"),sl(this,"version",2)}}class Vw{constructor(e){this.client=e}}function Hw(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ol(t,...e){if(!Hw(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 al(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 Ww(t,e){ol(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mo=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Gw(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function cl(t){return typeof t=="string"&&(t=Gw(t)),ol(t),t}class Zw{clone(){return this._cloneInto()}}function Yw(t){const e=r=>t().update(cl(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ul(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Xw(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}class Jw extends Zw{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Mo(this.buffer)}update(e){al(this);const{view:n,buffer:r,blockLen:i}=this;e=cl(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=Mo(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){al(this),Ww(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;Xw(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Mo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const ls=BigInt(2**32-1),jo=BigInt(32);function ll(t,e=!1){return e?{h:Number(t&ls),l:Number(t>>jo&ls)}:{h:Number(t>>jo&ls)|0,l:Number(t&ls)|0}}function Qw(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=ll(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const e1=(t,e)=>BigInt(t>>>0)<<jo|BigInt(e>>>0),t1=(t,e,n)=>t>>>n,n1=(t,e,n)=>t<<32-n|e>>>n,r1=(t,e,n)=>t>>>n|e<<32-n,i1=(t,e,n)=>t<<32-n|e>>>n,s1=(t,e,n)=>t<<64-n|e>>>n-32,o1=(t,e,n)=>t>>>n-32|e<<64-n,a1=(t,e)=>e,c1=(t,e)=>t,u1=(t,e,n)=>t<<n|e>>>32-n,l1=(t,e,n)=>e<<n|t>>>32-n,h1=(t,e,n)=>e<<n-32|t>>>64-n,f1=(t,e,n)=>t<<n-32|e>>>64-n;function d1(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const p1=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),g1=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,y1=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),w1=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,b1=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),m1=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,J={fromBig:ll,split:Qw,toBig:e1,shrSH:t1,shrSL:n1,rotrSH:r1,rotrSL:i1,rotrBH:s1,rotrBL:o1,rotr32H:a1,rotr32L:c1,rotlSH:u1,rotlSL:l1,rotlBH:h1,rotlBL:f1,add:d1,add3L:p1,add3H:g1,add4L:y1,add4H:w1,add5H:m1,add5L:b1},[v1,E1]=J.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),yn=new Uint32Array(80),wn=new Uint32Array(80);class _1 extends Jw{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let E=0;E<16;E++,n+=4)yn[E]=e.getUint32(n),wn[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const $=yn[E-15]|0,R=wn[E-15]|0,C=J.rotrSH($,R,1)^J.rotrSH($,R,8)^J.shrSH($,R,7),U=J.rotrSL($,R,1)^J.rotrSL($,R,8)^J.shrSL($,R,7),N=yn[E-2]|0,O=wn[E-2]|0,G=J.rotrSH(N,O,19)^J.rotrBH(N,O,61)^J.shrSH(N,O,6),W=J.rotrSL(N,O,19)^J.rotrBL(N,O,61)^J.shrSL(N,O,6),P=J.add4L(U,W,wn[E-7],wn[E-16]),v=J.add4H(P,C,G,yn[E-7],yn[E-16]);yn[E]=v|0,wn[E]=P|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:y,Hh:I,Hl:D}=this;for(let E=0;E<80;E++){const $=J.rotrSH(f,h,14)^J.rotrSH(f,h,18)^J.rotrBH(f,h,41),R=J.rotrSL(f,h,14)^J.rotrSL(f,h,18)^J.rotrBL(f,h,41),C=f&d^~f&g,U=h&p^~h&y,N=J.add5L(D,R,U,E1[E],wn[E]),O=J.add5H(N,I,$,C,v1[E],yn[E]),G=N|0,W=J.rotrSH(r,i,28)^J.rotrBH(r,i,34)^J.rotrBH(r,i,39),P=J.rotrSL(r,i,28)^J.rotrBL(r,i,34)^J.rotrBL(r,i,39),v=r&s^r&a^s&a,m=i&o^i&c^o&c;I=g|0,D=y|0,g=d|0,y=p|0,d=f|0,p=h|0,{h:f,l:h}=J.add(u|0,l|0,O|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const w=J.add3L(G,P,m);r=J.add3H(w,O,W,v),i=w|0}({h:r,l:i}=J.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=J.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=J.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=J.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=J.add(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=J.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:y}=J.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:I,l:D}=J.add(this.Hh|0,this.Hl|0,I|0,D|0),this.set(r,i,s,o,a,c,u,l,f,h,d,p,g,y,I,D)}roundClean(){yn.fill(0),wn.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 x1=Yw(()=>new _1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qo=BigInt(0),hl=BigInt(1),I1=BigInt(2);function zo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ko(t){if(!zo(t))throw new Error("Uint8Array expected")}function Vo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const S1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ho(t){Ko(t);let e="";for(let n=0;n<t.length;n++)e+=S1[t[n]];return e}function fl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?qo:BigInt("0x"+t)}const Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function dl(t){if(t>=Xt._0&&t<=Xt._9)return t-Xt._0;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function pl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=dl(t.charCodeAt(s)),a=dl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function D1(t){return fl(Ho(t))}function hs(t){return Ko(t),fl(Ho(Uint8Array.from(t).reverse()))}function gl(t,e){return pl(t.toString(16).padStart(e*2,"0"))}function Wo(t,e){return gl(t,e).reverse()}function Jt(t,e,n){let r;if(typeof e=="string")try{r=pl(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(zo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function yl(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Ko(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const Go=t=>typeof t=="bigint"&&qo<=t;function A1(t,e,n){return Go(t)&&Go(e)&&Go(n)&&e<=t&&t<n}function ii(t,e,n,r){if(!A1(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function O1(t){let e;for(e=0;t>qo;t>>=hl,e+=1);return e}const $1=t=>(I1<<BigInt(t-1))-hl,B1={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"||zo(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Zo(t,e,n={}){const r=(i,s,o)=>{const a=B1[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function wl(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Ie=BigInt(0),pe=BigInt(1),Zn=BigInt(2),T1=BigInt(3),Yo=BigInt(4),bl=BigInt(5),ml=BigInt(8);function be(t,e){const n=t%e;return n>=Ie?n:e+n}function P1(t,e,n){if(e<Ie)throw new Error("invalid exponent, negatives unsupported");if(n<=Ie)throw new Error("invalid modulus");if(n===pe)return Ie;let r=pe;for(;e>Ie;)e&pe&&(r=r*t%n),t=t*t%n,e>>=pe;return r}function jt(t,e,n){let r=t;for(;e-- >Ie;)r*=r,r%=n;return r}function vl(t,e){if(t===Ie)throw new Error("invert: expected non-zero number");if(e<=Ie)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,i=Ie,s=pe;for(;n!==Ie;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==pe)throw new Error("invert: does not exist");return be(i,e)}function R1(t){const e=(t-pe)/Zn;let n,r,i;for(n=t-pe,r=0;n%Zn===Ie;n/=Zn,r++);for(i=Zn;i<t&&P1(i,e,t)!==t-pe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+pe)/Yo;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(n+pe)/Zn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,i),n),l=o.pow(a,s),f=o.pow(a,n);for(;!o.eql(f,o.ONE);){if(o.eql(f,o.ZERO))return o.ZERO;let h=1;for(let p=o.sqr(f);h<c&&!o.eql(p,o.ONE);h++)p=o.sqr(p);const d=o.pow(u,pe<<BigInt(c-h-1));u=o.sqr(d),l=o.mul(l,d),f=o.mul(f,u),c=h}return l}}function C1(t){if(t%Yo===T1){const e=(t+pe)/Yo;return function(n,r){const i=n.pow(r,e);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%ml===bl){const e=(t-bl)/ml;return function(n,r){const i=n.mul(r,Zn),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Zn),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return R1(t)}const N1=(t,e)=>(be(t,e)&pe)===pe,U1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function F1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=U1.reduce((r,i)=>(r[i]="function",r),e);return Zo(t,n)}function k1(t,e,n){if(n<Ie)throw new Error("invalid exponent, negatives unsupported");if(n===Ie)return t.ONE;if(n===pe)return e;let r=t.ONE,i=e;for(;n>Ie;)n&pe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=pe;return r}function L1(t,e){const n=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(n[a]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(n[a]=t.mul(s,n[a]),t.mul(s,o)),i),n}function El(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function _l(t,e,n=!1,r={}){if(t<=Ie)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=El(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:$1(i),ZERO:Ie,ONE:pe,create:c=>be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ie<=c&&c<t},is0:c=>c===Ie,isOdd:c=>(c&pe)===pe,neg:c=>be(-c,t),eql:(c,u)=>c===u,sqr:c=>be(c*c,t),add:(c,u)=>be(c+u,t),sub:(c,u)=>be(c-u,t),mul:(c,u)=>be(c*u,t),pow:(c,u)=>k1(a,c,u),div:(c,u)=>be(c*vl(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>vl(c,t),sqrt:r.sqrt||(c=>(o||(o=C1(t)),o(a,c))),invertBatch:c=>L1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?Wo(c,s):gl(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?hs(c):D1(c)}});return Object.freeze(a)}const xl=BigInt(0),fs=BigInt(1);function Xo(t,e){const n=e.negate();return t?n:e}function Il(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){Il(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function M1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function j1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Qo=new WeakMap,Sl=new WeakMap;function ea(t){return Sl.get(t)||1}function q1(t,e){return{constTimeNegate:Xo,hasPrecomputes(n){return ea(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>xl;)r&fs&&(i=i.add(s)),s=s.double(),r>>=fs;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Jo(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){const{windows:s,windowSize:o}=Jo(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<s;h++){const d=h*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=fs);const g=d,y=d+Math.abs(p)-1,I=h%2!==0,D=p<0;p===0?c=c.add(Xo(I,r[g])):a=a.add(Xo(D,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=Jo(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let f=0;f<o;f++){const h=f*a;if(i===xl)break;let d=Number(i&c);if(i>>=l,d>a&&(d-=u,i+=fs),d===0)continue;let p=r[h+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=Qo.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Qo.set(r,i(s))),s},wNAFCached(n,r,i){const s=ea(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=ea(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Il(r,e),Sl.set(n,r),Qo.delete(n)}}}function z1(t,e,n,r){if(M1(n,t),j1(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=O1(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let f=u;f>=0;f-=o){c.fill(i);for(let d=0;d<r.length;d++){const p=r[d],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(n[d])}let h=i;for(let d=c.length-1,p=i;d>0;d--)p=p.add(c[d]),h=h.add(p);if(l=l.add(h),f!==0)for(let d=0;d<o;d++)l=l.double()}return l}function K1(t){return F1(t.Fp),Zo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...El(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Bt=BigInt(0),tt=BigInt(1),ds=BigInt(2),V1=BigInt(8),H1={zip215:!0};function W1(t){const e=K1(t);return Zo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function G1(t){const e=W1(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=ds<<BigInt(a*8)-tt,l=n.create,f=_l(e.n,e.nBitLength),h=e.uvRatio||((w,b)=>{try{return{isValid:!0,value:n.sqrt(w*n.inv(b))}}catch{return{isValid:!1,value:Bt}}}),d=e.adjustScalarBytes||(w=>w),p=e.domain||((w,b,x)=>{if(Vo("phflag",x),b.length||x)throw new Error("Contexts/pre-hash are not supported");return w});function g(w,b){ii("coordinate "+w,b,Bt,u)}function y(w){if(!(w instanceof E))throw new Error("ExtendedPoint expected")}const I=wl((w,b)=>{const{ex:x,ey:A,ez:_}=w,S=w.is0();b==null&&(b=S?V1:n.inv(_));const B=l(x*b),T=l(A*b),q=l(_*b);if(S)return{x:Bt,y:tt};if(q!==tt)throw new Error("invZ was invalid");return{x:B,y:T}}),D=wl(w=>{const{a:b,d:x}=e;if(w.is0())throw new Error("bad point: ZERO");const{ex:A,ey:_,ez:S,et:B}=w,T=l(A*A),q=l(_*_),L=l(S*S),k=l(L*L),z=l(T*b),H=l(L*l(z+q)),Z=l(k+l(x*l(T*q)));if(H!==Z)throw new Error("bad point: equation left != right (1)");const V=l(A*_),Y=l(S*B);if(V!==Y)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(b,x,A,_){this.ex=b,this.ey=x,this.ez=A,this.et=_,g("x",b),g("y",x),g("z",A),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof E)throw new Error("extended point not allowed");const{x,y:A}=b||{};return g("x",x),g("y",A),new E(x,A,tt,l(x*A))}static normalizeZ(b){const x=n.invertBatch(b.map(A=>A.ez));return b.map((A,_)=>A.toAffine(x[_])).map(E.fromAffine)}static msm(b,x){return z1(E,f,b,x)}_setWindowSize(b){C.setWindowSize(this,b)}assertValidity(){D(this)}equals(b){y(b);const{ex:x,ey:A,ez:_}=this,{ex:S,ey:B,ez:T}=b,q=l(x*T),L=l(S*_),k=l(A*T),z=l(B*_);return q===L&&k===z}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:b}=e,{ex:x,ey:A,ez:_}=this,S=l(x*x),B=l(A*A),T=l(ds*l(_*_)),q=l(b*S),L=x+A,k=l(l(L*L)-S-B),z=q+B,H=z-T,Z=q-B,V=l(k*H),Y=l(z*Z),he=l(k*Z),Ve=l(H*z);return new E(V,Y,Ve,he)}add(b){y(b);const{a:x,d:A}=e,{ex:_,ey:S,ez:B,et:T}=this,{ex:q,ey:L,ez:k,et:z}=b;if(x===BigInt(-1)){const D0=l((S-_)*(L+q)),A0=l((S+_)*(L-q)),bu=l(A0-D0);if(bu===Bt)return this.double();const O0=l(B*ds*z),$0=l(T*ds*k),B0=$0+O0,T0=A0+D0,P0=$0-O0,m$=l(B0*bu),v$=l(T0*P0),E$=l(B0*P0),_$=l(bu*T0);return new E(m$,v$,_$,E$)}const H=l(_*q),Z=l(S*L),V=l(T*A*z),Y=l(B*k),he=l((_+S)*(q+L)-H-Z),Ve=Y-V,mt=Y+V,gn=l(Z-x*H),wu=l(he*Ve),y$=l(mt*gn),w$=l(he*gn),b$=l(Ve*mt);return new E(wu,y$,b$,w$)}subtract(b){return this.add(b.negate())}wNAF(b){return C.wNAFCached(this,b,E.normalizeZ)}multiply(b){const x=b;ii("scalar",x,tt,r);const{p:A,f:_}=this.wNAF(x);return E.normalizeZ([A,_])[0]}multiplyUnsafe(b,x=E.ZERO){const A=b;return ii("scalar",A,Bt,r),A===Bt?R:this.is0()||A===tt?this:C.wNAFCachedUnsafe(this,A,E.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,r).is0()}toAffine(b){return I(this,b)}clearCofactor(){const{h:b}=e;return b===tt?this:this.multiplyUnsafe(b)}static fromHex(b,x=!1){const{d:A,a:_}=e,S=n.BYTES;b=Jt("pointHex",b,S),Vo("zip215",x);const B=b.slice(),T=b[S-1];B[S-1]=T&-129;const q=hs(B),L=x?u:n.ORDER;ii("pointHex.y",q,Bt,L);const k=l(q*q),z=l(k-tt),H=l(A*k-_);let{isValid:Z,value:V}=h(z,H);if(!Z)throw new Error("Point.fromHex: invalid y coordinate");const Y=(V&tt)===tt,he=(T&128)!==0;if(!x&&V===Bt&&he)throw new Error("Point.fromHex: x=0 and x_0=1");return he!==Y&&(V=l(-V)),E.fromAffine({x:V,y:q})}static fromPrivateKey(b){return O(b).point}toRawBytes(){const{x:b,y:x}=this.toAffine(),A=Wo(x,n.BYTES);return A[A.length-1]|=b&tt?128:0,A}toHex(){return Ho(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,tt,l(e.Gx*e.Gy)),E.ZERO=new E(Bt,tt,tt,Bt);const{BASE:$,ZERO:R}=E,C=q1(E,a*8);function U(w){return be(w,r)}function N(w){return U(hs(w))}function O(w){const b=n.BYTES;w=Jt("private key",w,b);const x=Jt("hashed private key",s(w),2*b),A=d(x.slice(0,b)),_=x.slice(b,2*b),S=N(A),B=$.multiply(S),T=B.toRawBytes();return{head:A,prefix:_,scalar:S,point:B,pointBytes:T}}function G(w){return O(w).pointBytes}function W(w=new Uint8Array,...b){const x=yl(...b);return N(s(p(x,Jt("context",w),!!i)))}function P(w,b,x={}){w=Jt("message",w),i&&(w=i(w));const{prefix:A,scalar:_,pointBytes:S}=O(b),B=W(x.context,A,w),T=$.multiply(B).toRawBytes(),q=W(x.context,T,S,w),L=U(B+q*_);ii("signature.s",L,Bt,r);const k=yl(T,Wo(L,n.BYTES));return Jt("result",k,n.BYTES*2)}const v=H1;function m(w,b,x,A=v){const{context:_,zip215:S}=A,B=n.BYTES;w=Jt("signature",w,2*B),b=Jt("message",b),x=Jt("publicKey",x,B),S!==void 0&&Vo("zip215",S),i&&(b=i(b));const T=hs(w.slice(B,2*B));let q,L,k;try{q=E.fromHex(x,S),L=E.fromHex(w.slice(0,B),S),k=$.multiplyUnsafe(T)}catch{return!1}if(!S&&q.isSmallOrder())return!1;const z=W(_,L.toRawBytes(),q.toRawBytes(),b);return L.add(q.multiplyUnsafe(z)).subtract(k).clearCofactor().equals(E.ZERO)}return $._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:P,verify:m,ExtendedPoint:E,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>o(n.BYTES),precompute(w=8,b=E.BASE){return b._setWindowSize(w),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const ta=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Dl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Z1=BigInt(1),Al=BigInt(2);BigInt(3);const Y1=BigInt(5),X1=BigInt(8);function J1(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=ta,o=t*t%s*t%s,a=jt(o,Al,s)*o%s,c=jt(a,Z1,s)*t%s,u=jt(c,Y1,s)*c%s,l=jt(u,e,s)*u%s,f=jt(l,n,s)*l%s,h=jt(f,r,s)*f%s,d=jt(h,i,s)*h%s,p=jt(d,i,s)*h%s,g=jt(p,e,s)*u%s;return{pow_p_5_8:jt(g,Al,s)*t%s,b2:o}}function Q1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function eb(t,e){const n=ta,r=be(e*e*e,n),i=be(r*r*e,n),s=J1(t*i).pow_p_5_8;let o=be(t*r*s,n);const a=be(e*o*o,n),c=o,u=be(o*Dl,n),l=a===t,f=a===be(-t,n),h=a===be(-t*Dl,n);return l&&(o=c),(f||h)&&(o=u),N1(o,n)&&(o=be(-o,n)),{isValid:l||f,value:o}}const tb=_l(ta,void 0,!0),nb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:tb,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:X1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:x1,randomBytes:ul,adjustScalarBytes:Q1,uvRatio:eb},Ol=G1(nb),rb="EdDSA",ib="JWT",ps=".",gs="base64url",$l="utf8",Bl="utf8",sb=":",ob="did",ab="key",Tl="base58btc",cb="z",ub="K36",lb=32;function na(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Pl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?na(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Rl(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Pl(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return na(n)}function hb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var fb=hb,db=fb;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")},pb=t=>new TextEncoder().encode(t),gb=t=>new TextDecoder().decode(t);class yb{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class wb{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Nl(this,e)}}class bb{constructor(e){this.decoders=e}or(e){return Nl(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Nl=(t,e)=>new bb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class mb{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new yb(e,n,r),this.decoder=new wb(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ys=({name:t,prefix:e,encode:n,decode:r})=>new mb(t,e,n,r),si=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=db(n,e);return ys({prefix:t,name:e,encode:r,decode:s=>Cl(i(s))})},vb=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Eb=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},De=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ys({prefix:e,name:t,encode(i){return Eb(i,r,n)},decode(i){return vb(i,r,n,t)}}),_b=ys({prefix:"\0",name:"identity",encode:t=>gb(t),decode:t=>pb(t)});var xb=Object.freeze({__proto__:null,identity:_b});const Ib=De({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Sb=Object.freeze({__proto__:null,base2:Ib});const Db=De({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Ab=Object.freeze({__proto__:null,base8:Db});const Ob=si({prefix:"9",name:"base10",alphabet:"0123456789"});var $b=Object.freeze({__proto__:null,base10:Ob});const Bb=De({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Tb=De({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Pb=Object.freeze({__proto__:null,base16:Bb,base16upper:Tb});const Rb=De({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cb=De({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Nb=De({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Ub=De({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Fb=De({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),kb=De({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Lb=De({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Mb=De({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),jb=De({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var qb=Object.freeze({__proto__:null,base32:Rb,base32upper:Cb,base32pad:Nb,base32padupper:Ub,base32hex:Fb,base32hexupper:kb,base32hexpad:Lb,base32hexpadupper:Mb,base32z:jb});const zb=si({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Kb=si({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Vb=Object.freeze({__proto__:null,base36:zb,base36upper:Kb});const Hb=si({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Wb=si({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Gb=Object.freeze({__proto__:null,base58btc:Hb,base58flickr:Wb});const Zb=De({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Yb=De({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Xb=De({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Jb=De({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Qb=Object.freeze({__proto__:null,base64:Zb,base64pad:Yb,base64url:Xb,base64urlpad:Jb});const Ul=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}"),em=Ul.reduce((t,e,n)=>(t[n]=e,t),[]),tm=Ul.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function nm(t){return t.reduce((e,n)=>(e+=em[n],e),"")}function rm(t){const e=[];for(const n of t){const r=tm[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const im=ys({prefix:"\u{1F680}",name:"base256emoji",encode:nm,decode:rm});var sm=Object.freeze({__proto__:null,base256emoji:im}),om=kl,Fl=128,am=127,cm=~am,um=Math.pow(2,31);function kl(t,e,n){e=e||[],n=n||0;for(var r=n;t>=um;)e[n++]=t&255|Fl,t/=128;for(;t&cm;)e[n++]=t&255|Fl,t>>>=7;return e[n]=t|0,kl.bytes=n-r+1,e}var lm=ra,hm=128,Ll=127;function ra(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw ra.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Ll)<<i:(o&Ll)*Math.pow(2,i),i+=7}while(o>=hm);return ra.bytes=s-r,n}var fm=Math.pow(2,7),dm=Math.pow(2,14),pm=Math.pow(2,21),gm=Math.pow(2,28),ym=Math.pow(2,35),wm=Math.pow(2,42),bm=Math.pow(2,49),mm=Math.pow(2,56),vm=Math.pow(2,63),Em=function(t){return t<fm?1:t<dm?2:t<pm?3:t<gm?4:t<ym?5:t<wm?6:t<bm?7:t<mm?8:t<vm?9:10},_m={encode:om,decode:lm,encodingLength:Em},Ml=_m;const jl=(t,e,n=0)=>(Ml.encode(t,e,n),e),ql=t=>Ml.encodingLength(t),ia=(t,e)=>{const n=e.byteLength,r=ql(t),i=r+ql(n),s=new Uint8Array(i+n);return jl(t,s,0),jl(n,s,r),s.set(e,i),new xm(t,n,e,s)};class xm{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const zl=({name:t,code:e,encode:n})=>new Im(t,e,n);class Im{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ia(this.code,n):n.then(r=>ia(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Kl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Sm=zl({name:"sha2-256",code:18,encode:Kl("SHA-256")}),Dm=zl({name:"sha2-512",code:19,encode:Kl("SHA-512")});var Am=Object.freeze({__proto__:null,sha256:Sm,sha512:Dm});const Vl=0,Om="identity",Hl=Cl;var $m=Object.freeze({__proto__:null,identity:{code:Vl,name:Om,encode:Hl,digest:t=>ia(Vl,Hl(t))}});new TextEncoder,new TextDecoder;const Wl={...xb,...Sb,...Ab,...$b,...Pb,...qb,...Vb,...Gb,...Qb,...sm};({...Am,...$m});function Gl(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Zl=Gl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),sa=Gl("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Pl(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Yl={utf8:Zl,"utf-8":Zl,hex:Wl.base16,latin1:sa,ascii:sa,binary:sa,...Wl};function ws(t,e="utf8"){const n=Yl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}function xr(t,e="utf8"){const n=Yl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?na(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Xl(t){return mr(ws(xr(t,gs),$l))}function bs(t){return ws(xr(Gn(t),$l),gs)}function Jl(t){const e=xr(ub,Tl),n=cb+ws(Rl([e,t]),Tl);return[ob,ab,n].join(sb)}function Bm(t){return ws(t,gs)}function Tm(t){return xr(t,gs)}function Pm(t){return xr([bs(t.header),bs(t.payload)].join(ps),Bl)}function Rm(t){return[bs(t.header),bs(t.payload),Bm(t.signature)].join(ps)}function oa(t){const e=t.split(ps),n=Xl(e[0]),r=Xl(e[1]),i=Tm(e[2]),s=xr(e.slice(0,2).join(ps),Bl);return{header:n,payload:r,signature:i,data:s}}function Ql(t=ul(lb)){const e=Ol.getPublicKey(t);return{secretKey:Rl([t,e]),publicKey:e}}async function Cm(t,e,n,r,i=M.fromMiliseconds(Date.now())){const s={alg:rb,typ:ib},o=Jl(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Pm({header:s,payload:c}),l=Ol.sign(u,r.secretKey.slice(0,32));return Rm({header:s,payload:c,signature:l})}var eh=function(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},Nm=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),Um=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),Fm=function(){function t(e,n,r,i){this.name=e,this.version=n,this.os=r,this.bot=i,this.type="bot-device"}return t}(),km=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),Lm=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Mm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,jm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,th=3,qm=[["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",Mm]],nh=[["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 zm(t){return t?rh(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new Lm:typeof navigator<"u"?rh(navigator.userAgent):Hm()}function Km(t){return t!==""&&qm.reduce(function(e,n){var r=n[0],i=n[1];if(e)return e;var s=i.exec(t);return!!s&&[r,s]},!1)}function rh(t){var e=Km(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new km;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<th&&(i=eh(eh([],i,!0),Wm(th-i.length),!0)):i=[];var s=i.join("."),o=Vm(t),a=jm.exec(t);return a&&a[1]?new Fm(n,s,o,a[1]):new Nm(n,s,o)}function Vm(t){for(var e=0,n=nh.length;e<n;e++){var r=nh[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function Hm(){var t=typeof process<"u"&&process.version;return t?new Um(process.version.slice(1)):null}function Wm(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.getLocalStorage=ce.getLocalStorageOrThrow=ce.getCrypto=ce.getCryptoOrThrow=ih=ce.getLocation=ce.getLocationOrThrow=aa=ce.getNavigator=ce.getNavigatorOrThrow=Xn=ce.getDocument=ce.getDocumentOrThrow=ce.getFromWindowOrThrow=ce.getFromWindow=void 0;function Yn(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ce.getFromWindow=Yn;function Ir(t){const e=Yn(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ce.getFromWindowOrThrow=Ir;function Gm(){return Ir("document")}ce.getDocumentOrThrow=Gm;function Zm(){return Yn("document")}var Xn=ce.getDocument=Zm;function Ym(){return Ir("navigator")}ce.getNavigatorOrThrow=Ym;function Xm(){return Yn("navigator")}var aa=ce.getNavigator=Xm;function Jm(){return Ir("location")}ce.getLocationOrThrow=Jm;function Qm(){return Yn("location")}var ih=ce.getLocation=Qm;function ev(){return Ir("crypto")}ce.getCryptoOrThrow=ev;function tv(){return Yn("crypto")}ce.getCrypto=tv;function nv(){return Ir("localStorage")}ce.getLocalStorageOrThrow=nv;function rv(){return Yn("localStorage")}ce.getLocalStorage=rv;var ca={};Object.defineProperty(ca,"__esModule",{value:!0});var sh=ca.getWindowMetadata=void 0;const oh=ce;function iv(){let t,e;try{t=oh.getDocumentOrThrow(),e=oh.getLocationOrThrow()}catch{return null}function n(){const f=t.getElementsByTagName("link"),h=[];for(let d=0;d<f.length;d++){const p=f[d],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=p.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let I=e.protocol+"//"+e.host;if(y.indexOf("/")===0)I+=y;else{const D=e.pathname.split("/");D.pop();const E=D.join("/");I+=E+"/"+y}h.push(I)}else if(y.indexOf("//")===0){const I=e.protocol+y;h.push(I)}else h.push(y)}}return h}function r(...f){const h=t.getElementsByTagName("meta");for(let d=0;d<h.length;d++){const p=h[d],g=["itemprop","property","name"].map(y=>p.getAttribute(y)).filter(y=>y?f.includes(y):!1);if(g.length&&g){const y=p.getAttribute("content");if(y)return y}}return""}function i(){let f=r("name","og:site_name","og:title","twitter:title");return f||(f=t.title),f}function s(){return r("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=n();return{description:a,url:c,icons:u,name:o}}sh=ca.getWindowMetadata=iv;function oi(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function ua(t){return oi(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const ah="2.36.0";let la={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${ah}`};class Jn extends Error{constructor(e,n={}){const r=n.cause instanceof Jn?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof Jn&&n.cause.docsPath||n.docsPath,s=la.getDocsUrl?.({...n,docsPath:i}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...la.version?[`Version: ${la.version}`]:[]].join(`
15
- `);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=ah}walk(e){return ch(this,e)}}function ch(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?ch(t.cause,e):e?null:t}class uh extends Jn{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}}function Sr(t,{dir:e,size:n=32}={}){return typeof t=="string"?sv(t,{dir:e,size:n}):ov(t,{dir:e,size:n})}function sv(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new uh({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function ov(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new uh({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s=e==="right";r[s?i:n-i-1]=t[s?i:t.length-i-1]}return r}class av extends Jn{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${n} to ${e})`:`(above ${n})`}`,{name:"IntegerOutOfRangeError"})}}class cv extends Jn{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed ${n} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Dr(t,{size:e}){if(ua(t)>e)throw new cv({givenSize:ua(t),maxSize:e})}function ha(t,e={}){const{signed:n}=e;e.size&&Dr(t,{size:e.size});const r=BigInt(t);if(!n)return r;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return r<=s?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function uv(t,e={}){return Number(ha(t,e))}const lv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function fa(t,e={}){return typeof t=="number"||typeof t=="bigint"?da(t,e):typeof t=="string"?dv(t,e):typeof t=="boolean"?hv(t,e):lh(t,e)}function hv(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{size:e.size})):n}function lh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=lv[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(Dr(r,{size:e.size}),Sr(r,{dir:"right",size:e.size})):r}function da(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new av({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:n,size:r,value:`${t}${c}`})}const a=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Sr(a,{size:r}):a}const fv=new TextEncoder;function dv(t,e={}){const n=fv.encode(t);return lh(n,e)}const pv=new TextEncoder;function gv(t,e={}){return typeof t=="number"||typeof t=="bigint"?wv(t,e):typeof t=="boolean"?yv(t,e):oi(t)?fh(t,e):dh(t,e)}function yv(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{size:e.size})):n}const Qt={zero:48,nine:57,A:65,F:70,a:97,f:102};function hh(t){if(t>=Qt.zero&&t<=Qt.nine)return t-Qt.zero;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function fh(t,e={}){let n=t;e.size&&(Dr(n,{size:e.size}),n=Sr(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=hh(r.charCodeAt(a++)),u=hh(r.charCodeAt(a++));if(c===void 0||u===void 0)throw new Jn(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);s[o]=c*16+u}return s}function wv(t,e){const n=da(t,e);return fh(n)}function dh(t,e={}){const n=pv.encode(t);return typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{dir:"right",size:e.size})):n}const ms=BigInt(2**32-1),ph=BigInt(32);function bv(t,e=!1){return e?{h:Number(t&ms),l:Number(t>>ph&ms)}:{h:Number(t>>ph&ms)|0,l:Number(t&ms)|0}}function mv(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=bv(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const vv=(t,e,n)=>t<<n|e>>>32-n,Ev=(t,e,n)=>e<<n|t>>>32-n,_v=(t,e,n)=>e<<n-32|t>>>64-n,xv=(t,e,n)=>t<<n-32|e>>>64-n,Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ai(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ci(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!ai(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 gh(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ci(t.outputLen),ci(t.blockLen)}function Or(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function yh(t,e){vt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Iv(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $r(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function pa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function qt(t,e){return t<<32-e|t>>>e}const Sv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Dv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Av(t){for(let e=0;e<t.length;e++)t[e]=Dv(t[e]);return t}const wh=Sv?t=>t:Av,bh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ov=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Br(t){if(vt(t),bh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ov[t[n]];return e}const en={_0:48,_9:57,A:65,F:70,a:97,f:102};function mh(t){if(t>=en._0&&t<=en._9)return t-en._0;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function vs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(bh)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=mh(t.charCodeAt(s)),a=mh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Tr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Es(t){return typeof t=="string"&&(t=Tr(t)),vt(t),t}function Ne(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];vt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class ga{}function vh(t){const e=r=>t().update(Es(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function _s(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const $v=BigInt(0),ui=BigInt(1),Bv=BigInt(2),Tv=BigInt(7),Pv=BigInt(256),Rv=BigInt(113),Eh=[],_h=[],xh=[];for(let t=0,e=ui,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Eh.push(2*(5*r+n)),_h.push((t+1)*(t+2)/2%64);let i=$v;for(let s=0;s<7;s++)e=(e<<ui^(e>>Tv)*Rv)%Pv,e&Bv&&(i^=ui<<(ui<<BigInt(s))-ui);xh.push(i)}const Ih=mv(xh,!0),Cv=Ih[0],Nv=Ih[1],Sh=(t,e,n)=>n>32?_v(t,e,n):vv(t,e,n),Dh=(t,e,n)=>n>32?xv(t,e,n):Ev(t,e,n);function Uv(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],f=Sh(u,l,1)^n[a],h=Dh(u,l,1)^n[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=_h[o],c=Sh(i,s,a),u=Dh(i,s,a),l=Eh[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Cv[r],t[1]^=Nv[r]}$r(n)}class ya extends ga{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,ci(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Iv(this.state)}clone(){return this._cloneInto()}keccak(){wh(this.state32),Uv(this.state32,this.rounds),wh(this.state32),this.posOut=0,this.pos=0}update(e){Or(this),e=Es(e),vt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Or(this,!1),vt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ci(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(yh(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,$r(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ya(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Fv=(t,e,n)=>vh(()=>new ya(e,t,n)),Ah=Fv(1,136,256/8);function Oh(t,e){const n=e||"hex",r=Ah(oi(t,{strict:!1})?gv(t):t);return n==="bytes"?r:fa(r)}class $h extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const wa=new $h(8192);function kv(t,e){if(wa.has(`${t}.${e}`))return wa.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=Oh(dh(n),"bytes"),i=(e?n.substring(`${e}0x`.length):n).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return wa.set(`${t}.${e}`,s),s}function Lv(t){const e=Oh(`0x${t.substring(4)}`).substring(26);return kv(`0x${e}`)}async function Mv({hash:t,signature:e}){const n=oi(t)?t:fa(t),{secp256k1:r}=await Promise.resolve().then(function(){return pE});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:h}=e,d=Number(h??f),p=Bh(d);return new r.Signature(ha(u),ha(l)).addRecoveryBit(p)}const o=oi(e)?e:fa(e);if(ua(o)!==65)throw new Error("invalid signature length");const a=uv(`0x${o.slice(130)}`),c=Bh(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function Bh(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 jv({hash:t,signature:e}){return Lv(await Mv({hash:t,signature:e}))}function qv(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function zv(t,e,n){return t&e^~t&n}function Kv(t,e,n){return t&e^t&n^e&n}class Vv extends ga{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=pa(this.buffer)}update(e){Or(this),e=Es(e),vt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=pa(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Or(this),yh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,$r(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;qv(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=pa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const bn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),mn=new Uint32Array(64);class Wv extends Vv{constructor(e=32){super(64,e,8,!1),this.A=bn[0]|0,this.B=bn[1]|0,this.C=bn[2]|0,this.D=bn[3]|0,this.E=bn[4]|0,this.F=bn[5]|0,this.G=bn[6]|0,this.H=bn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)mn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const h=mn[f-15],d=mn[f-2],p=qt(h,7)^qt(h,18)^h>>>3,g=qt(d,17)^qt(d,19)^d>>>10;mn[f]=g+mn[f-7]+p+mn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=qt(a,6)^qt(a,11)^qt(a,25),d=l+h+zv(a,c,u)+Hv[f]+mn[f]|0,g=(qt(r,2)^qt(r,13)^qt(r,22))+Kv(r,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=r,r=d+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){$r(mn)}destroy(){this.set(0,0,0,0,0,0,0,0),$r(this.buffer)}}const xs=vh(()=>new Wv),ba=BigInt(0),ma=BigInt(1);function Is(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Qn(t,e,n=""){const r=ai(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Ss(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Th(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ba:BigInt("0x"+t)}function er(t){return Th(Br(t))}function Ph(t){return vt(t),Th(Br(Uint8Array.from(t).reverse()))}function Ds(t,e){return vs(t.toString(16).padStart(e*2,"0"))}function Rh(t,e){return Ds(t,e).reverse()}function me(t,e,n){let r;if(typeof e=="string")try{r=vs(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ai(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const va=t=>typeof t=="bigint"&&ba<=t;function Ea(t,e,n){return va(t)&&va(e)&&va(n)&&e<=t&&t<n}function Gv(t,e,n,r){if(!Ea(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Ch(t){let e;for(e=0;t>ba;t>>=ma,e+=1);return e}const li=t=>(ma<<BigInt(t))-ma;function Zv(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=d=>new Uint8Array(d),i=d=>Uint8Array.of(d);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...d)=>n(o,s,...d),l=(d=r(0))=>{o=u(i(0),d),s=u(),d.length!==0&&(o=u(i(1),d),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const p=[];for(;d<e;){s=u();const g=s.slice();p.push(g),d+=s.length}return Ne(...p)};return(d,p)=>{c(),l(d);let g;for(;!(g=p(f()));)l();return c(),g}}function Yv(t){return typeof t=="function"&&Number.isSafeInteger(t.outputLen)}function As(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function Nh(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Xv="0.1.1";function Jv(){return Xv}class Ge extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof Ge){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof Ge&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
- `);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Jv()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Uh(this,e)}}function Uh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Uh(t.cause,e):e?null:t}function Qv(t,e){if(Lh(t)>e)throw new a2({givenSize:Lh(t),maxSize:e})}const tn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Fh(t){if(t>=tn.zero&&t<=tn.nine)return t-tn.zero;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function e2(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new c2({size:t.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=t[o?s:t.length-s-1]}return i}function _a(t,e){if(Ia(t)>e)throw new g2({givenSize:Ia(t),maxSize:e})}function kh(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const i=t.replace("0x","");if(i.length>r*2)throw new y2({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const t2=new TextEncoder;function n2(t){return t instanceof Uint8Array?t:typeof t=="string"?i2(t):r2(t)}function r2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function i2(t,e={}){const{size:n}=e;let r=t;n&&(_a(t,n),r=xa(t,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Fh(i.charCodeAt(c++)),l=Fh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new Ge(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function s2(t,e={}){const{size:n}=e,r=t2.encode(t);return typeof n=="number"?(Qv(r,n),o2(r,n)):r}function o2(t,e){return e2(t,{dir:"right",size:e})}function Lh(t){return t.length}class a2 extends Ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class c2 extends Ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const u2=new TextEncoder,l2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Mh(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function h2(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(_a(n,e.size),Os(n,e.size)):n}function jh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=l2[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(_a(r,e.size),xa(r,e.size)):r}function f2(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new p2({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:n,size:r,value:`${t}${u}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Os(c,r):c}function d2(t,e={}){return jh(u2.encode(t),e)}function Os(t,e){return kh(t,{dir:"left",size:e})}function xa(t,e){return kh(t,{dir:"right",size:e})}function Ia(t){return Math.ceil((t.length-2)/2)}class p2 extends Ge{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class g2 extends Ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class y2 extends Ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new $h(128),da(0,{size:32});function w2(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=Ah(n2(t));return n==="Bytes"?r:jh(r)}class b2 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Sa={checksum:new b2(8192)}.checksum,m2=/^0x[a-fA-F0-9]{40}$/;function qh(t,e={}){const{strict:n=!0}=e;if(!m2.test(t))throw new zh({address:t,cause:new E2});if(n){if(t.toLowerCase()===t)return;if(v2(t)!==t)throw new zh({address:t,cause:new _2})}}function v2(t){if(Sa.has(t))return Sa.get(t);qh(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=w2(s2(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return Sa.set(t,i),i}class zh extends Ge{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class E2 extends Ge{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class _2 extends Ge{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const x2=/^(.*)\[([0-9]*)\]$/,I2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,S2=/^(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 Da(t,e){if(t.length!==e.length)throw new A2({expectedLength:t.length,givenLength:e.length});const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r];n.push(Da.encode(i,s))}return Mh(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return qh(c),Os(c.toLowerCase(),i?32:0)}if(n==="string")return d2(r);if(n==="bytes")return r;if(n==="bool")return Os(h2(r),i?32:1);const s=n.match(S2);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return f2(r,{size:i?32:f,signed:u==="int"})}const o=n.match(I2);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(r.length-2)/2)throw new D2({expectedSize:Number.parseInt(u,10),value:r});return xa(r,i?32:0)}const a=n.match(x2);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let f=0;f<r.length;f++)l.push(e(u,r[f],!0));return l.length===0?"0x":Mh(...l)}throw new O2(n)}t.encode=e})(Da||(Da={}));class D2 extends Ge{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${Ia(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class A2 extends Ge{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
17
- `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class O2 extends Ge{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Kh extends ga{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,gh(e);const r=Es(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),$r(s)}update(e){return Or(this),this.iHash.update(e),this}digestInto(e){Or(this),vt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Vh=(t,e,n)=>new Kh(t,e).update(n).digest();Vh.create=(t,e)=>new Kh(t,e);const nt=BigInt(0),Ze=BigInt(1),tr=BigInt(2),Hh=BigInt(3),Wh=BigInt(4),Gh=BigInt(5),$2=BigInt(7),Zh=BigInt(8),B2=BigInt(9),Yh=BigInt(16);function lt(t,e){const n=t%e;return n>=nt?n:e+n}function Et(t,e,n){let r=t;for(;e-- >nt;)r*=r,r%=n;return r}function Xh(t,e){if(t===nt)throw new Error("invert: expected non-zero number");if(e<=nt)throw new Error("invert: expected positive modulus, got "+e);let n=lt(t,e),r=e,i=nt,s=Ze;for(;n!==nt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==Ze)throw new Error("invert: does not exist");return lt(i,e)}function Aa(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Jh(t,e){const n=(t.ORDER+Ze)/Wh,r=t.pow(e,n);return Aa(t,r,e),r}function T2(t,e){const n=(t.ORDER-Gh)/Zh,r=t.mul(e,tr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,tr),i),a=t.mul(s,t.sub(o,t.ONE));return Aa(t,a,e),a}function P2(t){const e=hi(t),n=Qh(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+$2)/Yh;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),y=a.cmov(u,l,g);return Aa(a,y,c),y}}function Qh(t){if(t<Hh)throw new Error("sqrt is not defined for small field");let e=t-Ze,n=0;for(;e%tr===nt;)e/=tr,n++;let r=tr;const i=hi(t);for(;tf(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Jh;let s=i.pow(r,e);const o=(e+Ze)/tr;return function(c,u){if(c.is0(u))return u;if(tf(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),h=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const y=Ze<<BigInt(l-p-1),I=c.pow(f,y);l=p,f=c.sqr(I),h=c.mul(h,f),d=c.mul(d,I)}return d}}function R2(t){return t%Wh===Hh?Jh:t%Zh===Gh?T2:t%Yh===B2?P2(t):Qh(t)}const C2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ef(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=C2.reduce((r,i)=>(r[i]="function",r),e);return As(t,n),t}function N2(t,e,n){if(n<nt)throw new Error("invalid exponent, negatives unsupported");if(n===nt)return t.ONE;if(n===Ze)return e;let r=t.ONE,i=e;for(;n>nt;)n&Ze&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ze;return r}function $s(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function tf(t,e){const n=(t.ORDER-Ze)/tr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function nf(t,e){e!==void 0&&ci(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function hi(t,e,n=!1,r={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=nf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:li(c),ZERO:nt,ONE:Ze,allowedLengths:a,create:h=>lt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return nt<=h&&h<t},is0:h=>h===nt,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ze)===Ze,neg:h=>lt(-h,t),eql:(h,d)=>h===d,sqr:h=>lt(h*h,t),add:(h,d)=>lt(h+d,t),sub:(h,d)=>lt(h-d,t),mul:(h,d)=>lt(h*d,t),pow:(h,d)=>N2(f,h,d),div:(h,d)=>lt(h*Xh(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>Xh(h,t),sqrt:s||(h=>(l||(l=R2(t)),l(f,h))),toBytes:h=>n?Rh(h,u):Ds(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=n?Ph(h):er(h);if(o&&(p=lt(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>$s(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function rf(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 sf(t){const e=rf(t);return e+Math.ceil(e/2)}function of(t,e,n=!1){const r=t.length,i=rf(e),s=sf(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Ph(t):er(t),a=lt(o,e-Ze)+Ze;return n?Rh(a,i):Ds(a,i)}const Pr=BigInt(0),nr=BigInt(1);function Bs(t,e){const n=e.negate();return t?n:e}function Oa(t,e){const n=$s(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function af(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $a(t,e){af(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=li(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function cf(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=nr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function U2(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function F2(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ba=new WeakMap,uf=new WeakMap;function Ta(t){return uf.get(t)||1}function lf(t){if(t!==Pr)throw new Error("invalid wNAF")}class k2{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>Pr;)n&nr&&(r=r.add(i)),i=i.double(),n>>=nr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=$a(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=$a(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=cf(r,a,o);r=c,l?s=s.add(Bs(h,n[d])):i=i.add(Bs(f,n[u]))}return lf(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=$a(e,this.bits);for(let o=0;o<s.windows&&r!==Pr;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=cf(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return lf(r),i}getPrecomputes(e,n,r){let i=Ba.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Ba.set(n,i))),i}cached(e,n,r){const i=Ta(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Ta(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){af(n,this.bits),uf.set(e,n),Ba.delete(e)}hasCache(e){return Ta(e)!==1}}function L2(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Pr||r>Pr;)n&nr&&(s=s.add(i)),r&nr&&(o=o.add(i)),i=i.double(),n>>=nr,r>>=nr;return{p1:s,p2:o}}function M2(t,e,n,r){U2(n,t),F2(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Ch(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=li(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],I=Number(y>>BigInt(d)&u);l[I]=l[I].add(n[g])}let p=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),p=p.add(y);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function hf(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ef(e),e}else return hi(t,{isLE:n})}function j2(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>Pr))throw new Error(`CURVE.${c} must be positive bigint`)}const i=hf(e.p,n.Fp,r),s=hf(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}const ff=(t,e)=>(t+(t>=0?e:-e)/zt)/e;function q2(t,e,n){const[[r,i],[s,o]]=e,a=ff(o*t,n),c=ff(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<Tt,h=l<Tt;f&&(u=-u),h&&(l=-l);const d=li(Math.ceil(Ch(n)/2))+Ue;if(u<Tt||u>=d||l<Tt||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Pa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ra(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Is(n.lowS,"lowS"),Is(n.prehash,"prehash"),n.format!==void 0&&Pa(n.format),n}class z2 extends Error{constructor(e=""){super(e)}}const nn={Err:z2,_tlv:{encode:(t,e)=>{const{Err:n}=nn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Ss(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Ss(i.length/2|128):"";return Ss(t)+s+i+e},decode(t,e){const{Err:n}=nn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=nn;if(t<Tt)throw new e("integer: negative integers are not allowed");let n=Ss(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=nn;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 er(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=nn,i=me("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=nn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Tt=BigInt(0),Ue=BigInt(1),zt=BigInt(2),Rr=BigInt(3),Ca=BigInt(4);function rr(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=me("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function K2(t,e={}){const n=j2("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;As(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=pf(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:w,y:b}=v.toAffine(),x=r.toBytes(w);if(Is(m,"isCompressed"),m){l();const A=!r.isOdd(b);return Ne(df(A),x)}else return Ne(Uint8Array.of(4),x,r.toBytes(b))}function h(P){Qn(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,w=P.length,b=P[0],x=P.subarray(1);if(w===v&&(b===2||b===3)){const A=r.fromBytes(x);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const _=g(A);let S;try{S=r.sqrt(_)}catch(q){const L=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+L)}l();const B=r.isOdd(S);return(b&1)===1!==B&&(S=r.neg(S)),{x:A,y:S}}else if(w===m&&b===4){const A=r.BYTES,_=r.fromBytes(x.subarray(0,A)),S=r.fromBytes(x.subarray(A,A*2));if(!y(_,S))throw new Error("bad point: is not on curve");return{x:_,y:S}}else throw new Error(`bad point: got length ${w}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=r.sqr(P),m=r.mul(v,P);return r.add(r.add(m,r.mul(P,s.a)),s.b)}function y(P,v){const m=r.sqr(v),w=g(P);return r.eql(m,w)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=r.mul(r.pow(s.a,Rr),Ca),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(I,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!r.isValid(v)||m&&r.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function $(P){if(!(P instanceof O))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return q2(P,c.basises,i.ORDER)}const C=Nh((P,v)=>{const{X:m,Y:w,Z:b}=P;if(r.eql(b,r.ONE))return{x:m,y:w};const x=P.is0();v==null&&(v=x?r.ONE:r.inv(b));const A=r.mul(m,v),_=r.mul(w,v),S=r.mul(b,v);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),U=Nh(P=>{if(P.is0()){if(e.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!r.isValid(v)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,w,b){return m=new O(r.mul(m.X,P),m.Y,m.Z),v=Bs(w,v),m=Bs(b,m),v.add(m)}class O{constructor(v,m,w){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",w),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y:w}=v||{};if(!v||!r.isValid(m)||!r.isValid(w))throw new Error("invalid affine point");if(v instanceof O)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(w)?O.ZERO:new O(m,w,r.ONE)}static fromBytes(v){const m=O.fromAffine(p(Qn(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return O.fromBytes(me("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(Rr),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v,S=r.eql(r.mul(m,_),r.mul(x,b)),B=r.eql(r.mul(w,_),r.mul(A,b));return S&&B}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,w=r.mul(m,Rr),{X:b,Y:x,Z:A}=this;let _=r.ZERO,S=r.ZERO,B=r.ZERO,T=r.mul(b,b),q=r.mul(x,x),L=r.mul(A,A),k=r.mul(b,x);return k=r.add(k,k),B=r.mul(b,A),B=r.add(B,B),_=r.mul(v,B),S=r.mul(w,L),S=r.add(_,S),_=r.sub(q,S),S=r.add(q,S),S=r.mul(_,S),_=r.mul(k,_),B=r.mul(w,B),L=r.mul(v,L),k=r.sub(T,L),k=r.mul(v,k),k=r.add(k,B),B=r.add(T,T),T=r.add(B,T),T=r.add(T,L),T=r.mul(T,k),S=r.add(S,T),L=r.mul(x,A),L=r.add(L,L),T=r.mul(L,k),_=r.sub(_,T),B=r.mul(L,q),B=r.add(B,B),B=r.add(B,B),new O(_,S,B)}add(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v;let S=r.ZERO,B=r.ZERO,T=r.ZERO;const q=s.a,L=r.mul(s.b,Rr);let k=r.mul(m,x),z=r.mul(w,A),H=r.mul(b,_),Z=r.add(m,w),V=r.add(x,A);Z=r.mul(Z,V),V=r.add(k,z),Z=r.sub(Z,V),V=r.add(m,b);let Y=r.add(x,_);return V=r.mul(V,Y),Y=r.add(k,H),V=r.sub(V,Y),Y=r.add(w,b),S=r.add(A,_),Y=r.mul(Y,S),S=r.add(z,H),Y=r.sub(Y,S),T=r.mul(q,V),S=r.mul(L,H),T=r.add(S,T),S=r.sub(z,T),T=r.add(z,T),B=r.mul(S,T),z=r.add(k,k),z=r.add(z,k),H=r.mul(q,H),V=r.mul(L,V),z=r.add(z,H),H=r.sub(k,H),H=r.mul(q,H),V=r.add(V,H),k=r.mul(z,V),B=r.add(B,k),k=r.mul(Y,V),S=r.mul(Z,S),S=r.sub(S,k),k=r.mul(Z,z),T=r.mul(Y,T),T=r.add(T,k),new O(S,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals(O.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let w,b;const x=A=>W.cached(this,A,_=>Oa(O,_));if(m){const{k1neg:A,k1:_,k2neg:S,k2:B}=R(v),{p:T,f:q}=x(_),{p:L,f:k}=x(B);b=q.add(k),w=N(m.beta,T,L,A,S)}else{const{p:A,f:_}=x(v);w=A,b=_}return Oa(O,[w,b])[0]}multiplyUnsafe(v){const{endo:m}=e,w=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===Tt||w.is0())return O.ZERO;if(v===Ue)return w;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:x,k2neg:A,k2:_}=R(v),{p1:S,p2:B}=L2(O,w,x,_);return N(m.beta,S,B,b,A)}else return W.unsafe(w,v)}multiplyAndAddUnsafe(v,m,w){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(w));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===Ue?!0:v?v(O,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===Ue?this:v?v(O,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return Is(v,"isCompressed"),this.assertValidity(),d(O,this,v)}toHex(v=!0){return Br(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return Oa(O,v)}static msm(v,m){return M2(O,i,v,m)}static fromPrivateKey(v){return O.BASE.multiply(rr(i,v))}}O.BASE=new O(s.Gx,s.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=i;const G=i.BITS,W=new k2(O,e.endo?Math.ceil(G/2):G);return O.BASE.precompute(8),O}function df(t){return Uint8Array.of(t?2:3)}function V2(t,e){const n=t.ORDER;let r=Tt;for(let p=n-Ue;p%zt===Tt;p/=zt)r+=Ue;const i=r,s=zt<<i-Ue-Ue,o=s*zt,a=(n-Ue)/o,c=(a-Ue)/zt,u=o-Ue,l=s,f=t.pow(e,a),h=t.pow(e,(a+Ue)/zt);let d=(p,g)=>{let y=f,I=t.pow(g,u),D=t.sqr(I);D=t.mul(D,g);let E=t.mul(p,D);E=t.pow(E,c),E=t.mul(E,I),I=t.mul(E,g),D=t.mul(E,p);let $=t.mul(D,I);E=t.pow($,l);let R=t.eql(E,t.ONE);I=t.mul(D,h),E=t.mul($,y),D=t.cmov(I,D,R),$=t.cmov(E,$,R);for(let C=i;C>Ue;C--){let U=C-zt;U=zt<<U-Ue;let N=t.pow($,U);const O=t.eql(N,t.ONE);I=t.mul(D,y),y=t.mul(y,y),N=t.mul($,y),D=t.cmov(I,D,O),$=t.cmov(N,$,O)}return{isValid:R,value:D}};if(t.ORDER%Ca===Rr){const p=(t.ORDER-Rr)/Ca,g=t.sqrt(t.neg(e));d=(y,I)=>{let D=t.sqr(I);const E=t.mul(y,I);D=t.mul(D,E);let $=t.pow(D,p);$=t.mul($,E);const R=t.mul($,g),C=t.mul(t.sqr($),I),U=t.eql(C,y);let N=t.cmov(R,$,U);return{isValid:U,value:N}}}return d}function H2(t,e){ef(t);const{A:n,B:r,Z:i}=e;if(!t.isValid(n)||!t.isValid(r)||!t.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");const s=V2(t,i);if(!t.isOdd)throw new Error("Field does not have .isOdd()");return o=>{let a,c,u,l,f,h,d,p;a=t.sqr(o),a=t.mul(a,i),c=t.sqr(a),c=t.add(c,a),u=t.add(c,t.ONE),u=t.mul(u,r),l=t.cmov(i,t.neg(c),!t.eql(c,t.ZERO)),l=t.mul(l,n),c=t.sqr(u),h=t.sqr(l),f=t.mul(h,n),c=t.add(c,f),c=t.mul(c,u),h=t.mul(h,l),f=t.mul(h,r),c=t.add(c,f),d=t.mul(a,u);const{isValid:g,value:y}=s(c,h);p=t.mul(a,o),p=t.mul(p,y),d=t.cmov(d,u,g),p=t.cmov(p,y,g);const I=t.isOdd(o)===t.isOdd(p);p=t.cmov(t.neg(p),p,I);const D=$s(t,[l],!0)[0];return d=t.mul(d,D),{x:d,y:p}}}function pf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function W2(t,e={}){const{Fn:n}=t,r=e.randomBytes||_s,i=Object.assign(pf(t.Fp,n),{seed:sf(n.ORDER)});function s(d){try{return!!rr(n,d)}catch{return!1}}function o(d,p){const{publicKey:g,publicKeyUncompressed:y}=i;try{const I=d.length;return p===!0&&I!==g||p===!1&&I!==y?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=r(i.seed)){return of(Qn(d,i.seed,"seed"),n.ORDER)}function c(d,p=!0){return t.BASE.multiply(rr(n,d)).toBytes(p)}function u(d){const p=a(d);return{secretKey:p,publicKey:c(p)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:y}=i;if(n.allowedLengths||p===g)return;const I=me("key",d).length;return I===g||I===y}function f(d,p,g=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const y=rr(n,d);return t.fromHex(p).multiply(y).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:d=>rr(n,d),precompute(d=8,p=t.BASE){return p.precompute(d,!1)}},lengths:i})}function G2(t,e,n={}){gh(e),As(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||_s,i=n.hmac||((m,...w)=>Vh(e,m,Ne(...w))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=W2(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(m){const w=a>>Ue;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function D(m,w){Pa(w);const b=d.signature,x=w==="compact"?b:w==="recovered"?b+1:void 0;return Qn(m,x,`${w} signature`)}class E{constructor(w,b,x){this.r=I("r",w),this.s=I("s",b),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(w,b=g){D(w,b);let x;if(b==="der"){const{r:B,s:T}=nn.toSig(Qn(w));return new E(B,T)}b==="recovered"&&(x=w[0],b="compact",w=w.subarray(1));const A=o.BYTES,_=w.subarray(0,A),S=w.subarray(A,A*2);return new E(o.fromBytes(_),o.fromBytes(S),x)}static fromHex(w,b){return this.fromBytes(vs(w),b)}addRecoveryBit(w){return new E(this.r,this.s,w)}recoverPublicKey(w){const b=s.ORDER,{r:x,s:A,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*zt<b&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const B=_===2||_===3?x+a:x;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");const T=s.toBytes(B),q=t.fromBytes(Ne(df((_&1)===0),T)),L=o.inv(B),k=R(me("msgHash",w)),z=o.create(-k*L),H=o.create(A*L),Z=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return y(this.s)}toBytes(w=g){if(Pa(w),w==="der")return vs(nn.hexFromSig(this));const b=o.toBytes(this.r),x=o.toBytes(this.s);if(w==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ne(Uint8Array.of(this.recovery),b,x)}return Ne(b,x)}toHex(w){return Br(this.toBytes(w))}assertValidity(){}static fromCompact(w){return E.fromBytes(me("sig",w),"compact")}static fromDER(w){return E.fromBytes(me("sig",w),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Br(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Br(this.toBytes("compact"))}}const $=n.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const b=er(w),x=w.length*8-c;return x>0?b>>BigInt(x):b},R=n.bits2int_modN||function(w){return o.create($(w))},C=li(c);function U(m){return Gv("num < 2^"+c,m,Tt,C),o.toBytes(m)}function N(m,w){return Qn(m,void 0,"message"),w?Qn(e(m),void 0,"prehashed message"):m}function O(m,w,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:A,extraEntropy:_}=Ra(b,p);m=N(m,A);const S=R(m),B=rr(o,w),T=[U(B),U(S)];if(_!=null&&_!==!1){const z=_===!0?r(d.secretKey):_;T.push(me("extraEntropy",z))}const q=Ne(...T),L=S;function k(z){const H=$(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===Tt)return;const he=o.create(Z*o.create(L+Y*B));if(he===Tt)return;let Ve=(V.x===Y?0:2)|Number(V.y&Ue),mt=he;return x&&y(he)&&(mt=o.neg(he),Ve^=1),new E(Y,mt,Ve)}return{seed:q,k2sig:k}}function G(m,w,b={}){m=me("message",m);const{seed:x,k2sig:A}=O(m,w,b);return Zv(e.outputLen,o.BYTES,i)(x,A)}function W(m){let w;const b=typeof m=="string"||ai(m),x=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)w=new E(m.r,m.s);else if(b){try{w=E.fromBytes(me("sig",m),"der")}catch(A){if(!(A instanceof nn.Err))throw A}if(!w)try{w=E.fromBytes(me("sig",m),"compact")}catch{return!1}}return w||!1}function P(m,w,b,x={}){const{lowS:A,prehash:_,format:S}=Ra(x,p);if(b=me("publicKey",b),w=N(me("message",w),_),"strict"in x)throw new Error("options.strict was renamed to lowS");const B=S===void 0?W(m):E.fromBytes(me("sig",m),S);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:q,s:L}=B,k=R(w),z=o.inv(L),H=o.create(k*z),Z=o.create(q*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===q}catch{return!1}}function v(m,w,b={}){const{prehash:x}=Ra(b,p);return w=N(w,x),E.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function Z2(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=hi(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function Y2(t){const{CURVE:e,curveOpts:n}=Z2(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function X2(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,nf(n.Fn.ORDER,n.Fn.BITS))})}function J2(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Y2(t),s=K2(e,n),o=G2(s,r,i);return X2(t,o)}function Q2(t,e){const n=r=>J2({...t,hash:r});return{...n(e),create:n}}const eE=er;function vn(t,e){if(fi(t),fi(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function tE(t,e){const n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function fi(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function gf(t){if(!ai(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or string");return typeof t=="string"?Tr(t):t}function nE(t,e,n,r){vt(t),fi(n),e=gf(e),e.length>255&&(e=r(Ne(Tr("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=Ne(e,vn(e.length,1)),c=vn(0,s),u=vn(n,2),l=new Array(o),f=r(Ne(c,t,u,vn(0,1),a));l[0]=r(Ne(f,vn(1,1),a));for(let d=1;d<=o;d++){const p=[tE(f,l[d-1]),vn(d+1,1),a];l[d]=r(Ne(...p))}return Ne(...l).slice(0,n)}function rE(t,e,n,r,i){if(vt(t),fi(n),e=gf(e),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(Tr("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(t).update(vn(n,2)).update(e).update(vn(e.length,1)).digest()}function Na(t,e,n){As(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;if(!Yv(n.hash))throw new Error("expected valid hash");vt(t),fi(e);const u=r.toString(2).length,l=Math.ceil((u+i)/8),f=e*s*l;let h;if(a==="xmd")h=nE(t,c,f,o);else if(a==="xof")h=rE(t,c,f,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let p=0;p<e;p++){const g=new Array(s);for(let y=0;y<s;y++){const I=l*(y+p*s),D=h.subarray(I,I+l);g[y]=lt(eE(D),r)}d[p]=g}return d}function iE(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(f=>f.reduce((h,d)=>t.add(t.mul(h,r),d))),[u,l]=$s(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}const sE=Tr("HashToScalar-");function oE(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const a=Object.assign({},n,o),c=Na(s,2,a),u=r(c[0]),l=r(c[1]);return i(u.add(l))},encodeToCurve(s,o){const a=n.encodeDST?{DST:n.encodeDST}:{},c=Object.assign({},n,a,o),u=Na(s,1,c),l=r(u[0]);return i(l)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))},hashToScalar(s,o){const a=t.Fn.ORDER,c=Object.assign({},n,{p:a,m:1,DST:sE},o);return Na(s,1,c)[0][0]}}}const Cr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},aE={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},cE=BigInt(0),yf=BigInt(1),Ua=BigInt(2);function uE(t){const e=Cr.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Et(l,n,e)*l%e,h=Et(f,n,e)*l%e,d=Et(h,Ua,e)*u%e,p=Et(d,i,e)*d%e,g=Et(p,s,e)*p%e,y=Et(g,a,e)*g%e,I=Et(y,c,e)*y%e,D=Et(I,a,e)*g%e,E=Et(D,n,e)*l%e,$=Et(E,o,e)*p%e,R=Et($,r,e)*u%e,C=Et(R,Ua,e);if(!rn.eql(rn.sqr(C),t))throw new Error("Cannot find square root");return C}const rn=hi(Cr.p,{sqrt:uE}),Ts=Q2({...Cr,Fp:rn,lowS:!0,endo:aE},xs),wf={};function Ps(t,...e){let n=wf[t];if(n===void 0){const r=xs(Tr(t));n=Ne(r,r),wf[t]=n}return xs(Ne(n,...e))}const Fa=t=>t.toBytes(!0).slice(1),Nr=Ts.Point,ka=t=>t%Ua===cE;function La(t){const{Fn:e,BASE:n}=Nr,r=rr(e,t),i=n.multiply(r);return{scalar:ka(i.y)?r:e.neg(r),bytes:Fa(i)}}function bf(t){const e=rn;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");const n=e.create(t*t),r=e.create(n*t+BigInt(7));let i=e.sqrt(r);ka(i)||(i=e.neg(i));const s=Nr.fromAffine({x:t,y:i});return s.assertValidity(),s}const di=er;function mf(...t){return Nr.Fn.create(di(Ps("BIP0340/challenge",...t)))}function vf(t){return La(t).bytes}function lE(t,e,n=_s(32)){const{Fn:r}=Nr,i=me("message",t),{bytes:s,scalar:o}=La(e),a=me("auxRand",n,32),c=r.toBytes(o^di(Ps("BIP0340/aux",a))),u=Ps("BIP0340/nonce",c,s,i),{bytes:l,scalar:f}=La(u),h=mf(l,s,i),d=new Uint8Array(64);if(d.set(l,0),d.set(r.toBytes(r.create(f+h*o)),32),!Ef(d,i,s))throw new Error("sign: Invalid signature produced");return d}function Ef(t,e,n){const{Fn:r,BASE:i}=Nr,s=me("signature",t,64),o=me("message",e),a=me("publicKey",n,32);try{const c=bf(di(a)),u=di(s.subarray(0,32));if(!Ea(u,yf,Cr.p))return!1;const l=di(s.subarray(32,64));if(!Ea(l,yf,Cr.n))return!1;const f=mf(r.toBytes(u),Fa(c),o),h=i.multiplyUnsafe(l).add(c.multiplyUnsafe(r.neg(f))),{x:d,y:p}=h.toAffine();return!(h.is0()||!ka(p)||d!==u)}catch{return!1}}const hE=(()=>{const n=(i=_s(48))=>of(i,Cr.n);Ts.utils.randomSecretKey;function r(i){const s=n(i);return{secretKey:s,publicKey:vf(s)}}return{keygen:r,getPublicKey:vf,sign:lE,verify:Ef,Point:Nr,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Ps,lift_x:bf,pointToBytes:Fa,numberToBytesBE:Ds,bytesToNumberBE:er,mod:lt},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})(),fE=iE(rn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),dE=H2(rn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:rn.create(BigInt("-11"))}),Ma=oE(Ts.Point,t=>{const{x:e,y:n}=dE(rn.create(t[0]));return fE(e,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:rn.ORDER,m:1,k:128,expand:"xmd",hash:xs});var pE=Object.freeze({__proto__:null,secp256k1:Ts,schnorr:hE,secp256k1_hasher:Ma,hashToCurve:Ma.hashToCurve,encodeToCurve:Ma.encodeToCurve});function gE(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),f=l.charCodeAt(0);if(e[f]!==255)throw new TypeError(l+" is ambiguous");e[f]=u}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,f=0,h=0;const d=u.length;for(;h!==d&&u[h]===0;)h++,l++;const p=(d-h)*s+1>>>0,g=new Uint8Array(p);for(;h!==d;){let D=u[h],E=0;for(let $=p-1;(D!==0||E<f)&&$!==-1;$--,E++)D+=256*g[$]>>>0,g[$]=D%n>>>0,D=D/n>>>0;if(D!==0)throw new Error("Non-zero carry");f=E,h++}let y=p-f;for(;y!==p&&g[y]===0;)y++;let I=r.repeat(l);for(;y<p;++y)I+=t.charAt(g[y]);return I}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,h=0;for(;u[l]===r;)f++,l++;const d=(u.length-l)*i+1>>>0,p=new Uint8Array(d);for(;l<u.length;){const D=u.charCodeAt(l);if(D>255)return;let E=e[D];if(E===255)return;let $=0;for(let R=d-1;(E!==0||$<h)&&R!==-1;R--,$++)E+=n*p[R]>>>0,p[R]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");h=$,l++}let g=d-h;for(;g!==d&&p[g]===0;)g++;const y=new Uint8Array(f+(d-g));let I=f;for(;g!==d;)y[I++]=p[g++];return y}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var yE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pi=gE(yE);function wE(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function bE(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if((o&4294967168)===0){e[i++]=o;continue}else if((o&4294965248)===0)e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128):(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128)}e[i++]=o&63|128}}const mE=new TextEncoder,vE=50;function EE(t,e,n){mE.encodeInto(t,e.subarray(n))}function _E(t,e,n){t.length>vE?EE(t,e,n):bE(t,e,n)}const xE=4096;function _f(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const a=t[r++];if((a&128)===0)s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,l=t[r++]&63;let f=(a&7)<<18|c<<12|u<<6|l;f>65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=xE&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const IE=new TextDecoder,SE=200;function DE(t,e,n){const r=t.subarray(e,e+n);return IE.decode(r)}function AE(t,e,n){return n>SE?DE(t,e,n):_f(t,e,n)}class Rs{constructor(e,n){this.type=e,this.data=n}}class ht extends Error{constructor(e){super(e);const n=Object.create(ht.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ht.name})}}const gi=4294967295;function OE(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function xf(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function If(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function $E(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const BE=-1,TE=4294967296-1,PE=17179869184-1;function RE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=PE)if(e===0&&t<=TE){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),xf(r,4,t),n}}function CE(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function NE(t){if(t instanceof Date){const e=CE(t);return RE(e)}else return null}function UE(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=If(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ht(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function FE(t){const e=UE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const kE={type:BE,encode:NE,decode:FE};class Cs{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(kE)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new Rs(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new Rs(o,s)}}}return e instanceof Rs?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new Rs(n,e)}}Cs.defaultCodec=new Cs;function LE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ja(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):LE(t)?new Uint8Array(t):Uint8Array.from(t)}const ME=100,jE=2048;class qa{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Cs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??ME,this.initialBufferSize=e?.initialBufferSize??jE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new qa({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=wE(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),_E(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=ja(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),OE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),xf(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function qE(t,e){return new qa(e).encodeSharedRef(t)}function za(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const zE=16,KE=16;class VE{constructor(e=zE,n=KE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=_f(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Ka="array",yi="map_key",Sf="map_value",HE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ht("The type of key must be string or number but "+typeof t)};class WE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Ka,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=yi,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ka){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===yi||e.type===Sf){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const wi=-1,Va=new DataView(new ArrayBuffer(0)),GE=new Uint8Array(Va.buffer);try{Va.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Df=new RangeError("Insufficient data"),ZE=new VE;class Ha{constructor(e){this.totalPos=0,this.pos=0,this.view=Va,this.bytes=GE,this.headByte=wi,this.stack=new WE,this.entered=!1,this.extensionCodec=e?.extensionCodec??Cs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??gi,this.maxBinLength=e?.maxBinLength??gi,this.maxArrayLength=e?.maxArrayLength??gi,this.maxMapLength=e?.maxMapLength??gi,this.maxExtLength=e?.maxExtLength??gi,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:ZE,this.mapKeyConverter=e?.mapKeyConverter??HE}clone(){return new Ha({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=wi,this.stack.reset()}setBuffer(e){const n=ja(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===wi&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ja(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${za(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new ht(`Unrecognized type byte: ${za(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Ka)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===yi){if(n==="__proto__")throw new ht("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Sf;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=yi;continue e}}return n}}readHeadByte(){return this.headByte===wi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=wi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ht(`Unrecognized array type byte: ${za(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ht(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ht(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new ht(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Df;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=AE(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===yi:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new ht(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Df;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new ht(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=$E(this.view,this.pos);return this.pos+=8,e}readI64(){const e=If(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function YE(t,e){return new Ha(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ns(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wa(t,...e){if(!Ns(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 Af(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function Of(t){if(typeof t!="function")throw new Error("function expected");return!0}function En(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function bi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Us(t){if(!Array.isArray(t))throw new Error("array expected")}function Fs(t,e){if(!Af(!0,e))throw new Error(`${t}: array of strings expected`)}function Ga(t,e){if(!Af(!1,e))throw new Error(`${t}: array of numbers expected`)}function ft(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function dt(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Fs("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Us(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Us(i),i.map(s=>{En("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function pt(t=""){return En("join",t),{encode:e=>(Fs("join.decode",e),e.join(t)),decode:e=>(En("join.decode",e),e.split(t))}}function ks(t,e="="){return bi(t),En("padding",e),{encode(n){for(Fs("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Fs("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function $f(t){return Of(t),{encode:e=>e,decode:e=>t(e)}}function Bf(t,e,n){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Us(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(bi(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=r;u<o;u++){const l=s[u],f=e*a,h=f+l;if(!Number.isSafeInteger(h)||f/e!==a||h-l!==f)throw new Error("convertRadix: carry overflow");const d=h/n;a=h%n;const p=Math.floor(d);if(s[u]=p,!Number.isSafeInteger(p)||p*n+a!==h)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:r=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const Tf=(t,e)=>e===0?t:Tf(e,t%e),Ls=(t,e)=>t+(e-Tf(t,e)),Ms=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Za(t,e,n,r){if(Us(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Ls(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ls(e,n)}`);let i=0,s=0;const o=Ms[e],a=Ms[n]-1,c=[];for(const u of t){if(bi(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const l=Ms[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function XE(t){bi(t);const e=2**8;return{encode:n=>{if(!Ns(n))throw new Error("radix.encode input should be Uint8Array");return Bf(Array.from(n),e,t)},decode:n=>(Ga("radix.decode",n),Uint8Array.from(Bf(n,t,e)))}}function _t(t,e=!1){if(bi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ls(8,t)>32||Ls(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Ns(n))throw new Error("radix2.encode input should be Uint8Array");return Za(Array.from(n),8,t,!e)},decode:n=>(Ga("radix2.decode",n),Uint8Array.from(Za(n,t,8,e)))}}function Pf(t){return Of(t),function(...e){try{return t.apply(null,e)}catch{}}}const JE=ft(_t(5),dt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ks(5),pt("")),Rf=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Cf=(t,e)=>{En("base64",t);const n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Ya=t=>ft(XE(58),dt(t),pt("")),Xa=ft(dt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),pt("")),Nf=[996825010,642813549,513874426,1027748829,705979059];function mi(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Nf.length;r++)(e>>r&1)===1&&(n^=Nf[r]);return n}function Uf(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=mi(i)^o>>5}i=mi(i);for(let s=0;s<r;s++)i=mi(i)^t.charCodeAt(s)&31;for(let s of e)i=mi(i)^s;for(let s=0;s<6;s++)i=mi(i);return i^=n,Xa.encode(Za([i%Ms[30]],30,5,!1))}function Ff(t){const e=t==="bech32"?1:734539939,n=_t(5),r=n.decode,i=n.encode,s=Pf(r);function o(f,h,d=90){En("bech32.encode prefix",f),Ns(h)&&(h=Array.from(h)),Ga("bech32.encode",h);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+h.length;if(d!==!1&&g>d)throw new TypeError(`Length ${g} exceeds limit ${d}`);const y=f.toLowerCase(),I=Uf(y,h,e);return`${y}1${Xa.encode(h)}${I}`}function a(f,h=90){En("bech32.decode input",f);const d=f.length;if(d<8||h!==!1&&d>h)throw new TypeError(`invalid string length: ${d} (${f}). Expected (8..${h})`);const p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=p.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=p.slice(0,g),I=p.slice(g+1);if(I.length<6)throw new Error("Data must be at least 6 characters long");const D=Xa.decode(I).slice(0,-6),E=Uf(y,D,e);if(!I.endsWith(E))throw new Error(`Invalid checksum in ${f}: expected "${E}"`);return{prefix:y,words:D}}const c=Pf(a);function u(f){const{prefix:h,words:d}=a(f,!1);return{prefix:h,words:d,bytes:r(d)}}function l(f,h){return o(f,i(h))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const QE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",e3={encode(t){return Wa(t),t.toHex()},decode(t){return En("hex",t),Uint8Array.fromHex(t)}};function Ja(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function kf(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ja(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function vi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=kf(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Ja(n)}function t3(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var n3=t3,r3=n3;const Lf=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")},i3=t=>new TextEncoder().encode(t),s3=t=>new TextDecoder().decode(t);class o3{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class a3{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Mf(this,e)}}class c3{constructor(e){this.decoders=e}or(e){return Mf(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Mf=(t,e)=>new c3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class u3{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new o3(e,n,r),this.decoder=new a3(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const js=({name:t,prefix:e,encode:n,decode:r})=>new u3(t,e,n,r),Ei=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=r3(n,e);return js({prefix:t,name:e,encode:r,decode:s=>Lf(i(s))})},l3=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},h3=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Ae=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>js({prefix:e,name:t,encode(i){return h3(i,r,n)},decode(i){return l3(i,r,n,t)}}),f3=js({prefix:"\0",name:"identity",encode:t=>s3(t),decode:t=>i3(t)});var d3=Object.freeze({__proto__:null,identity:f3});const p3=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var g3=Object.freeze({__proto__:null,base2:p3});const y3=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var w3=Object.freeze({__proto__:null,base8:y3});const b3=Ei({prefix:"9",name:"base10",alphabet:"0123456789"});var m3=Object.freeze({__proto__:null,base10:b3});const v3=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),E3=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var _3=Object.freeze({__proto__:null,base16:v3,base16upper:E3});const x3=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),I3=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),S3=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),D3=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),A3=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),O3=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),$3=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),B3=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),T3=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var P3=Object.freeze({__proto__:null,base32:x3,base32upper:I3,base32pad:S3,base32padupper:D3,base32hex:A3,base32hexupper:O3,base32hexpad:$3,base32hexpadupper:B3,base32z:T3});const R3=Ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),C3=Ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var N3=Object.freeze({__proto__:null,base36:R3,base36upper:C3});const U3=Ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),F3=Ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var k3=Object.freeze({__proto__:null,base58btc:U3,base58flickr:F3});const L3=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),M3=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),j3=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),q3=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var z3=Object.freeze({__proto__:null,base64:L3,base64pad:M3,base64url:j3,base64urlpad:q3});const jf=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=jf.reduce((t,e,n)=>(t[n]=e,t),[]),V3=jf.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function H3(t){return t.reduce((e,n)=>(e+=K3[n],e),"")}function W3(t){const e=[];for(const n of t){const r=V3[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const G3=js({prefix:"\u{1F680}",name:"base256emoji",encode:H3,decode:W3});var Z3=Object.freeze({__proto__:null,base256emoji:G3}),Y3=zf,qf=128,X3=127,J3=~X3,Q3=Math.pow(2,31);function zf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Q3;)e[n++]=t&255|qf,t/=128;for(;t&J3;)e[n++]=t&255|qf,t>>>=7;return e[n]=t|0,zf.bytes=n-r+1,e}var e_=Qa,t_=128,Kf=127;function Qa(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Kf)<<i:(o&Kf)*Math.pow(2,i),i+=7}while(o>=t_);return Qa.bytes=s-r,n}var n_=Math.pow(2,7),r_=Math.pow(2,14),i_=Math.pow(2,21),s_=Math.pow(2,28),o_=Math.pow(2,35),a_=Math.pow(2,42),c_=Math.pow(2,49),u_=Math.pow(2,56),l_=Math.pow(2,63),h_=function(t){return t<n_?1:t<r_?2:t<i_?3:t<s_?4:t<o_?5:t<a_?6:t<c_?7:t<u_?8:t<l_?9:10},f_={encode:Y3,decode:e_,encodingLength:h_},Vf=f_;const Hf=(t,e,n=0)=>(Vf.encode(t,e,n),e),Wf=t=>Vf.encodingLength(t),ec=(t,e)=>{const n=e.byteLength,r=Wf(t),i=r+Wf(n),s=new Uint8Array(i+n);return Hf(t,s,0),Hf(n,s,r),s.set(e,i),new d_(t,n,e,s)};class d_{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Gf=({name:t,code:e,encode:n})=>new p_(t,e,n);class p_{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ec(this.code,n):n.then(r=>ec(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Zf=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),g_=Gf({name:"sha2-256",code:18,encode:Zf("SHA-256")}),y_=Gf({name:"sha2-512",code:19,encode:Zf("SHA-512")});var w_=Object.freeze({__proto__:null,sha256:g_,sha512:y_});const Yf=0,b_="identity",Xf=Lf;var m_=Object.freeze({__proto__:null,identity:{code:Yf,name:b_,encode:Xf,digest:t=>ec(Yf,Xf(t))}});new TextEncoder,new TextDecoder;const Jf={...d3,...g3,...w3,...m3,..._3,...P3,...N3,...k3,...z3,...Z3};({...w_,...m_});function Qf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const ed=Qf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),tc=Qf("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=kf(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),td={utf8:ed,"utf-8":ed,hex:Jf.base16,latin1:tc,ascii:tc,binary:tc,...Jf};function xt(t,e="utf8"){const n=td[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ja(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function rt(t,e="utf8"){const n=td[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}const v_={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"}},E_="Input must be an string, Buffer or Uint8Array";function __(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(E_);return e}function x_(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function qs(t){return(4294967296+t).toString(16).substring(1)}function I_(t,e,n){let r=`
18
- `+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=qs(e[i]).toUpperCase(),r+=" ",r+=qs(e[i+1]).toUpperCase();else if(n===64)r+=qs(e[i+1]).toUpperCase(),r+=qs(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
19
- `+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function S_(t,e,n){let r=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=t(i),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var nd={normalizeInput:__,toHex:x_,debugPrint:I_,testSpeed:S_};const zs=nd;function Ks(t,e,n){const r=t[e]+t[n];let i=t[e+1]+t[n+1];r>=4294967296&&i++,t[e]=r,t[e+1]=i}function rd(t,e,n,r){let i=t[e]+n;n<0&&(i+=4294967296);let s=t[e+1]+r;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function id(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function _n(t,e,n,r,i,s){const o=_i[i],a=_i[i+1],c=_i[s],u=_i[s+1];Ks(X,t,e),rd(X,t,o,a);let l=X[r]^X[t],f=X[r+1]^X[t+1];X[r]=f,X[r+1]=l,Ks(X,n,r),l=X[e]^X[n],f=X[e+1]^X[n+1],X[e]=l>>>24^f<<8,X[e+1]=f>>>24^l<<8,Ks(X,t,e),rd(X,t,c,u),l=X[r]^X[t],f=X[r+1]^X[t+1],X[r]=l>>>16^f<<16,X[r+1]=f>>>16^l<<16,Ks(X,n,r),l=X[e]^X[n],f=X[e+1]^X[n+1],X[e]=f>>>31^l<<1,X[e+1]=l>>>31^f<<1}const sd=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),D_=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Fe=new Uint8Array(D_.map(function(t){return t*2})),X=new Uint32Array(32),_i=new Uint32Array(32);function od(t,e){let n=0;for(n=0;n<16;n++)X[n]=t.h[n],X[n+16]=sd[n];for(X[24]=X[24]^t.t,X[25]=X[25]^t.t/4294967296,e&&(X[28]=~X[28],X[29]=~X[29]),n=0;n<32;n++)_i[n]=id(t.b,4*n);for(n=0;n<12;n++)_n(0,8,16,24,Fe[n*16+0],Fe[n*16+1]),_n(2,10,18,26,Fe[n*16+2],Fe[n*16+3]),_n(4,12,20,28,Fe[n*16+4],Fe[n*16+5]),_n(6,14,22,30,Fe[n*16+6],Fe[n*16+7]),_n(0,10,20,30,Fe[n*16+8],Fe[n*16+9]),_n(2,12,22,24,Fe[n*16+10],Fe[n*16+11]),_n(4,14,16,26,Fe[n*16+12],Fe[n*16+13]),_n(6,8,18,28,Fe[n*16+14],Fe[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^X[n]^X[n+16]}const xn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function ad(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};xn.fill(0),xn[0]=t,e&&(xn[1]=e.length),xn[2]=1,xn[3]=1,n&&xn.set(n,32),r&&xn.set(r,48);for(let s=0;s<16;s++)i.h[s]=sd[s]^id(xn,s*4);return e&&(nc(i,e),i.c=128),i}function nc(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,od(t,!1),t.c=0),t.b[t.c++]=e[n]}function cd(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;od(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3);return e}function ud(t,e,n,r,i){n=n||64,t=zs.normalizeInput(t),r&&(r=zs.normalizeInput(r)),i&&(i=zs.normalizeInput(i));const s=ad(n,e,r,i);return nc(s,t),cd(s)}function A_(t,e,n,r,i){const s=ud(t,e,n,r,i);return zs.toHex(s)}var O_={blake2b:ud,blake2bHex:A_,blake2bInit:ad,blake2bUpdate:nc,blake2bFinal:cd};const ld=nd;function $_(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function In(t,e,n,r,i,s){te[t]=te[t]+te[e]+i,te[r]=Vs(te[r]^te[t],16),te[n]=te[n]+te[r],te[e]=Vs(te[e]^te[n],12),te[t]=te[t]+te[e]+s,te[r]=Vs(te[r]^te[t],8),te[n]=te[n]+te[r],te[e]=Vs(te[e]^te[n],7)}function Vs(t,e){return t>>>e^t<<32-e}const hd=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),te=new Uint32Array(16),Oe=new Uint32Array(16);function fd(t,e){let n=0;for(n=0;n<8;n++)te[n]=t.h[n],te[n+8]=hd[n];for(te[12]^=t.t,te[13]^=t.t/4294967296,e&&(te[14]=~te[14]),n=0;n<16;n++)Oe[n]=$_(t.b,4*n);for(n=0;n<10;n++)In(0,4,8,12,Oe[ke[n*16+0]],Oe[ke[n*16+1]]),In(1,5,9,13,Oe[ke[n*16+2]],Oe[ke[n*16+3]]),In(2,6,10,14,Oe[ke[n*16+4]],Oe[ke[n*16+5]]),In(3,7,11,15,Oe[ke[n*16+6]],Oe[ke[n*16+7]]),In(0,5,10,15,Oe[ke[n*16+8]],Oe[ke[n*16+9]]),In(1,6,11,12,Oe[ke[n*16+10]],Oe[ke[n*16+11]]),In(2,7,8,13,Oe[ke[n*16+12]],Oe[ke[n*16+13]]),In(3,4,9,14,Oe[ke[n*16+14]],Oe[ke[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=te[n]^te[n+8]}function dd(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(hd),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(rc(r,e),r.c=64),r}function rc(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,fd(t,!1),t.c=0),t.b[t.c++]=e[n]}function pd(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;fd(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3)&255;return e}function gd(t,e,n){n=n||32,t=ld.normalizeInput(t);const r=dd(n,e);return rc(r,t),pd(r)}function B_(t,e,n){const r=gd(t,e,n);return ld.toHex(r)}var T_={blake2s:gd,blake2sHex:B_,blake2sInit:dd,blake2sUpdate:rc,blake2sFinal:pd};const xi=O_,Ii=T_;var P_={blake2b:xi.blake2b,blake2bHex:xi.blake2bHex,blake2bInit:xi.blake2bInit,blake2bUpdate:xi.blake2bUpdate,blake2bFinal:xi.blake2bFinal,blake2s:Ii.blake2s,blake2sHex:Ii.blake2sHex,blake2sInit:Ii.blake2sInit,blake2sUpdate:Ii.blake2sUpdate,blake2sFinal:Ii.blake2sFinal},R_=Object.defineProperty,C_=Object.defineProperties,N_=Object.getOwnPropertyDescriptors,yd=Object.getOwnPropertySymbols,U_=Object.prototype.hasOwnProperty,F_=Object.prototype.propertyIsEnumerable,wd=(t,e,n)=>e in t?R_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ur=(t,e)=>{for(var n in e||(e={}))U_.call(e,n)&&wd(t,n,e[n]);if(yd)for(var n of yd(e))F_.call(e,n)&&wd(t,n,e[n]);return t},Si=(t,e)=>C_(t,N_(e));const k_=":";function ir(t){const[e,n]=t.split(k_);return{namespace:e,reference:n}}function bd(t,e){return t.includes(":")?[t]:e.chains||[]}var L_=Object.defineProperty,M_=Object.defineProperties,j_=Object.getOwnPropertyDescriptors,md=Object.getOwnPropertySymbols,q_=Object.prototype.hasOwnProperty,z_=Object.prototype.propertyIsEnumerable,ic=(t,e,n)=>e in t?L_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,vd=(t,e)=>{for(var n in e||(e={}))q_.call(e,n)&&ic(t,n,e[n]);if(md)for(var n of md(e))z_.call(e,n)&&ic(t,n,e[n]);return t},K_=(t,e)=>M_(t,j_(e)),Ed=(t,e,n)=>ic(t,typeof e!="symbol"?e+"":e,n);const V_="ReactNative",gt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},H_="js";function Hs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Sn(){return!Xn()&&!!aa()&&navigator.product===V_}function W_(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function G_(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Fr(){return!Hs()&&!!aa()&&!!Xn()}function Di(){return Sn()?gt.reactNative:Hs()?gt.node:Fr()?gt.browser:gt.unknown}function _d(){var t;try{return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function Z_(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function Y_(t){var e,n;const r=xd();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),K_(vd(vd({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function xd(){return sh()||{name:"",description:"",url:"",icons:[""]}}function X_(){if(Di()===gt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=zm();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 J_(){var t;const e=Di();return e===gt.browser?[e,((t=ih())==null?void 0:t.host)||"unknown"].join(":"):e}function Id(t,e,n){const r=X_(),i=J_();return[[t,e].join("-"),[H_,n].join("-"),r,i].join("/")}function Q_({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=Id(t,e,r),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=Z_(u[1]||"",f);return u[0]+"?"+h}function sr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function sc(t){return Object.fromEntries(t.entries())}function oc(t){return new Map(Object.entries(t))}function or(t=M.FIVE_MINUTES,e){const n=M.toMiliseconds(t||M.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},n),r=a,i=c})}}function Kt(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function Sd(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function ex(t){return Sd("topic",t)}function tx(t){return Sd("id",t)}function Dd(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function ve(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function Dn(t){return Date.now()>=M.toMiliseconds(t)}function ie(t,e){return`${t}${e?`:${e}`:""}`}function ar(t=[],e=[]){return[...new Set([...t,...e])]}async function nx({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=rx(s,t,e),a=Di();if(a===gt.browser){if(!((r=Xn())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}ix(o)}else a===gt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function rx(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${cx(r,!0)}`}else i=`${i}/wc?${r}`;return i}function ix(t){let e="_self";ax()?e="_top":(ox()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function sx(t,e){let n="";try{if(Fr()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function Ad(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function Od(){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 ac(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function ox(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ax(){try{return window.self!==window.top}catch{return!1}}function cx(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function $d(t){return Buffer.from(t,"base64").toString("utf-8")}function ux(t){return new Promise(e=>setTimeout(e,t))}class lx{constructor({limit:e}){Ed(this,"limit"),Ed(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}}const Ws=BigInt(2**32-1),Bd=BigInt(32);function Td(t,e=!1){return e?{h:Number(t&Ws),l:Number(t>>Bd&Ws)}:{h:Number(t>>Bd&Ws)|0,l:Number(t&Ws)|0}}function Pd(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Td(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Rd=(t,e,n)=>t>>>n,Cd=(t,e,n)=>t<<32-n|e>>>n,An=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,Ai=(t,e,n)=>t<<64-n|e>>>n-32,Oi=(t,e,n)=>t>>>n-32|e<<64-n,hx=(t,e)=>e,fx=(t,e)=>t,dx=(t,e,n)=>t<<n|e>>>32-n,px=(t,e,n)=>e<<n|t>>>32-n,gx=(t,e,n)=>e<<n-32|t>>>64-n,yx=(t,e,n)=>t<<n-32|e>>>64-n;function Pt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const cc=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),uc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,wx=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),bx=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,mx=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),vx=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,kr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Gs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Rt(t,...e){if(!Gs(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Zs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");sn(t.outputLen),sn(t.blockLen)}function $n(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 lc(t,e){Rt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function $i(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function It(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function hc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Vt(t,e){return t<<32-e|t>>>e}const Nd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Ud(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const on=Nd?t=>t:t=>Ud(t);function Ex(t){for(let e=0;e<t.length;e++)t[e]=Ud(t[e]);return t}const Bn=Nd?t=>t:Ex,Fd=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",_x=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lr(t){if(Rt(t),Fd)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=_x[t[n]];return e}const an={_0:48,_9:57,A:65,F:70,a:97,f:102};function kd(t){if(t>=an._0&&t<=an._9)return t-an._0;if(t>=an.A&&t<=an.F)return t-(an.A-10);if(t>=an.a&&t<=an.f)return t-(an.a-10)}function Ys(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Fd)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=kd(t.charCodeAt(s)),a=kd(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Ld(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ct(t){return typeof t=="string"&&(t=Ld(t)),Rt(t),t}function Tn(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Rt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class Xs{}function Bi(t){const e=r=>t().update(Ct(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function xx(t){const e=(r,i)=>t(i).update(Ct(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function cr(t=32){if(kr&&typeof kr.getRandomValues=="function")return kr.getRandomValues(new Uint8Array(t));if(kr&&typeof kr.randomBytes=="function")return Uint8Array.from(kr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Ix=BigInt(0),Ti=BigInt(1),Sx=BigInt(2),Dx=BigInt(7),Ax=BigInt(256),Ox=BigInt(113),Md=[],jd=[],qd=[];for(let t=0,e=Ti,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Md.push(2*(5*r+n)),jd.push((t+1)*(t+2)/2%64);let i=Ix;for(let s=0;s<7;s++)e=(e<<Ti^(e>>Dx)*Ox)%Ax,e&Sx&&(i^=Ti<<(Ti<<BigInt(s))-Ti);qd.push(i)}const zd=Pd(qd,!0),$x=zd[0],Bx=zd[1],Kd=(t,e,n)=>n>32?gx(t,e,n):dx(t,e,n),Vd=(t,e,n)=>n>32?yx(t,e,n):px(t,e,n);function Tx(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],f=Kd(u,l,1)^n[a],h=Vd(u,l,1)^n[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=jd[o],c=Kd(i,s,a),u=Vd(i,s,a),l=Md[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=$x[r],t[1]^=Bx[r]}It(n)}class fc extends Xs{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,sn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$i(this.state)}clone(){return this._cloneInto()}keccak(){Bn(this.state32),Tx(this.state32,this.rounds),Bn(this.state32),this.posOut=0,this.pos=0}update(e){$n(this),e=Ct(e),Rt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){$n(this,!1),Rt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return sn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(lc(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,It(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new fc(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Px=(t,e,n)=>Bi(()=>new fc(e,t,n)),Rx=Px(1,136,256/8);function Cx(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Nx(t,e,n){return t&e^~t&n}function Ux(t,e,n){return t&e^t&n^e&n}class Hd extends Xs{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=hc(this.buffer)}update(e){$n(this),e=Ct(e),Rt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=hc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$n(this),lc(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,It(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;Cx(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=hc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Pn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Fx=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Rn=new Uint32Array(64);class kx extends Hd{constructor(e=32){super(64,e,8,!1),this.A=Pn[0]|0,this.B=Pn[1]|0,this.C=Pn[2]|0,this.D=Pn[3]|0,this.E=Pn[4]|0,this.F=Pn[5]|0,this.G=Pn[6]|0,this.H=Pn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)Rn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const h=Rn[f-15],d=Rn[f-2],p=Vt(h,7)^Vt(h,18)^h>>>3,g=Vt(d,17)^Vt(d,19)^d>>>10;Rn[f]=g+Rn[f-7]+p+Rn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=Vt(a,6)^Vt(a,11)^Vt(a,25),d=l+h+Nx(a,c,u)+Fx[f]+Rn[f]|0,p=(Vt(r,2)^Vt(r,13)^Vt(r,22))+Ux(r,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=r,r=d+p|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){It(Rn)}destroy(){this.set(0,0,0,0,0,0,0,0),It(this.buffer)}}const Wd=Pd(["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))),Lx=Wd[0],Mx=Wd[1],Cn=new Uint32Array(80),Nn=new Uint32Array(80);class dc extends Hd{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let E=0;E<16;E++,n+=4)Cn[E]=e.getUint32(n),Nn[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const $=Cn[E-15]|0,R=Nn[E-15]|0,C=An($,R,1)^An($,R,8)^Rd($,R,7),U=On($,R,1)^On($,R,8)^Cd($,R,7),N=Cn[E-2]|0,O=Nn[E-2]|0,G=An(N,O,19)^Ai(N,O,61)^Rd(N,O,6),W=On(N,O,19)^Oi(N,O,61)^Cd(N,O,6),P=wx(U,W,Nn[E-7],Nn[E-16]),v=bx(P,C,G,Cn[E-7],Cn[E-16]);Cn[E]=v|0,Nn[E]=P|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:y,Hh:I,Hl:D}=this;for(let E=0;E<80;E++){const $=An(f,h,14)^An(f,h,18)^Ai(f,h,41),R=On(f,h,14)^On(f,h,18)^Oi(f,h,41),C=f&d^~f&g,U=h&p^~h&y,N=mx(D,R,U,Mx[E],Nn[E]),O=vx(N,I,$,C,Lx[E],Cn[E]),G=N|0,W=An(r,i,28)^Ai(r,i,34)^Ai(r,i,39),P=On(r,i,28)^Oi(r,i,34)^Oi(r,i,39),v=r&s^r&a^s&a,m=i&o^i&c^o&c;I=g|0,D=y|0,g=d|0,y=p|0,d=f|0,p=h|0,{h:f,l:h}=Pt(u|0,l|0,O|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const w=cc(G,P,m);r=uc(w,O,W,v),i=w|0}({h:r,l:i}=Pt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Pt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=Pt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=Pt(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:y}=Pt(this.Gh|0,this.Gl|0,g|0,y|0),{h:I,l:D}=Pt(this.Hh|0,this.Hl|0,I|0,D|0),this.set(r,i,s,o,a,c,u,l,f,h,d,p,g,y,I,D)}roundClean(){It(Cn,Nn)}destroy(){It(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class jx extends dc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const je=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class qx extends dc{constructor(){super(32),this.Ah=je[0]|0,this.Al=je[1]|0,this.Bh=je[2]|0,this.Bl=je[3]|0,this.Ch=je[4]|0,this.Cl=je[5]|0,this.Dh=je[6]|0,this.Dl=je[7]|0,this.Eh=je[8]|0,this.El=je[9]|0,this.Fh=je[10]|0,this.Fl=je[11]|0,this.Gh=je[12]|0,this.Gl=je[13]|0,this.Hh=je[14]|0,this.Hl=je[15]|0}}const Js=Bi(()=>new kx),zx=Bi(()=>new dc),Kx=Bi(()=>new jx),Vx=Bi(()=>new qx),Hx=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Ee=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),K=new Uint32Array(32);function Un(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*n],d=K[2*n+1],p=K[2*r],g=K[2*r+1],y=cc(c,l,o);u=uc(y,u,f,a),c=y|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:hx(g,p),Dl:fx(g)},{h:d,l:h}=Pt(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:An(f,l,24),Bl:On(f,l,24)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*n]=h,K[2*n+1]=d,K[2*r]=p,K[2*r+1]=g}function Fn(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*n],d=K[2*n+1],p=K[2*r],g=K[2*r+1],y=cc(c,l,o);u=uc(y,u,f,a),c=y|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:An(g,p,16),Dl:On(g,p,16)},{h:d,l:h}=Pt(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:Ai(f,l,63),Bl:Oi(f,l,63)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*n]=h,K[2*n+1]=d,K[2*r]=p,K[2*r+1]=g}function Wx(t,e={},n,r,i){if(sn(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class Gx extends Xs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,sn(e),sn(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=$i(this.buffer)}update(e){$n(this),e=Ct(e),Rt(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(Bn(i),this.compress(i,0,!1),Bn(i),this.pos=0);const u=Math.min(n-this.pos,s-c),l=o+c;if(u===n&&!(l%4)&&c+u<s){const f=new Uint32Array(a,l,Math.floor((s-c)/4));Bn(f);for(let h=0;c+n<s;h+=i.length,c+=n)this.length+=n,this.compress(f,h,!1);Bn(f);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){$n(this),lc(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,It(this.buffer.subarray(n)),Bn(r),this.compress(r,0,!0),Bn(r);const i=$i(e);this.get().forEach((s,o)=>i[o]=on(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Zx extends Gx{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Ee[0]|0,this.v0h=Ee[1]|0,this.v1l=Ee[2]|0,this.v1h=Ee[3]|0,this.v2l=Ee[4]|0,this.v2h=Ee[5]|0,this.v3l=Ee[6]|0,this.v3h=Ee[7]|0,this.v4l=Ee[8]|0,this.v4h=Ee[9]|0,this.v5l=Ee[10]|0,this.v5h=Ee[11]|0,this.v6l=Ee[12]|0,this.v6h=Ee[13]|0,this.v7l=Ee[14]|0,this.v7h=Ee[15]|0,Wx(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Ct(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Ct(s);const a=$i(s);this.v4l^=on(a[0]),this.v4h^=on(a[1]),this.v5l^=on(a[2]),this.v5h^=on(a[3])}if(i!==void 0){i=Ct(i);const a=$i(i);this.v6l^=on(a[0]),this.v6h^=on(a[1]),this.v7l^=on(a[2]),this.v7h^=on(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:f,v5h:h,v6l:d,v6h:p,v7l:g,v7h:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=h|0,this.v6l=d|0,this.v6h=p|0,this.v7l=g|0,this.v7h=y|0}compress(e,n,r){this.get().forEach((c,u)=>K[u]=c),K.set(Ee,16);let{h:i,l:s}=Td(BigInt(this.length));K[24]=Ee[8]^s,K[25]=Ee[9]^i,r&&(K[28]=~K[28],K[29]=~K[29]);let o=0;const a=Hx;for(let c=0;c<12;c++)Un(0,4,8,12,e,n+2*a[o++]),Fn(0,4,8,12,e,n+2*a[o++]),Un(1,5,9,13,e,n+2*a[o++]),Fn(1,5,9,13,e,n+2*a[o++]),Un(2,6,10,14,e,n+2*a[o++]),Fn(2,6,10,14,e,n+2*a[o++]),Un(3,7,11,15,e,n+2*a[o++]),Fn(3,7,11,15,e,n+2*a[o++]),Un(0,5,10,15,e,n+2*a[o++]),Fn(0,5,10,15,e,n+2*a[o++]),Un(1,6,11,12,e,n+2*a[o++]),Fn(1,6,11,12,e,n+2*a[o++]),Un(2,7,8,13,e,n+2*a[o++]),Fn(2,7,8,13,e,n+2*a[o++]),Un(3,4,9,14,e,n+2*a[o++]),Fn(3,4,9,14,e,n+2*a[o++]);this.v0l^=K[0]^K[16],this.v0h^=K[1]^K[17],this.v1l^=K[2]^K[18],this.v1h^=K[3]^K[19],this.v2l^=K[4]^K[20],this.v2h^=K[5]^K[21],this.v3l^=K[6]^K[22],this.v3h^=K[7]^K[23],this.v4l^=K[8]^K[24],this.v4h^=K[9]^K[25],this.v5l^=K[10]^K[26],this.v5h^=K[11]^K[27],this.v6l^=K[12]^K[28],this.v6h^=K[13]^K[29],this.v7l^=K[14]^K[30],this.v7h^=K[15]^K[31],It(K)}destroy(){this.destroyed=!0,It(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Yx=xx(t=>new Zx(t)),Xx="https://rpc.walletconnect.org/v1";function Gd(t){const e=`Ethereum Signed Message:
20
- ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Rx(n)).toString("hex")}async function Jx(t,e,n,r,i,s){switch(n.t){case"eip191":return await Qx(t,e,n.s);case"eip1271":return await e8(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}async function Qx(t,e,n){return(await jv({hash:Gd(e),signature:n})).toLowerCase()===t.toLowerCase()}async function e8(t,e,n,r,i,s){const o=ir(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),f=(e.startsWith("0x")?e:Gd(e)).substring(2),h=a+f+c+l+u,d=await fetch(`${s||Xx}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:t8(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:p}=await d.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function t8(){return Date.now()+Math.floor(Math.random()*1e3)}function n8(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return pi.encode(s)}function r8(t){const e=new Uint8Array(Buffer.from(t,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const i=Yx(r,{dkLen:32});return pi.encode(i)}function Zd(t){const e=new Uint8Array(Js(i8(t)));return pi.encode(e)}function i8(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Yd(t){const e=Buffer.from(t,"base64"),n=YE(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=qE(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=Vx(s);return JE.encode(o).replace(/=+$/,"")}function pc(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function s8(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(pc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(pc(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(pc(r.length)),i.push(r);const s=Buffer.concat(i),o=Js(s);return Buffer.from(o).toString("hex").toUpperCase()}function o8(t){var e,n;const r=[];try{if(typeof t=="string")return r.push(t),r;if(typeof t!="object")return r;t!=null&&t.id&&r.push(t.id);const i=(n=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:n.transactionHashes;i&&r.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return r}var a8=Object.defineProperty,c8=Object.defineProperties,u8=Object.getOwnPropertyDescriptors,Xd=Object.getOwnPropertySymbols,l8=Object.prototype.hasOwnProperty,h8=Object.prototype.propertyIsEnumerable,Jd=(t,e,n)=>e in t?a8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f8=(t,e)=>{for(var n in e||(e={}))l8.call(e,n)&&Jd(t,n,e[n]);if(Xd)for(var n of Xd(e))h8.call(e,n)&&Jd(t,n,e[n]);return t},d8=(t,e)=>c8(t,u8(e));const p8="did:pkh:",gc=t=>t?.split(":"),g8=t=>{const e=t&&gc(t);if(e)return t.includes(p8)?e[3]:e[1]},yc=t=>{const e=t&&gc(t);if(e)return e[2]+":"+e[3]},Qs=t=>{const e=t&&gc(t);if(e)return e.pop()};async function Qd(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=ep(i,i.iss),o=Qs(i.iss);return await Jx(o,s,r,yc(i.iss),n)}const ep=(t,e)=>{const n=`${t.domain} wants you to sign in with your Ethereum account:`,r=Qs(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: ${g8(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(g=>`
21
- - ${g}`).join("")}`:void 0,p=eo(t.resources);if(p){const g=Pi(p);i=I8(i,g)}return[n,r,"",i,"",s,o,a,c,u,l,f,h,d].filter(g=>g!=null).join(`
22
- `)};function y8(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function w8(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function ur(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function b8(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:m8(e,n,r)}}}function m8(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function tp(t){return ur(t),`urn:recap:${y8(t).replace(/=/g,"")}`}function Pi(t){const e=w8(t.replace("urn:recap:",""));return ur(e),e}function v8(t,e,n){const r=b8(t,e,n);return tp(r)}function E8(t){return t&&t.includes("urn:recap:")}function _8(t,e){const n=Pi(t),r=Pi(e),i=x8(n,r);return tp(i)}function x8(t,e){ur(t),ur(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;r.att[i]=d8(f8({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function I8(t="",e){ur(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,h)=>f.action.localeCompare(h.action));const u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});const l=Object.keys(u).map(f=>(i++,`(${i}) '${f}': '${u[f].join("', '")}' for '${a}'.`));r.push(l.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${t?t+" ":""}${o}`}function np(t){var e;const n=Pi(t);ur(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function rp(t){const e=Pi(t);ur(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function eo(t){if(!t)return;const e=t?.[t.length-1];return E8(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function ip(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function bc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function it(t,...e){if(!ip(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 sp(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 S8(t,e){it(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function kn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Mr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function D8(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const A8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function O8(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function mc(t){if(typeof t=="string")t=O8(t);else if(ip(t))t=vc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function $8(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function B8(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const T8=(t,e)=>{function n(r,...i){if(it(r),!A8)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?it(u):it(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&it(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");it(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,it(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(it(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(n,t),n};function op(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!R8(e))throw new Error("invalid output, must be aligned");return e}function ap(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function P8(t,e,n){wc(n);const r=new Uint8Array(16),i=D8(r);return ap(i,0,BigInt(e),n),ap(i,8,BigInt(t),n),r}function R8(t){return t.byteOffset%4===0}function vc(t){return Uint8Array.from(t)}const cp=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),C8=cp("expand 16-byte k"),N8=cp("expand 32-byte k"),U8=kn(C8),F8=kn(N8);function ne(t,e){return t<<e|t>>>32-e}function Ec(t){return t.byteOffset%4===0}const to=64,k8=16,up=2**32-1,lp=new Uint32Array;function L8(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(to),l=kn(u),f=Ec(i)&&Ec(s),h=f?kn(i):lp,d=f?kn(s):lp;for(let p=0;p<c;o++){if(t(e,n,r,l,o,a),o>=up)throw new Error("arx: counter overflow");const g=Math.min(to,c-p);if(f&&g===to){const y=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let I=0,D;I<k8;I++)D=y+I,d[D]=h[D]^l[I];p+=to;continue}for(let y=0,I;y<g;y++)I=p+y,s[I]=i[I]^u[y];p+=g}}function M8(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=$8({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return bc(i),bc(o),wc(s),wc(n),(a,c,u,l,f=0)=>{it(a),it(c),it(u);const h=u.length;if(l===void 0&&(l=new Uint8Array(h)),it(l),bc(f),f<0||f>=up)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p=a.length,g,y;if(p===32)d.push(g=vc(a)),y=F8;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=U8,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Ec(c)||d.push(c=vc(c));const I=kn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,I,kn(c.subarray(0,16)),I),c=c.subarray(16)}const D=16-i;if(D!==c.length)throw new Error(`arx: nonce must be ${D} or 16 bytes`);if(D!==12){const $=new Uint8Array(12);$.set(c,s?0:12-c.length),c=$,d.push(c)}const E=kn(c);return L8(t,y,I,E,u,l,f,o),Mr(...d),l}}const $e=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class j8{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=mc(e),it(e,32);const n=$e(e,0),r=$e(e,2),i=$e(e,4),s=$e(e,6),o=$e(e,8),a=$e(e,10),c=$e(e,12),u=$e(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=$e(e,16+2*l)}process(e,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],f=o[4],h=o[5],d=o[6],p=o[7],g=o[8],y=o[9],I=$e(e,n+0),D=$e(e,n+2),E=$e(e,n+4),$=$e(e,n+6),R=$e(e,n+8),C=$e(e,n+10),U=$e(e,n+12),N=$e(e,n+14);let O=s[0]+(I&8191),G=s[1]+((I>>>13|D<<3)&8191),W=s[2]+((D>>>10|E<<6)&8191),P=s[3]+((E>>>7|$<<9)&8191),v=s[4]+(($>>>4|R<<12)&8191),m=s[5]+(R>>>1&8191),w=s[6]+((R>>>14|C<<2)&8191),b=s[7]+((C>>>11|U<<5)&8191),x=s[8]+((U>>>8|N<<8)&8191),A=s[9]+(N>>>5|i),_=0,S=_+O*a+G*(5*y)+W*(5*g)+P*(5*p)+v*(5*d);_=S>>>13,S&=8191,S+=m*(5*h)+w*(5*f)+b*(5*l)+x*(5*u)+A*(5*c),_+=S>>>13,S&=8191;let B=_+O*c+G*a+W*(5*y)+P*(5*g)+v*(5*p);_=B>>>13,B&=8191,B+=m*(5*d)+w*(5*h)+b*(5*f)+x*(5*l)+A*(5*u),_+=B>>>13,B&=8191;let T=_+O*u+G*c+W*a+P*(5*y)+v*(5*g);_=T>>>13,T&=8191,T+=m*(5*p)+w*(5*d)+b*(5*h)+x*(5*f)+A*(5*l),_+=T>>>13,T&=8191;let q=_+O*l+G*u+W*c+P*a+v*(5*y);_=q>>>13,q&=8191,q+=m*(5*g)+w*(5*p)+b*(5*d)+x*(5*h)+A*(5*f),_+=q>>>13,q&=8191;let L=_+O*f+G*l+W*u+P*c+v*a;_=L>>>13,L&=8191,L+=m*(5*y)+w*(5*g)+b*(5*p)+x*(5*d)+A*(5*h),_+=L>>>13,L&=8191;let k=_+O*h+G*f+W*l+P*u+v*c;_=k>>>13,k&=8191,k+=m*a+w*(5*y)+b*(5*g)+x*(5*p)+A*(5*d),_+=k>>>13,k&=8191;let z=_+O*d+G*h+W*f+P*l+v*u;_=z>>>13,z&=8191,z+=m*c+w*a+b*(5*y)+x*(5*g)+A*(5*p),_+=z>>>13,z&=8191;let H=_+O*p+G*d+W*h+P*f+v*l;_=H>>>13,H&=8191,H+=m*u+w*c+b*a+x*(5*y)+A*(5*g),_+=H>>>13,H&=8191;let Z=_+O*g+G*p+W*d+P*h+v*f;_=Z>>>13,Z&=8191,Z+=m*l+w*u+b*c+x*a+A*(5*y),_+=Z>>>13,Z&=8191;let V=_+O*y+G*g+W*p+P*d+v*h;_=V>>>13,V&=8191,V+=m*f+w*l+b*u+x*c+A*a,_+=V>>>13,V&=8191,_=(_<<2)+_|0,_=_+S|0,S=_&8191,_=_>>>13,B+=_,s[0]=S,s[1]=B,s[2]=T,s[3]=q,s[4]=L,s[5]=k,s[6]=z,s[7]=H,s[8]=Z,s[9]=V}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Mr(r)}update(e){sp(this),e=mc(e),it(e);const{buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Mr(this.h,this.r,this.buffer,this.pad)}digestInto(e){sp(this),S8(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function q8(t){const e=(r,i)=>t(i).update(mc(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const z8=q8(t=>new j8(t));function K8(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],h=e[2],d=e[3],p=e[4],g=e[5],y=e[6],I=e[7],D=i,E=n[0],$=n[1],R=n[2],C=o,U=a,N=c,O=u,G=l,W=f,P=h,v=d,m=p,w=g,b=y,x=I,A=D,_=E,S=$,B=R;for(let q=0;q<s;q+=2)C=C+G|0,A=ne(A^C,16),m=m+A|0,G=ne(G^m,12),C=C+G|0,A=ne(A^C,8),m=m+A|0,G=ne(G^m,7),U=U+W|0,_=ne(_^U,16),w=w+_|0,W=ne(W^w,12),U=U+W|0,_=ne(_^U,8),w=w+_|0,W=ne(W^w,7),N=N+P|0,S=ne(S^N,16),b=b+S|0,P=ne(P^b,12),N=N+P|0,S=ne(S^N,8),b=b+S|0,P=ne(P^b,7),O=O+v|0,B=ne(B^O,16),x=x+B|0,v=ne(v^x,12),O=O+v|0,B=ne(B^O,8),x=x+B|0,v=ne(v^x,7),C=C+W|0,B=ne(B^C,16),b=b+B|0,W=ne(W^b,12),C=C+W|0,B=ne(B^C,8),b=b+B|0,W=ne(W^b,7),U=U+P|0,A=ne(A^U,16),x=x+A|0,P=ne(P^x,12),U=U+P|0,A=ne(A^U,8),x=x+A|0,P=ne(P^x,7),N=N+v|0,_=ne(_^N,16),m=m+_|0,v=ne(v^m,12),N=N+v|0,_=ne(_^N,8),m=m+_|0,v=ne(v^m,7),O=O+G|0,S=ne(S^O,16),w=w+S|0,G=ne(G^w,12),O=O+G|0,S=ne(S^O,8),w=w+S|0,G=ne(G^w,7);let T=0;r[T++]=o+C|0,r[T++]=a+U|0,r[T++]=c+N|0,r[T++]=u+O|0,r[T++]=l+G|0,r[T++]=f+W|0,r[T++]=h+P|0,r[T++]=d+v|0,r[T++]=p+m|0,r[T++]=g+w|0,r[T++]=y+b|0,r[T++]=I+x|0,r[T++]=D+A|0,r[T++]=E+_|0,r[T++]=$+S|0,r[T++]=R+B|0}const V8=M8(K8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),H8=new Uint8Array(16),hp=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(H8.subarray(n))},W8=new Uint8Array(32);function fp(t,e,n,r,i){const s=t(e,n,W8),o=z8.create(s);i&&hp(o,i),hp(o,r);const a=P8(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Mr(s,a),c}const G8=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=op(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=fp(t,e,n,a,r);return s.set(c,o),Mr(c),s},decrypt(i,s){s=op(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=fp(t,e,n,o,r);if(!B8(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Mr(c),s}}),dp=T8({blockSize:64,nonceLength:12,tagLength:16},G8(V8));class pp extends Xs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Zs(e);const r=Ct(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),It(s)}update(e){return $n(this),this.iHash.update(e),this}digestInto(e){$n(this),Rt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const no=(t,e,n)=>new pp(t,e).update(n).digest();no.create=(t,e)=>new pp(t,e);function Z8(t,e,n){return Zs(t),n===void 0&&(n=new Uint8Array(t.outputLen)),no(t,Ct(n),Ct(e))}const _c=Uint8Array.from([0]),gp=Uint8Array.of();function Y8(t,e,n,r=32){Zs(t),sn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=gp);const o=new Uint8Array(s*i),a=no.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)_c[0]=l+1,c.update(l===0?gp:u).update(n).update(_c).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),It(u,_c),o.slice(0,r)}const X8=(t,e,n,r,i)=>Y8(t,Z8(t,e,n),r,i),ro=Js,xc=BigInt(0),Ic=BigInt(1);function io(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function lr(t,e,n=""){const r=Gs(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function so(t){const e=t.toString(16);return e.length&1?"0"+e:e}function yp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xc:BigInt("0x"+t)}function oo(t){return yp(Lr(t))}function ao(t){return Rt(t),yp(Lr(Uint8Array.from(t).reverse()))}function Sc(t,e){return Ys(t.toString(16).padStart(e*2,"0"))}function Dc(t,e){return Sc(t,e).reverse()}function qe(t,e,n){let r;if(typeof e=="string")try{r=Ys(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Gs(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Ac=t=>typeof t=="bigint"&&xc<=t;function J8(t,e,n){return Ac(t)&&Ac(e)&&Ac(n)&&e<=t&&t<n}function Oc(t,e,n,r){if(!J8(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function wp(t){let e;for(e=0;t>xc;t>>=Ic,e+=1);return e}const Ri=t=>(Ic<<BigInt(t))-Ic;function Q8(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...h)=>n(o,s,...h),l=(h=r(0))=>{o=u(i(0),h),s=u(),h.length!==0&&(o=u(i(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const d=[];for(;h<e;){s=u();const p=s.slice();d.push(p),h+=s.length}return Tn(...d)};return(h,d)=>{c(),l(h);let p;for(;!(p=d(f()));)l();return c(),p}}function co(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function bp(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const st=BigInt(0),Ye=BigInt(1),hr=BigInt(2),mp=BigInt(3),vp=BigInt(4),Ep=BigInt(5),eI=BigInt(7),_p=BigInt(8),tI=BigInt(9),xp=BigInt(16);function yt(t,e){const n=t%e;return n>=st?n:e+n}function Nt(t,e,n){let r=t;for(;e-- >st;)r*=r,r%=n;return r}function Ip(t,e){if(t===st)throw new Error("invert: expected non-zero number");if(e<=st)throw new Error("invert: expected positive modulus, got "+e);let n=yt(t,e),r=e,i=st,s=Ye;for(;n!==st;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==Ye)throw new Error("invert: does not exist");return yt(i,e)}function $c(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Sp(t,e){const n=(t.ORDER+Ye)/vp,r=t.pow(e,n);return $c(t,r,e),r}function nI(t,e){const n=(t.ORDER-Ep)/_p,r=t.mul(e,hr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,hr),i),a=t.mul(s,t.sub(o,t.ONE));return $c(t,a,e),a}function rI(t){const e=Ln(t),n=Dp(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+eI)/xp;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),y=a.cmov(u,l,g);return $c(a,y,c),y}}function Dp(t){if(t<mp)throw new Error("sqrt is not defined for small field");let e=t-Ye,n=0;for(;e%hr===st;)e/=hr,n++;let r=hr;const i=Ln(t);for(;Op(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Sp;let s=i.pow(r,e);const o=(e+Ye)/hr;return function(a,c){if(a.is0(c))return c;if(Op(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),f=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let d=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(d++,p=a.sqr(p),d===u)throw new Error("Cannot find square root");const g=Ye<<BigInt(u-d-1),y=a.pow(l,g);u=d,l=a.sqr(y),f=a.mul(f,l),h=a.mul(h,y)}return h}}function iI(t){return t%vp===mp?Sp:t%_p===Ep?nI:t%xp===tI?rI(t):Dp(t)}const sI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function oI(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=sI.reduce((r,i)=>(r[i]="function",r),e);return co(t,n),t}function aI(t,e,n){if(n<st)throw new Error("invalid exponent, negatives unsupported");if(n===st)return t.ONE;if(n===Ye)return e;let r=t.ONE,i=e;for(;n>st;)n&Ye&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ye;return r}function Ap(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Op(t,e){const n=(t.ORDER-Ye)/hr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function $p(t,e){e!==void 0&&sn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ln(t,e,n=!1,r={}){if(t<=st)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=$p(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:Ri(c),ZERO:st,ONE:Ye,allowedLengths:a,create:h=>yt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return st<=h&&h<t},is0:h=>h===st,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ye)===Ye,neg:h=>yt(-h,t),eql:(h,d)=>h===d,sqr:h=>yt(h*h,t),add:(h,d)=>yt(h+d,t),sub:(h,d)=>yt(h-d,t),mul:(h,d)=>yt(h*d,t),pow:(h,d)=>aI(f,h,d),div:(h,d)=>yt(h*Ip(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>Ip(h,t),sqrt:s||(h=>(l||(l=iI(t)),l(f,h))),toBytes:h=>n?Dc(h,u):Sc(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=n?ao(h):oo(h);if(o&&(p=yt(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>Ap(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function Bp(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 Tp(t){const e=Bp(t);return e+Math.ceil(e/2)}function cI(t,e,n=!1){const r=t.length,i=Bp(e),s=Tp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ao(t):oo(t),a=yt(o,e-Ye)+Ye;return n?Dc(a,i):Sc(a,i)}const jr=BigInt(0),fr=BigInt(1);function uo(t,e){const n=e.negate();return t?n:e}function Bc(t,e){const n=Ap(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Pp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Tc(t,e){Pp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Ri(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Rp(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=fr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function uI(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function lI(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Pc=new WeakMap,Cp=new WeakMap;function Rc(t){return Cp.get(t)||1}function Np(t){if(t!==jr)throw new Error("invalid wNAF")}class hI{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>jr;)n&fr&&(r=r.add(i)),i=i.double(),n>>=fr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=Tc(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=Tc(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=Rp(r,a,o);r=c,l?s=s.add(uo(h,n[d])):i=i.add(uo(f,n[u]))}return Np(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=Tc(e,this.bits);for(let o=0;o<s.windows&&r!==jr;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Rp(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return Np(r),i}getPrecomputes(e,n,r){let i=Pc.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Pc.set(n,i))),i}cached(e,n,r){const i=Rc(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Rc(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Pp(n,this.bits),Cp.set(e,n),Pc.delete(e)}hasCache(e){return Rc(e)!==1}}function fI(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>jr||r>jr;)n&fr&&(s=s.add(i)),r&fr&&(o=o.add(i)),i=i.double(),n>>=fr,r>>=fr;return{p1:s,p2:o}}function dI(t,e,n,r){uI(n,t),lI(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=wp(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Ri(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],I=Number(y>>BigInt(d)&u);l[I]=l[I].add(n[g])}let p=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),p=p.add(y);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function Up(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return oI(e),e}else return Ln(t,{isLE:n})}function pI(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>jr))throw new Error(`CURVE.${a} must be positive bigint`)}const i=Up(e.p,n.Fp,r),s=Up(e.n,n.Fn,r),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Ld("HashToScalar-");const Ci=BigInt(0),qr=BigInt(1),lo=BigInt(2);function gI(t){return co(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(Ur({},t))}function yI(t){const e=gI(t),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||cr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),h=BigInt(a?121665:39081),d=a?lo**BigInt(254):lo**BigInt(447),p=a?BigInt(8)*lo**BigInt(251)-qr:BigInt(4)*lo**BigInt(445)-qr,g=d+p+qr,y=P=>yt(P,n),I=D(f);function D(P){return Dc(y(P),l)}function E(P){const v=qe("u coordinate",P,l);return a&&(v[31]&=127),y(ao(v))}function $(P){return ao(i(qe("scalar",P,l)))}function R(P,v){const m=N(E(v),$(P));if(m===Ci)throw new Error("invalid private or public key received");return D(m)}function C(P){return R(P,I)}function U(P,v,m){const w=y(P*(v-m));return v=y(v-w),m=y(m+w),{x_2:v,x_3:m}}function N(P,v){Oc("u",P,Ci,n),Oc("scalar",v,d,g);const m=v,w=P;let b=qr,x=Ci,A=P,_=qr,S=Ci;for(let T=BigInt(u-1);T>=Ci;T--){const q=m>>T&qr;S^=q,{x_2:b,x_3:A}=U(S,b,A),{x_2:x,x_3:_}=U(S,x,_),S=q;const L=b+x,k=y(L*L),z=b-x,H=y(z*z),Z=k-H,V=A+_,Y=A-_,he=y(Y*L),Ve=y(V*z),mt=he+Ve,gn=he-Ve;A=y(mt*mt),_=y(w*y(gn*gn)),b=y(k*H),x=y(Z*(k+y(h*Z)))}({x_2:b,x_3:A}=U(S,b,A)),{x_2:x,x_3:_}=U(S,x,_);const B=s(x);return y(b*B)}const O={secretKey:l,publicKey:l,seed:l},G=(P=c(l))=>(Rt(P,O.seed),P);function W(P){const v=G(P);return{secretKey:v,publicKey:C(v)}}return{keygen:W,getSharedSecret:(P,v)=>R(P,v),getPublicKey:P=>C(P),scalarMult:R,scalarMultBase:C,utils:{randomSecretKey:G,randomPrivateKey:G},GuBytes:I.slice(),lengths:O}}const wI=BigInt(1),Fp=BigInt(2),bI=BigInt(3),mI=BigInt(5),vI=BigInt(8),kp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),EI={p:kp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:vI,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function _I(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=kp,o=t*t%s*t%s,a=Nt(o,Fp,s)*o%s,c=Nt(a,wI,s)*t%s,u=Nt(c,mI,s)*c%s,l=Nt(u,e,s)*u%s,f=Nt(l,n,s)*l%s,h=Nt(f,r,s)*f%s,d=Nt(h,i,s)*h%s,p=Nt(d,i,s)*h%s,g=Nt(p,e,s)*u%s;return{pow_p_5_8:Nt(g,Fp,s)*t%s,b2:o}}function xI(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const II=Ln(EI.p,{isLE:!0}),Cc=(()=>{const t=II.ORDER;return yI({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=_I(e);return yt(Nt(n,bI,t)*r,t)},adjustScalarBytes:xI})})(),Lp=(t,e)=>(t+(t>=0?e:-e)/Mp)/e;function SI(t,e,n){const[[r,i],[s,o]]=e,a=Lp(o*t,n),c=Lp(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<un,h=l<un;f&&(u=-u),h&&(l=-l);const d=Ri(Math.ceil(wp(n)/2))+zr;if(u<un||u>=d||l<un||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Nc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Uc(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return io(n.lowS,"lowS"),io(n.prehash,"prehash"),n.format!==void 0&&Nc(n.format),n}class DI extends Error{constructor(e=""){super(e)}}const cn={Err:DI,_tlv:{encode:(t,e)=>{const{Err:n}=cn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=so(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?so(i.length/2|128):"";return so(t)+s+i+e},decode(t,e){const{Err:n}=cn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=cn;if(t<un)throw new e("integer: negative integers are not allowed");let n=so(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=cn;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 oo(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=cn,i=qe("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=cn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},un=BigInt(0),zr=BigInt(1),Mp=BigInt(2),ho=BigInt(3),AI=BigInt(4);function Kr(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=qe("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function OI(t,e={}){const n=pI("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;co(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=qp(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:w,y:b}=v.toAffine(),x=r.toBytes(w);if(io(m,"isCompressed"),m){l();const A=!r.isOdd(b);return Tn(jp(A),x)}else return Tn(Uint8Array.of(4),x,r.toBytes(b))}function h(P){lr(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,w=P.length,b=P[0],x=P.subarray(1);if(w===v&&(b===2||b===3)){const A=r.fromBytes(x);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const _=g(A);let S;try{S=r.sqrt(_)}catch(T){const q=T instanceof Error?": "+T.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}l();const B=r.isOdd(S);return(b&1)===1!==B&&(S=r.neg(S)),{x:A,y:S}}else if(w===m&&b===4){const A=r.BYTES,_=r.fromBytes(x.subarray(0,A)),S=r.fromBytes(x.subarray(A,A*2));if(!y(_,S))throw new Error("bad point: is not on curve");return{x:_,y:S}}else throw new Error(`bad point: got length ${w}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=r.sqr(P),m=r.mul(v,P);return r.add(r.add(m,r.mul(P,s.a)),s.b)}function y(P,v){const m=r.sqr(v),w=g(P);return r.eql(m,w)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=r.mul(r.pow(s.a,ho),AI),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(I,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!r.isValid(v)||m&&r.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function $(P){if(!(P instanceof O))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return SI(P,c.basises,i.ORDER)}const C=bp((P,v)=>{const{X:m,Y:w,Z:b}=P;if(r.eql(b,r.ONE))return{x:m,y:w};const x=P.is0();v==null&&(v=x?r.ONE:r.inv(b));const A=r.mul(m,v),_=r.mul(w,v),S=r.mul(b,v);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),U=bp(P=>{if(P.is0()){if(e.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!r.isValid(v)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,w,b){return m=new O(r.mul(m.X,P),m.Y,m.Z),v=uo(w,v),m=uo(b,m),v.add(m)}class O{constructor(v,m,w){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",w),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y:w}=v||{};if(!v||!r.isValid(m)||!r.isValid(w))throw new Error("invalid affine point");if(v instanceof O)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(w)?O.ZERO:new O(m,w,r.ONE)}static fromBytes(v){const m=O.fromAffine(p(lr(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return O.fromBytes(qe("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(ho),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v,S=r.eql(r.mul(m,_),r.mul(x,b)),B=r.eql(r.mul(w,_),r.mul(A,b));return S&&B}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,w=r.mul(m,ho),{X:b,Y:x,Z:A}=this;let _=r.ZERO,S=r.ZERO,B=r.ZERO,T=r.mul(b,b),q=r.mul(x,x),L=r.mul(A,A),k=r.mul(b,x);return k=r.add(k,k),B=r.mul(b,A),B=r.add(B,B),_=r.mul(v,B),S=r.mul(w,L),S=r.add(_,S),_=r.sub(q,S),S=r.add(q,S),S=r.mul(_,S),_=r.mul(k,_),B=r.mul(w,B),L=r.mul(v,L),k=r.sub(T,L),k=r.mul(v,k),k=r.add(k,B),B=r.add(T,T),T=r.add(B,T),T=r.add(T,L),T=r.mul(T,k),S=r.add(S,T),L=r.mul(x,A),L=r.add(L,L),T=r.mul(L,k),_=r.sub(_,T),B=r.mul(L,q),B=r.add(B,B),B=r.add(B,B),new O(_,S,B)}add(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v;let S=r.ZERO,B=r.ZERO,T=r.ZERO;const q=s.a,L=r.mul(s.b,ho);let k=r.mul(m,x),z=r.mul(w,A),H=r.mul(b,_),Z=r.add(m,w),V=r.add(x,A);Z=r.mul(Z,V),V=r.add(k,z),Z=r.sub(Z,V),V=r.add(m,b);let Y=r.add(x,_);return V=r.mul(V,Y),Y=r.add(k,H),V=r.sub(V,Y),Y=r.add(w,b),S=r.add(A,_),Y=r.mul(Y,S),S=r.add(z,H),Y=r.sub(Y,S),T=r.mul(q,V),S=r.mul(L,H),T=r.add(S,T),S=r.sub(z,T),T=r.add(z,T),B=r.mul(S,T),z=r.add(k,k),z=r.add(z,k),H=r.mul(q,H),V=r.mul(L,V),z=r.add(z,H),H=r.sub(k,H),H=r.mul(q,H),V=r.add(V,H),k=r.mul(z,V),B=r.add(B,k),k=r.mul(Y,V),S=r.mul(Z,S),S=r.sub(S,k),k=r.mul(Z,z),T=r.mul(Y,T),T=r.add(T,k),new O(S,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals(O.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let w,b;const x=A=>W.cached(this,A,_=>Bc(O,_));if(m){const{k1neg:A,k1:_,k2neg:S,k2:B}=R(v),{p:T,f:q}=x(_),{p:L,f:k}=x(B);b=q.add(k),w=N(m.beta,T,L,A,S)}else{const{p:A,f:_}=x(v);w=A,b=_}return Bc(O,[w,b])[0]}multiplyUnsafe(v){const{endo:m}=e,w=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===un||w.is0())return O.ZERO;if(v===zr)return w;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:x,k2neg:A,k2:_}=R(v),{p1:S,p2:B}=fI(O,w,x,_);return N(m.beta,S,B,b,A)}else return W.unsafe(w,v)}multiplyAndAddUnsafe(v,m,w){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(w));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===zr?!0:v?v(O,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===zr?this:v?v(O,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return io(v,"isCompressed"),this.assertValidity(),d(O,this,v)}toHex(v=!0){return Lr(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return Bc(O,v)}static msm(v,m){return dI(O,i,v,m)}static fromPrivateKey(v){return O.BASE.multiply(Kr(i,v))}}O.BASE=new O(s.Gx,s.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=i;const G=i.BITS,W=new hI(O,e.endo?Math.ceil(G/2):G);return O.BASE.precompute(8),O}function jp(t){return Uint8Array.of(t?2:3)}function qp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function $I(t,e={}){const{Fn:n}=t,r=e.randomBytes||cr,i=Object.assign(qp(t.Fp,n),{seed:Tp(n.ORDER)});function s(h){try{return!!Kr(n,h)}catch{return!1}}function o(h,d){const{publicKey:p,publicKeyUncompressed:g}=i;try{const y=h.length;return d===!0&&y!==p||d===!1&&y!==g?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return cI(lr(h,i.seed,"seed"),n.ORDER)}function c(h,d=!0){return t.BASE.multiply(Kr(n,h)).toBytes(d)}function u(h){const d=a(h);return{secretKey:d,publicKey:c(d)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:d,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||d===p)return;const y=qe("key",h).length;return y===p||y===g}function f(h,d,p=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");const g=Kr(n,h);return t.fromHex(d).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>Kr(n,h),precompute(h=8,d=t.BASE){return d.precompute(h,!1)}},lengths:i})}function BI(t,e,n={}){Zs(e),co(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||cr,i=n.hmac||((m,...w)=>no(e,m,Tn(...w))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=$I(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(m){const w=a>>zr;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function D(m,w){Nc(w);const b=d.signature,x=w==="compact"?b:w==="recovered"?b+1:void 0;return lr(m,x,`${w} signature`)}class E{constructor(w,b,x){this.r=I("r",w),this.s=I("s",b),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(w,b=g){D(w,b);let x;if(b==="der"){const{r:B,s:T}=cn.toSig(lr(w));return new E(B,T)}b==="recovered"&&(x=w[0],b="compact",w=w.subarray(1));const A=o.BYTES,_=w.subarray(0,A),S=w.subarray(A,A*2);return new E(o.fromBytes(_),o.fromBytes(S),x)}static fromHex(w,b){return this.fromBytes(Ys(w),b)}addRecoveryBit(w){return new E(this.r,this.s,w)}recoverPublicKey(w){const b=s.ORDER,{r:x,s:A,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*Mp<b&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=_===2||_===3?x+a:x;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(S),T=t.fromBytes(Tn(jp((_&1)===0),B)),q=o.inv(S),L=R(qe("msgHash",w)),k=o.create(-L*q),z=o.create(A*q),H=t.BASE.multiplyUnsafe(k).add(T.multiplyUnsafe(z));if(H.is0())throw new Error("point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(w=g){if(Nc(w),w==="der")return Ys(cn.hexFromSig(this));const b=o.toBytes(this.r),x=o.toBytes(this.s);if(w==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Tn(Uint8Array.of(this.recovery),b,x)}return Tn(b,x)}toHex(w){return Lr(this.toBytes(w))}assertValidity(){}static fromCompact(w){return E.fromBytes(qe("sig",w),"compact")}static fromDER(w){return E.fromBytes(qe("sig",w),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Lr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Lr(this.toBytes("compact"))}}const $=n.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const w=oo(m),b=m.length*8-c;return b>0?w>>BigInt(b):w},R=n.bits2int_modN||function(m){return o.create($(m))},C=Ri(c);function U(m){return Oc("num < 2^"+c,m,un,C),o.toBytes(m)}function N(m,w){return lr(m,void 0,"message"),w?lr(e(m),void 0,"prehashed message"):m}function O(m,w,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:A,extraEntropy:_}=Uc(b,p);m=N(m,A);const S=R(m),B=Kr(o,w),T=[U(B),U(S)];if(_!=null&&_!==!1){const z=_===!0?r(d.secretKey):_;T.push(qe("extraEntropy",z))}const q=Tn(...T),L=S;function k(z){const H=$(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===un)return;const he=o.create(Z*o.create(L+Y*B));if(he===un)return;let Ve=(V.x===Y?0:2)|Number(V.y&zr),mt=he;return x&&y(he)&&(mt=o.neg(he),Ve^=1),new E(Y,mt,Ve)}return{seed:q,k2sig:k}}function G(m,w,b={}){m=qe("message",m);const{seed:x,k2sig:A}=O(m,w,b);return Q8(e.outputLen,o.BYTES,i)(x,A)}function W(m){let w;const b=typeof m=="string"||Gs(m),x=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)w=new E(m.r,m.s);else if(b){try{w=E.fromBytes(qe("sig",m),"der")}catch(A){if(!(A instanceof cn.Err))throw A}if(!w)try{w=E.fromBytes(qe("sig",m),"compact")}catch{return!1}}return w||!1}function P(m,w,b,x={}){const{lowS:A,prehash:_,format:S}=Uc(x,p);if(b=qe("publicKey",b),w=N(qe("message",w),_),"strict"in x)throw new Error("options.strict was renamed to lowS");const B=S===void 0?W(m):E.fromBytes(qe("sig",m),S);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:q,s:L}=B,k=R(w),z=o.inv(L),H=o.create(k*z),Z=o.create(q*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===q}catch{return!1}}function v(m,w,b={}){const{prehash:x}=Uc(b,p);return w=N(w,x),E.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function TI(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=Ln(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function PI(t){const{CURVE:e,curveOpts:n}=TI(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,hash:t.hash,ecdsaOpts:r}}function RI(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,$p(n.Fn.ORDER,n.Fn.BITS))})}function CI(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=PI(t),s=OI(e,n),o=BI(s,r,i);return RI(t,o)}function Fc(t,e){const n=r=>CI(Si(Ur({},t),{hash:r}));return Si(Ur({},n(e)),{create:n})}const zp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},Kp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Vp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},NI=Ln(zp.p),UI=Ln(Kp.p),FI=Ln(Vp.p),kI=Fc(Si(Ur({},zp),{Fp:NI,lowS:!1}),Js);Fc(Si(Ur({},Kp),{Fp:UI,lowS:!1}),Kx),Fc(Si(Ur({},Vp),{Fp:FI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),zx);const LI=kI,Hp="base10",Xe="base16",ot="base64pad",Mn="base64url",Ni="utf8",Wp=0,ln=1,Ui=2,MI=0,Gp=1,Fi=12,kc=32;function jI(){const t=Cc.utils.randomPrivateKey(),e=Cc.getPublicKey(t);return{privateKey:rt(t,Xe),publicKey:rt(e,Xe)}}function Lc(){const t=cr(kc);return rt(t,Xe)}function qI(t,e){const n=Cc.getSharedSecret(xt(t,Xe),xt(e,Xe)),r=X8(ro,n,void 0,void 0,kc);return rt(r,Xe)}function fo(t){const e=ro(xt(t,Xe));return rt(e,Xe)}function St(t){const e=ro(xt(t,Ni));return rt(e,Xe)}function Zp(t){return xt(`${t}`,Hp)}function dr(t){return Number(rt(t,Hp))}function Yp(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Xp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function zI(t){const e=Zp(typeof t.type<"u"?t.type:Wp);if(dr(e)===ln&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?xt(t.senderPublicKey,Xe):void 0,r=typeof t.iv<"u"?xt(t.iv,Xe):cr(Fi),i=xt(t.symKey,Xe),s=dp(i,r).encrypt(xt(t.message,Ni)),o=Jp({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===Mn?Yp(o):o}function KI(t){const e=xt(t.symKey,Xe),{sealed:n,iv:r}=ki({encoded:t.encoded,encoding:t.encoding}),i=dp(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return rt(i,Ni)}function VI(t,e){const n=Zp(Ui),r=cr(Fi),i=xt(t,Ni),s=Jp({type:n,sealed:i,iv:r});return e===Mn?Yp(s):s}function HI(t,e){const{sealed:n}=ki({encoded:t,encoding:e});return rt(n,Ni)}function Jp(t){if(dr(t.type)===Ui)return rt(vi([t.type,t.sealed]),ot);if(dr(t.type)===ln){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return rt(vi([t.type,t.senderPublicKey,t.iv,t.sealed]),ot)}return rt(vi([t.type,t.iv,t.sealed]),ot)}function ki(t){const e=(t.encoding||ot)===Mn?Xp(t.encoded):t.encoded,n=xt(e,ot),r=n.slice(MI,Gp),i=Gp;if(dr(r)===ln){const c=i+kc,u=c+Fi,l=n.slice(i,c),f=n.slice(c,u),h=n.slice(u);return{type:r,sealed:h,iv:f,senderPublicKey:l}}if(dr(r)===Ui){const c=n.slice(i),u=cr(Fi);return{type:r,sealed:c,iv:u}}const s=i+Fi,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function WI(t,e){const n=ki({encoded:t,encoding:e?.encoding});return Qp({type:dr(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?rt(n.senderPublicKey,Xe):void 0,receiverPublicKey:e?.receiverPublicKey})}function Qp(t){const e=t?.type||Wp;if(e===ln){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 eg(t){return t.type===ln&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function tg(t){return t.type===Ui}function GI(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return vi([new Uint8Array([4]),e,n])}function ZI(t,e){const[n,r,i]=t.split("."),s=Buffer.from(Xp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,u=ro(c),l=GI(e);if(!LI.verify(vi([o,a]),u,l))throw new Error("Invalid signature");return oa(t).payload}const YI="irn";function po(t){return t?.relay||{protocol:YI}}function Vr(t){const e=v_[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var XI=Object.defineProperty,JI=Object.defineProperties,QI=Object.getOwnPropertyDescriptors,ng=Object.getOwnPropertySymbols,eS=Object.prototype.hasOwnProperty,tS=Object.prototype.propertyIsEnumerable,rg=(t,e,n)=>e in t?XI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Mc=(t,e)=>{for(var n in e||(e={}))eS.call(e,n)&&rg(t,n,e[n]);if(ng)for(var n of ng(e))tS.call(e,n)&&rg(t,n,e[n]);return t},nS=(t,e)=>JI(t,QI(e));function rS(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=t[i];n[s]=o}}),n}function ig(t){if(!t.includes("wc:")){const u=$d(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,n).split("@"),s=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:iS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:rS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function iS(t){return t.startsWith("//")?t.substring(2):t}function sS(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(i=>{const s=i,o=n+e+s;t[s]&&(r[o]=t[s])}),r}function sg(t){const e=new URLSearchParams,n=Mc(Mc(nS(Mc({},sS(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(n).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!==void 0&&e.append(r,String(i))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function go(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var oS=Object.defineProperty,aS=Object.defineProperties,cS=Object.getOwnPropertyDescriptors,og=Object.getOwnPropertySymbols,uS=Object.prototype.hasOwnProperty,lS=Object.prototype.propertyIsEnumerable,ag=(t,e,n)=>e in t?oS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,hS=(t,e)=>{for(var n in e||(e={}))uS.call(e,n)&&ag(t,n,e[n]);if(og)for(var n of og(e))lS.call(e,n)&&ag(t,n,e[n]);return t},fS=(t,e)=>aS(t,cS(e));function Hr(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function dS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Hr(n.accounts))}),e}function pS(t,e){const n=[];return Object.values(t).forEach(r=>{Hr(r.accounts).includes(e)&&n.push(...r.methods)}),n}function gS(t,e){const n=[];return Object.values(t).forEach(r=>{Hr(r.accounts).includes(e)&&n.push(...r.events)}),n}function cg(t){return t.includes(":")}function yS(t){return cg(t)?t.split(":")[0]:t}function ug(t){var e,n,r;const i={};if(!Li(t))return i;for(const[s,o]of Object.entries(t)){const a=cg(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=yS(s);i[l]=fS(hS({},i[l]),{chains:ar(a,(e=i[l])==null?void 0:e.chains),methods:ar(c,(n=i[l])==null?void 0:n.methods),events:ar(u,(r=i[l])==null?void 0:r.events)})}return i}function wS(t){const e={};return t?.forEach(n=>{var r;const[i,s]=n.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(n),(r=e[i].chains)==null||r.push(`${i}:${s}`)}),e}function lg(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=wS(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=ar(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function bS(t,e){var n,r,i,s,o,a;const c=ug(t),u=ug(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const h of f)l[h]={chains:ar((n=c[h])==null?void 0:n.chains,(r=u[h])==null?void 0:r.chains),methods:ar((i=c[h])==null?void 0:i.methods,(s=u[h])==null?void 0:s.methods),events:ar((o=c[h])==null?void 0:o.events,(a=u[h])==null?void 0:a.events)};return l}const mS={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}},vS={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 j(t,e){const{message:n,code:r}=vS[t];return{message:e?`${n} ${e}`:n,code:r}}function fe(t,e){const{message:n,code:r}=mS[t];return{message:e?`${n} ${e}`:n,code:r}}function Wr(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Li(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function ye(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function jc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function ES(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return sr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Hr(a),f=n[o];(!sr(bd(o,f),l)||!sr(f.methods,c)||!sr(f.events,u))&&(s=!1)}),s):!1}function Mi(t){return ye(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function _S(t){if(ye(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Mi(n)}}return!1}function xS(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(ye(t,!1)){if(e(t))return!0;const n=$d(t);return e(n)}}catch{}return!1}function IS(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function SS(t){return t?.topic}function DS(t,e){let n=null;return ye(t?.publicKey,!1)||(n=j("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function hg(t){let e=!0;return Wr(t)?t.length&&(e=t.every(n=>ye(n,!1))):e=!1,e}function AS(t,e,n){let r=null;return Wr(e)&&e.length?e.forEach(i=>{r||Mi(i)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Mi(t)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function OS(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=AS(i,bd(i,s),`${e} ${n}`);o&&(r=o)}),r}function $S(t,e){let n=null;return Wr(t)?t.forEach(r=>{n||_S(r)||(n=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function BS(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=$S(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function TS(t,e){let n=null;return hg(t?.methods)?hg(t?.events)||(n=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function fg(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=TS(r,`${e}, namespace`);i&&(n=i)}),n}function PS(t,e,n){let r=null;if(t&&Li(t)){const i=fg(t,e);i&&(r=i);const s=OS(t,e,n);s&&(r=s)}else r=j("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function qc(t,e){let n=null;if(t&&Li(t)){const r=fg(t,e);r&&(n=r);const i=BS(t,e);i&&(n=i)}else n=j("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function dg(t){return ye(t.protocol,!0)}function RS(t,e){let n=!1;return e&&!t?n=!0:t&&Wr(t)&&t.length&&t.forEach(r=>{n=dg(r)}),n}function CS(t){return typeof t=="number"}function at(t){return typeof t<"u"&&typeof t!==null}function NS(t){return!(!t||typeof t!="object"||!t.code||!jc(t.code,!1)||!t.message||!ye(t.message,!1))}function US(t){return!(_e(t)||!ye(t.method,!1))}function FS(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!jc(t.id,!1)||!ye(t.jsonrpc,!1))}function kS(t){return!(_e(t)||!ye(t.name,!1))}function pg(t,e){return!(!Mi(e)||!dS(t).includes(e))}function LS(t,e,n){return ye(n,!1)?pS(t,e).includes(n):!1}function MS(t,e,n){return ye(n,!1)?gS(t,e).includes(n):!1}function gg(t,e,n){let r=null;const i=jS(t),s=qS(e),o=Object.keys(i),a=Object.keys(s),c=yg(Object.keys(t)),u=yg(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
14
+ ***************************************************************************** */var mo=function(t,e){return mo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},mo(t,e)};function y0(t,e){mo(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var bo=function(){return bo=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},bo.apply(this,arguments)};function w0(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function m0(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function b0(t,e){return function(n,r){e(n,r,t)}}function v0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function E0(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function x0(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function _0(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function I0(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function vo(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $u(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function S0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($u(arguments[e]));return t}function A0(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Mr(t){return this instanceof Mr?(this.v=t,this):new Mr(t)}function D0(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){r[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Mr?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function O0(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Mr(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function $0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof vo=="function"?vo(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function T0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function B0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function P0(t){return t&&t.__esModule?t:{default:t}}function C0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function R0(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var N0=Object.freeze({__proto__:null,__extends:y0,get __assign(){return bo},__rest:w0,__decorate:m0,__param:b0,__metadata:v0,__awaiter:E0,__generator:x0,__createBinding:_0,__exportStar:I0,__values:vo,__read:$u,__spread:S0,__spreadArrays:A0,__await:Mr,__asyncGenerator:D0,__asyncDelegator:O0,__asyncValues:$0,__makeTemplateObject:T0,__importStar:B0,__importDefault:P0,__classPrivateFieldGet:C0,__classPrivateFieldSet:R0}),Xi=fu(N0),Eo={},zr={},Tu;function U0(){if(Tu)return zr;Tu=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return zr.delay=t,zr}var zn={},xo={},qn={},Bu;function F0(){return Bu||(Bu=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.ONE_THOUSAND=qn.ONE_HUNDRED=void 0,qn.ONE_HUNDRED=100,qn.ONE_THOUSAND=1e3),qn}var _o={},Pu;function k0(){return Pu||(Pu=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}(_o)),_o}var Cu;function Ru(){return Cu||(Cu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(F0(),t),e.__exportStar(k0(),t)}(xo)),xo}var Nu;function L0(){if(Nu)return zn;Nu=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.fromMiliseconds=zn.toMiliseconds=void 0;const t=Ru();function e(r){return r*t.ONE_THOUSAND}zn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return zn.fromMiliseconds=n,zn}var Uu;function M0(){return Uu||(Uu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(U0(),t),e.__exportStar(L0(),t)}(Eo)),Eo}var pr={},Fu;function z0(){if(Fu)return pr;Fu=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const i=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:i})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return pr.Watch=t,pr.default=t,pr}var Io={},qr={},ku;function q0(){if(ku)return qr;ku=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.IWatch=void 0;class t{}return qr.IWatch=t,qr}var Lu;function j0(){return Lu||(Lu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Xi.__exportStar(q0(),t)}(Io)),Io}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(M0(),t),e.__exportStar(z0(),t),e.__exportStar(j0(),t),e.__exportStar(Ru(),t)})(M);class jn{}class V0 extends jn{constructor(e){super()}}const Mu=M.FIVE_SECONDS,Vn={pulse:"heartbeat_pulse"};class So extends V0{constructor(e){super(e),this.events=new Ve.exports.EventEmitter,this.interval=Mu,this.interval=e?.interval||Mu}static async init(e){const n=new So(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(Vn.pulse)}}const K0=/"(?:_|\\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*:/,H0=/"(?: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*:/,W0=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function G0(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Y0(t);return}return e}function Y0(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Qi(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const n=t.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!W0.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(K0.test(t)||H0.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,G0)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Z0(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ie(t,...e){try{return Z0(t(...e))}catch(n){return Promise.reject(n)}}function J0(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function X0(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function es(t){if(J0(t))return String(t);if(X0(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return es(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ao="base64:";function Q0(t){return typeof t=="string"?t:Ao+ny(t)}function ey(t){return typeof t!="string"||!t.startsWith(Ao)?t:ty(t.slice(Ao.length))}function ty(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function ny(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ze(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function ry(...t){return Ze(t.join(":"))}function ts(t){return t=Ze(t),t?t+":":""}function iy(t,e){if(e===void 0)return!0;let n=0,r=t.indexOf(":");for(;r>-1;)n++,r=t.indexOf(":",r+1);return n<=e}function sy(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function C5(t){return t}const oy="memory",ay=()=>{const t=new Map;return{name:oy,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,n){t.set(e,n)},setItemRaw(e,n){t.set(e,n)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function cy(t={}){const e={mounts:{"":t.driver||ay()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},r=(u,l)=>e.mountpoints.filter(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=Ze(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 zu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,p=d=>{let g=f.get(d.base);return g||(g={driver:d.driver,base:d.base,items:[]},f.set(d.base,g)),g};for(const d of u){const g=typeof d=="string",y=Ze(g?d:d.key),_=g?void 0:d.value,A=g||!d.options?l:{...l,...d.options},b=n(y);p(b).items.push({key:y,value:_,relativeKey:b.relativeKey,options:A})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return Ie(f.hasItem,h,l)},getItem(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return Ie(f.getItem,h,l).then(p=>Qi(p))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Ie(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:ry(h.base,p.key),value:Qi(p.value)}))):Promise.all(h.items.map(f=>Ie(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:Qi(p)})))))},getItemRaw(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return f.getItemRaw?Ie(f.getItemRaw,h,l):Ie(f.getItem,h,l).then(p=>ey(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ze(u);const{relativeKey:f,driver:p}=n(u);p.setItem&&(await Ie(p.setItem,f,es(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Ie(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:es(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Ie(h.driver.setItem,f.relativeKey,es(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ze(u);const{relativeKey:f,driver:p}=n(u);if(p.setItemRaw)await Ie(p.setItemRaw,f,l,h);else if(p.setItem)await Ie(p.setItem,f,Q0(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ze(u);const{relativeKey:h,driver:f}=n(u);f.removeItem&&(await Ie(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Ie(f.removeItem,h+"$",l),f.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ze(u);const{relativeKey:h,driver:f}=n(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await Ie(f.getMeta,h,l)),!l.nativeOnly){const d=await Ie(f.getItem,h+"$",l).then(g=>Qi(g));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=ts(u);const h=r(u,!0);let f=[];const p=[];let d=!0;for(const y of h){y.driver.flags?.maxDepth||(d=!1);const _=await Ie(y.driver.getKeys,y.relativeBase,l);for(const A of _){const b=y.mountpoint+Ze(A);f.some(v=>b.startsWith(v))||p.push(b)}f=[y.mountpoint,...f.filter(A=>!A.startsWith(y.mountpoint))]}const g=l.maxDepth!==void 0&&!d;return p.filter(y=>(!g||iy(y,l.maxDepth))&&sy(y,u))},async clear(u,l={}){u=ts(u),await Promise.all(r(u,!1).map(async h=>{if(h.driver.clear)return Ie(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>qu(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=ts(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(zu(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=ts(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await qu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ze(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ze(u),r(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function zu(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function qu(t){typeof t.dispose=="function"&&await Ie(t.dispose)}function Kn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function ju(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Kn(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let Do;function jr(){return Do||(Do=ju("keyval-store","keyval")),Do}function Vu(t,e=jr()){return e("readonly",n=>Kn(n.get(t)))}function uy(t,e,n=jr()){return n("readwrite",r=>(r.put(e,t),Kn(r.transaction)))}function ly(t,e=jr()){return e("readwrite",n=>(n.delete(t),Kn(n.transaction)))}function hy(t=jr()){return t("readwrite",e=>(e.clear(),Kn(e.transaction)))}function fy(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Kn(t.transaction)}function dy(t=jr()){return t("readonly",e=>{if(e.getAllKeys)return Kn(e.getAllKeys());const n=[];return fy(e,r=>n.push(r.key)).then(()=>n)})}const py=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),gy=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function gr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return gy(t)}catch{return t}}function Hn(t){return typeof t=="string"?t:py(t)||""}const yy="idb-keyval";var wy=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=ju(t.dbName,t.storeName)),{name:yy,options:t,async hasItem(i){return!(typeof await Vu(n(i),r)>"u")},async getItem(i){return await Vu(n(i),r)??null},setItem(i,s){return uy(n(i),s,r)},removeItem(i){return ly(n(i),r)},getKeys(){return dy(r)},clear(){return hy(r)}}};const my="WALLET_CONNECT_V2_INDEXED_DB",by="keyvaluestorage";class vy{constructor(){this.indexedDb=cy({driver:wy({dbName:my,storeName:by})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Hn(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ns={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Oo<"u"&&Oo.localStorage?ns.exports=Oo.localStorage:typeof window<"u"&&window.localStorage?ns.exports=window.localStorage:ns.exports=new e})();function Ey(t){var e;return[t[0],gr((e=t[1])!=null?e:"")]}class xy{constructor(){this.localStorage=ns.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Ey)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return gr(n)}async setItem(e,n){this.localStorage.setItem(e,Hn(n))}async removeItem(e){this.localStorage.removeItem(e)}}const _y="wc_storage_version",Ku=1,Iy=async(t,e,n)=>{const r=_y,i=await e.getItem(r);if(i&&i>=Ku){n(e);return}const s=await t.getKeys();if(!s.length){n(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(r,Ku),n(e),Sy(t,o)},Sy=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class Ay{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new xy;this.storage=e;try{const n=new vy;Iy(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}function Dy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Oy=$y;function $y(t,e,n){var r=n&&n.stringify||Dy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=r(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const Hu=Oy;var kt=Lt;const Vr=Ly().console||{},Ty={mapHttpRequest:is,mapHttpResponse:is,wrapRequestSerializer:To,wrapResponseSerializer:To,wrapErrorSerializer:To,req:is,res:is,err:Ny};function By(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Lt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const n=t.browser.write||Vr;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=By(t.browser.serialize,r);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=Kr),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:f});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:Uy(t)};c.levels=Lt.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=Kr,c.serializers=r,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=$o());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,yr(u,c,"error","log"),yr(u,c,"fatal","error"),yr(u,c,"warn","error"),yr(u,c,"info","log"),yr(u,c,"debug","log"),yr(u,c,"trace","log")}function p(d,g){if(!d)throw new Error("missing bindings for child Pino");g=g||{},i&&d.serializers&&(g.serializers=d.serializers);const y=g.serializers;if(i&&y){var _=Object.assign({},r,y),A=t.browser.serialize===!0?Object.keys(_):i;delete d.serializers,rs([d],A,_,this._stdErrSerialize)}function b(v){this._childLevel=(v._childLevel|0)+1,this.error=wr(v,d,"error"),this.fatal=wr(v,d,"fatal"),this.warn=wr(v,d,"warn"),this.info=wr(v,d,"info"),this.debug=wr(v,d,"debug"),this.trace=wr(v,d,"trace"),_&&(this.serializers=_,this._serialize=A),e&&(this._logEvent=$o([].concat(v._logEvent.bindings,d)))}return b.prototype=this,new b(this)}return c}Lt.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"}},Lt.stdSerializers=Ty,Lt.stdTimeFunctions=Object.assign({},{nullTime:Wu,epochTime:Gu,unixTime:Fy,isoTime:ky});function yr(t,e,n,r){const i=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?Kr:i[n]?i[n]:Vr[n]||Vr[r]||Kr,Py(t,e,n)}function Py(t,e,n){!t.transmit&&e[n]===Kr||(e[n]=function(r){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Vr?Vr:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&rs(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,Cy(this,n,o,s)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Lt.levels.values[u],h=Lt.levels.values[n];if(h<l)return;Ry(this,{ts:s,methodLevel:n,methodValue:h,transmitLevel:u,transmitValue:Lt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[n]))}function Cy(t,e,n,r){t._serialize&&rs(n,t._serialize,t.serializers,t._stdErrSerialize);const i=n.slice();let s=i[0];const o={};r&&(o.time=r),o.level=Lt.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?Hu(i.shift(),i):void 0}else typeof s=="string"&&(s=Hu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function rs(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=Lt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function wr(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var i=1;i<r.length;i++)r[i]=arguments[i-1];return t[n].apply(this,r)}}function Ry(t,e,n){const r=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;rs(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=n.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,r(s,t._logEvent,a),t._logEvent=$o(c)}function $o(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Ny(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function Uy(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Wu:Gu}function is(){return{}}function To(t){return t}function Kr(){}function Wu(){return!1}function Gu(){return Date.now()}function Fy(){return Math.round(Date.now()/1e3)}function ky(){return new Date(Date.now()).toISOString()}function Ly(){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 My={level:"info"},Hr="custom_context",Bo=1e3*1024;class zy{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 Yu{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new zy(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}class Zu{constructor(e,n=Bo){this.level=e??"error",this.levelValue=kt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Yu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===kt.levels.values.error?console.error(e):n===kt.levels.values.warn?console.warn(e):n===kt.levels.values.debug?console.debug(e):n===kt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Hn({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new Yu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Hn({extraMetadata:e})),new Blob(n,{type:"application/json"})}}class qy{constructor(e,n=Bo){this.baseChunkLogger=new Zu(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}class jy{constructor(e,n=Bo){this.baseChunkLogger=new Zu(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var Vy=Object.defineProperty,Ky=Object.defineProperties,Hy=Object.getOwnPropertyDescriptors,Ju=Object.getOwnPropertySymbols,Wy=Object.prototype.hasOwnProperty,Gy=Object.prototype.propertyIsEnumerable,Xu=(t,e,n)=>e in t?Vy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ss=(t,e)=>{for(var n in e||(e={}))Wy.call(e,n)&&Xu(t,n,e[n]);if(Ju)for(var n of Ju(e))Gy.call(e,n)&&Xu(t,n,e[n]);return t},os=(t,e)=>Ky(t,Hy(e));function Po(t){return os(ss({},t),{level:t?.level||My.level})}function Yy(t,e=Hr){return t[e]||""}function Zy(t,e,n=Hr){return t[n]=e,t}function Je(t,e=Hr){let n="";return typeof t.bindings>"u"?n=Yy(t,e):n=t.bindings().context||"",n}function Jy(t,e,n=Hr){const r=Je(t,n);return r.trim()?`${r}/${e}`:e}function Ke(t,e,n=Hr){const r=Jy(t,e,n),i=t.child({context:r});return Zy(i,r,n)}function Xy(t){var e,n;const r=new qy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt(os(ss({},t.opts),{level:"trace",browser:os(ss({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Qy(t){var e;const n=new jy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt(os(ss({},t.opts),{level:"trace"})),chunkLoggerController:n}}function ew(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Xy(t):Qy(t)}var tw=Object.defineProperty,nw=(t,e,n)=>e in t?tw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Qu=(t,e,n)=>nw(t,typeof e!="symbol"?e+"":e,n);class rw extends jn{constructor(e){super(),this.opts=e,Qu(this,"protocol","wc"),Qu(this,"version",2)}}var iw=Object.defineProperty,sw=(t,e,n)=>e in t?iw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ow=(t,e,n)=>sw(t,typeof e!="symbol"?e+"":e,n);class aw extends jn{constructor(e,n){super(),this.core=e,this.logger=n,ow(this,"records",new Map)}}class cw{constructor(e,n){this.logger=e,this.core=n}}class uw extends jn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class lw extends jn{constructor(e){super()}}class hw{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class fw extends jn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class dw extends jn{constructor(e,n){super(),this.core=e,this.logger=n}}class pw{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class gw{constructor(e,n){this.projectId=e,this.logger=n}}class yw{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var ww=Object.defineProperty,mw=(t,e,n)=>e in t?ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,el=(t,e,n)=>mw(t,typeof e!="symbol"?e+"":e,n);class bw{constructor(e){this.opts=e,el(this,"protocol","wc"),el(this,"version",2)}}class vw{constructor(e){this.client=e}}function Ew(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tl(t,...e){if(!Ew(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 nl(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 xw(t,e){tl(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const mr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Co=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function _w(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function rl(t){return typeof t=="string"&&(t=_w(t)),tl(t),t}class Iw{clone(){return this._cloneInto()}}function Sw(t){const e=r=>t().update(rl(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function il(t=32){if(mr&&typeof mr.getRandomValues=="function")return mr.getRandomValues(new Uint8Array(t));if(mr&&typeof mr.randomBytes=="function")return mr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Aw(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}class Dw extends Iw{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){nl(this);const{view:n,buffer:r,blockLen:i}=this;e=rl(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Co(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nl(this),xw(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;Aw(r,i-8,BigInt(this.length*8),s),this.process(r,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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const as=BigInt(2**32-1),Ro=BigInt(32);function sl(t,e=!1){return e?{h:Number(t&as),l:Number(t>>Ro&as)}:{h:Number(t>>Ro&as)|0,l:Number(t&as)|0}}function Ow(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=sl(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const $w=(t,e)=>BigInt(t>>>0)<<Ro|BigInt(e>>>0),Tw=(t,e,n)=>t>>>n,Bw=(t,e,n)=>t<<32-n|e>>>n,Pw=(t,e,n)=>t>>>n|e<<32-n,Cw=(t,e,n)=>t<<32-n|e>>>n,Rw=(t,e,n)=>t<<64-n|e>>>n-32,Nw=(t,e,n)=>t>>>n-32|e<<64-n,Uw=(t,e)=>e,Fw=(t,e)=>t,kw=(t,e,n)=>t<<n|e>>>32-n,Lw=(t,e,n)=>e<<n|t>>>32-n,Mw=(t,e,n)=>e<<n-32|t>>>64-n,zw=(t,e,n)=>t<<n-32|e>>>64-n;function qw(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const jw=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Vw=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Kw=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Hw=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ww=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Gw=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Y={fromBig:sl,split:Ow,toBig:$w,shrSH:Tw,shrSL:Bw,rotrSH:Pw,rotrSL:Cw,rotrBH:Rw,rotrBL:Nw,rotr32H:Uw,rotr32L:Fw,rotlSH:kw,rotlSL:Lw,rotlBH:Mw,rotlBL:zw,add:qw,add3L:jw,add3H:Vw,add4L:Kw,add4H:Hw,add5H:Gw,add5L:Ww},[Yw,Zw]=Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),dn=new Uint32Array(80),pn=new Uint32Array(80);class Jw extends Dw{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let b=0;b<16;b++,n+=4)dn[b]=e.getUint32(n),pn[b]=e.getUint32(n+=4);for(let b=16;b<80;b++){const v=dn[b-15]|0,x=pn[b-15]|0,T=Y.rotrSH(v,x,1)^Y.rotrSH(v,x,8)^Y.shrSH(v,x,7),R=Y.rotrSL(v,x,1)^Y.rotrSL(v,x,8)^Y.shrSL(v,x,7),C=dn[b-2]|0,m=pn[b-2]|0,B=Y.rotrSH(C,m,19)^Y.rotrBH(C,m,61)^Y.shrSH(C,m,6),S=Y.rotrSL(C,m,19)^Y.rotrBL(C,m,61)^Y.shrSL(C,m,6),O=Y.add4L(R,S,pn[b-7],pn[b-16]),P=Y.add4H(O,T,B,dn[b-7],dn[b-16]);dn[b]=P|0,pn[b]=O|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let b=0;b<80;b++){const v=Y.rotrSH(h,f,14)^Y.rotrSH(h,f,18)^Y.rotrBH(h,f,41),x=Y.rotrSL(h,f,14)^Y.rotrSL(h,f,18)^Y.rotrBL(h,f,41),T=h&p^~h&g,R=f&d^~f&y,C=Y.add5L(A,x,R,Zw[b],pn[b]),m=Y.add5H(C,_,v,T,Yw[b],dn[b]),B=C|0,S=Y.rotrSH(r,i,28)^Y.rotrBH(r,i,34)^Y.rotrBH(r,i,39),O=Y.rotrSL(r,i,28)^Y.rotrBL(r,i,34)^Y.rotrBL(r,i,39),P=r&s^r&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(u|0,l|0,m|0,B|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const E=Y.add3L(B,O,F);r=Y.add3H(E,m,S,P),i=E|0}({h:r,l:i}=Y.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Y.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Y.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Y.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Y.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Y.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:_,l:A}=Y.add(this.Hh|0,this.Hl|0,_|0,A|0),this.set(r,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){dn.fill(0),pn.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 Xw=Sw(()=>new Jw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const No=BigInt(0),ol=BigInt(1),Qw=BigInt(2);function Uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Fo(t){if(!Uo(t))throw new Error("Uint8Array expected")}function ko(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const e1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lo(t){Fo(t);let e="";for(let n=0;n<t.length;n++)e+=e1[t[n]];return e}function al(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?No:BigInt("0x"+t)}const Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function cl(t){if(t>=Jt._0&&t<=Jt._9)return t-Jt._0;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function ul(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=cl(t.charCodeAt(s)),a=cl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function t1(t){return al(Lo(t))}function cs(t){return Fo(t),al(Lo(Uint8Array.from(t).reverse()))}function ll(t,e){return ul(t.toString(16).padStart(e*2,"0"))}function Mo(t,e){return ll(t,e).reverse()}function Xt(t,e,n){let r;if(typeof e=="string")try{r=ul(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Uo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function hl(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Fo(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const zo=t=>typeof t=="bigint"&&No<=t;function n1(t,e,n){return zo(t)&&zo(e)&&zo(n)&&e<=t&&t<n}function Wr(t,e,n,r){if(!n1(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function r1(t){let e;for(e=0;t>No;t>>=ol,e+=1);return e}const i1=t=>(Qw<<BigInt(t-1))-ol,s1={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"||Uo(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 qo(t,e,n={}){const r=(i,s,o)=>{const a=s1[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function fl(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Se=BigInt(0),pe=BigInt(1),Wn=BigInt(2),o1=BigInt(3),jo=BigInt(4),dl=BigInt(5),pl=BigInt(8);function ve(t,e){const n=t%e;return n>=Se?n:e+n}function a1(t,e,n){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(n<=Se)throw new Error("invalid modulus");if(n===pe)return Se;let r=pe;for(;e>Se;)e&pe&&(r=r*t%n),t=t*t%n,e>>=pe;return r}function Mt(t,e,n){let r=t;for(;e-- >Se;)r*=r,r%=n;return r}function gl(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 n=ve(t,e),r=e,i=Se,s=pe;for(;n!==Se;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==pe)throw new Error("invert: does not exist");return ve(i,e)}function c1(t){const e=(t-pe)/Wn;let n,r,i;for(n=t-pe,r=0;n%Wn===Se;n/=Wn,r++);for(i=Wn;i<t&&a1(i,e,t)!==t-pe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+pe)/jo;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(n+pe)/Wn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,i),n),l=o.pow(a,s),h=o.pow(a,n);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,pe<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function u1(t){if(t%jo===o1){const e=(t+pe)/jo;return function(n,r){const i=n.pow(r,e);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%pl===dl){const e=(t-dl)/pl;return function(n,r){const i=n.mul(r,Wn),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Wn),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return c1(t)}const l1=(t,e)=>(ve(t,e)&pe)===pe,h1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function f1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=h1.reduce((r,i)=>(r[i]="function",r),e);return qo(t,n)}function d1(t,e,n){if(n<Se)throw new Error("invalid exponent, negatives unsupported");if(n===Se)return t.ONE;if(n===pe)return e;let r=t.ONE,i=e;for(;n>Se;)n&pe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=pe;return r}function p1(t,e){const n=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(n[a]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(n[a]=t.mul(s,n[a]),t.mul(s,o)),i),n}function yl(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function wl(t,e,n=!1,r={}){if(t<=Se)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=yl(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:i1(i),ZERO:Se,ONE:pe,create:c=>ve(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&pe)===pe,neg:c=>ve(-c,t),eql:(c,u)=>c===u,sqr:c=>ve(c*c,t),add:(c,u)=>ve(c+u,t),sub:(c,u)=>ve(c-u,t),mul:(c,u)=>ve(c*u,t),pow:(c,u)=>d1(a,c,u),div:(c,u)=>ve(c*gl(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>gl(c,t),sqrt:r.sqrt||(c=>(o||(o=u1(t)),o(a,c))),invertBatch:c=>p1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?Mo(c,s):ll(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?cs(c):t1(c)}});return Object.freeze(a)}const ml=BigInt(0),us=BigInt(1);function Vo(t,e){const n=e.negate();return t?n:e}function bl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ko(t,e){bl(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function g1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function y1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ho=new WeakMap,vl=new WeakMap;function Wo(t){return vl.get(t)||1}function w1(t,e){return{constTimeNegate:Vo,hasPrecomputes(n){return Wo(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>ml;)r&us&&(i=i.add(s)),s=s.double(),r>>=us;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Ko(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){const{windows:s,windowSize:o}=Ko(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,h=BigInt(n);for(let f=0;f<s;f++){const p=f*o;let d=Number(i&u);i>>=h,d>o&&(d-=l,i+=us);const g=p,y=p+Math.abs(d)-1,_=f%2!==0,A=d<0;d===0?c=c.add(Vo(_,r[g])):a=a.add(Vo(A,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=Ko(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let h=0;h<o;h++){const f=h*a;if(i===ml)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=us),p===0)continue;let d=r[f+Math.abs(p)-1];p<0&&(d=d.negate()),s=s.add(d)}return s},getPrecomputes(n,r,i){let s=Ho.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Ho.set(r,i(s))),s},wNAFCached(n,r,i){const s=Wo(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Wo(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){bl(r,e),vl.set(n,r),Ho.delete(n)}}}function m1(t,e,n,r){if(g1(n,t),y1(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=r1(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let h=u;h>=0;h-=o){c.fill(i);for(let p=0;p<r.length;p++){const d=r[p],g=Number(d>>BigInt(h)&BigInt(a));c[g]=c[g].add(n[p])}let f=i;for(let p=c.length-1,d=i;p>0;p--)d=d.add(c[p]),f=f.add(d);if(l=l.add(f),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function b1(t){return f1(t.Fp),qo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Tt=BigInt(0),Xe=BigInt(1),ls=BigInt(2),v1=BigInt(8),E1={zip215:!0};function x1(t){const e=b1(t);return qo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function _1(t){const e=x1(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=ls<<BigInt(a*8)-Xe,l=n.create,h=wl(e.n,e.nBitLength),f=e.uvRatio||((E,w)=>{try{return{isValid:!0,value:n.sqrt(E*n.inv(w))}}catch{return{isValid:!1,value:Tt}}}),p=e.adjustScalarBytes||(E=>E),d=e.domain||((E,w,I)=>{if(ko("phflag",I),w.length||I)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){Wr("coordinate "+E,w,Tt,u)}function y(E){if(!(E instanceof b))throw new Error("ExtendedPoint expected")}const _=fl((E,w)=>{const{ex:I,ey:$,ez:D}=E,N=E.is0();w==null&&(w=N?v1:n.inv(D));const U=l(I*w),L=l($*w),j=l(D*w);if(N)return{x:Tt,y:Xe};if(j!==Xe)throw new Error("invZ was invalid");return{x:U,y:L}}),A=fl(E=>{const{a:w,d:I}=e;if(E.is0())throw new Error("bad point: ZERO");const{ex:$,ey:D,ez:N,et:U}=E,L=l($*$),j=l(D*D),V=l(N*N),K=l(V*V),H=l(L*w),Z=l(V*l(H+j)),Q=l(K+l(I*l(L*j)));if(Z!==Q)throw new Error("bad point: equation left != right (1)");const W=l($*D),ae=l(N*U);if(W!==ae)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(w,I,$,D){this.ex=w,this.ey=I,this.ez=$,this.et=D,g("x",w),g("y",I),g("z",$),g("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof b)throw new Error("extended point not allowed");const{x:I,y:$}=w||{};return g("x",I),g("y",$),new b(I,$,Xe,l(I*$))}static normalizeZ(w){const I=n.invertBatch(w.map($=>$.ez));return w.map(($,D)=>$.toAffine(I[D])).map(b.fromAffine)}static msm(w,I){return m1(b,h,w,I)}_setWindowSize(w){T.setWindowSize(this,w)}assertValidity(){A(this)}equals(w){y(w);const{ex:I,ey:$,ez:D}=this,{ex:N,ey:U,ez:L}=w,j=l(I*L),V=l(N*D),K=l($*L),H=l(U*D);return j===V&&K===H}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:I,ey:$,ez:D}=this,N=l(I*I),U=l($*$),L=l(ls*l(D*D)),j=l(w*N),V=I+$,K=l(l(V*V)-N-U),H=j+U,Z=H-L,Q=j-U,W=l(K*Z),ae=l(H*Q),ye=l(K*Q),gt=l(Z*H);return new b(W,ae,gt,ye)}add(w){y(w);const{a:I,d:$}=e,{ex:D,ey:N,ez:U,et:L}=this,{ex:j,ey:V,ez:K,et:H}=w;if(I===BigInt(-1)){const t0=l((N-D)*(V+j)),n0=l((N+D)*(V-j)),hu=l(n0-t0);if(hu===Tt)return this.double();const r0=l(U*ls*H),i0=l(L*ls*K),s0=i0+r0,o0=n0+t0,a0=i0-r0,$5=l(s0*hu),T5=l(o0*a0),B5=l(s0*a0),P5=l(hu*o0);return new b($5,T5,P5,B5)}const Z=l(D*j),Q=l(N*V),W=l(L*$*H),ae=l(U*K),ye=l((D+N)*(j+V)-Z-Q),gt=ae-W,Ot=ae+W,$t=l(Q-I*Z),Zt=l(ye*gt),go=l(Ot*$t),D5=l(ye*$t),O5=l(gt*Ot);return new b(Zt,go,O5,D5)}subtract(w){return this.add(w.negate())}wNAF(w){return T.wNAFCached(this,w,b.normalizeZ)}multiply(w){const I=w;Wr("scalar",I,Xe,r);const{p:$,f:D}=this.wNAF(I);return b.normalizeZ([$,D])[0]}multiplyUnsafe(w,I=b.ZERO){const $=w;return Wr("scalar",$,Tt,r),$===Tt?x:this.is0()||$===Xe?this:T.wNAFCachedUnsafe(this,$,b.normalizeZ,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,r).is0()}toAffine(w){return _(this,w)}clearCofactor(){const{h:w}=e;return w===Xe?this:this.multiplyUnsafe(w)}static fromHex(w,I=!1){const{d:$,a:D}=e,N=n.BYTES;w=Xt("pointHex",w,N),ko("zip215",I);const U=w.slice(),L=w[N-1];U[N-1]=L&-129;const j=cs(U),V=I?u:n.ORDER;Wr("pointHex.y",j,Tt,V);const K=l(j*j),H=l(K-Xe),Z=l($*K-D);let{isValid:Q,value:W}=f(H,Z);if(!Q)throw new Error("Point.fromHex: invalid y coordinate");const ae=(W&Xe)===Xe,ye=(L&128)!==0;if(!I&&W===Tt&&ye)throw new Error("Point.fromHex: x=0 and x_0=1");return ye!==ae&&(W=l(-W)),b.fromAffine({x:W,y:j})}static fromPrivateKey(w){return m(w).point}toRawBytes(){const{x:w,y:I}=this.toAffine(),$=Mo(I,n.BYTES);return $[$.length-1]|=w&Xe?128:0,$}toHex(){return Lo(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,Xe,l(e.Gx*e.Gy)),b.ZERO=new b(Tt,Xe,Xe,Tt);const{BASE:v,ZERO:x}=b,T=w1(b,a*8);function R(E){return ve(E,r)}function C(E){return R(cs(E))}function m(E){const w=n.BYTES;E=Xt("private key",E,w);const I=Xt("hashed private key",s(E),2*w),$=p(I.slice(0,w)),D=I.slice(w,2*w),N=C($),U=v.multiply(N),L=U.toRawBytes();return{head:$,prefix:D,scalar:N,point:U,pointBytes:L}}function B(E){return m(E).pointBytes}function S(E=new Uint8Array,...w){const I=hl(...w);return C(s(d(I,Xt("context",E),!!i)))}function O(E,w,I={}){E=Xt("message",E),i&&(E=i(E));const{prefix:$,scalar:D,pointBytes:N}=m(w),U=S(I.context,$,E),L=v.multiply(U).toRawBytes(),j=S(I.context,L,N,E),V=R(U+j*D);Wr("signature.s",V,Tt,r);const K=hl(L,Mo(V,n.BYTES));return Xt("result",K,n.BYTES*2)}const P=E1;function F(E,w,I,$=P){const{context:D,zip215:N}=$,U=n.BYTES;E=Xt("signature",E,2*U),w=Xt("message",w),I=Xt("publicKey",I,U),N!==void 0&&ko("zip215",N),i&&(w=i(w));const L=cs(E.slice(U,2*U));let j,V,K;try{j=b.fromHex(I,N),V=b.fromHex(E.slice(0,U),N),K=v.multiplyUnsafe(L)}catch{return!1}if(!N&&j.isSmallOrder())return!1;const H=S(D,V.toRawBytes(),j.toRawBytes(),w);return V.add(j.multiplyUnsafe(H)).subtract(K).clearCofactor().equals(b.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:B,sign:O,verify:F,ExtendedPoint:b,utils:{getExtendedPublicKey:m,randomPrivateKey:()=>o(n.BYTES),precompute(E=8,w=b.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const Go=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),El=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const I1=BigInt(1),xl=BigInt(2);BigInt(3);const S1=BigInt(5),A1=BigInt(8);function D1(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Go,o=t*t%s*t%s,a=Mt(o,xl,s)*o%s,c=Mt(a,I1,s)*t%s,u=Mt(c,S1,s)*c%s,l=Mt(u,e,s)*u%s,h=Mt(l,n,s)*l%s,f=Mt(h,r,s)*h%s,p=Mt(f,i,s)*f%s,d=Mt(p,i,s)*f%s,g=Mt(d,e,s)*u%s;return{pow_p_5_8:Mt(g,xl,s)*t%s,b2:o}}function O1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function $1(t,e){const n=Go,r=ve(e*e*e,n),i=ve(r*r*e,n),s=D1(t*i).pow_p_5_8;let o=ve(t*r*s,n);const a=ve(e*o*o,n),c=o,u=ve(o*El,n),l=a===t,h=a===ve(-t,n),f=a===ve(-t*El,n);return l&&(o=c),(h||f)&&(o=u),l1(o,n)&&(o=ve(-o,n)),{isValid:l||h,value:o}}const T1=wl(Go,void 0,!0),B1={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:T1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:A1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xw,randomBytes:il,adjustScalarBytes:O1,uvRatio:$1},_l=_1(B1),P1="EdDSA",C1="JWT",hs=".",fs="base64url",Il="utf8",Sl="utf8",R1=":",N1="did",U1="key",Al="base58btc",F1="z",k1="K36",L1=32;function Yo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Dl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Yo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ol(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Dl(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Yo(n)}function M1(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var z1=M1,q1=z1;const $l=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},j1=t=>new TextEncoder().encode(t),V1=t=>new TextDecoder().decode(t);class K1{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class H1{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Tl(this,e)}}class W1{constructor(e){this.decoders=e}or(e){return Tl(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Tl=(t,e)=>new W1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class G1{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new K1(e,n,r),this.decoder=new H1(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ds=({name:t,prefix:e,encode:n,decode:r})=>new G1(t,e,n,r),Gr=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=q1(n,e);return ds({prefix:t,name:e,encode:r,decode:s=>$l(i(s))})},Y1=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Z1=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Oe=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ds({prefix:e,name:t,encode(i){return Z1(i,r,n)},decode(i){return Y1(i,r,n,t)}}),J1=ds({prefix:"\0",name:"identity",encode:t=>V1(t),decode:t=>j1(t)});var X1=Object.freeze({__proto__:null,identity:J1});const Q1=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var em=Object.freeze({__proto__:null,base2:Q1});const tm=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nm=Object.freeze({__proto__:null,base8:tm});const rm=Gr({prefix:"9",name:"base10",alphabet:"0123456789"});var im=Object.freeze({__proto__:null,base10:rm});const sm=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),om=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var am=Object.freeze({__proto__:null,base16:sm,base16upper:om});const cm=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),um=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lm=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hm=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fm=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dm=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pm=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ym=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wm=Object.freeze({__proto__:null,base32:cm,base32upper:um,base32pad:lm,base32padupper:hm,base32hex:fm,base32hexupper:dm,base32hexpad:pm,base32hexpadupper:gm,base32z:ym});const mm=Gr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bm=Gr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vm=Object.freeze({__proto__:null,base36:mm,base36upper:bm});const Em=Gr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xm=Gr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _m=Object.freeze({__proto__:null,base58btc:Em,base58flickr:xm});const Im=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sm=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Am=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Dm=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Om=Object.freeze({__proto__:null,base64:Im,base64pad:Sm,base64url:Am,base64urlpad:Dm});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}"),$m=Bl.reduce((t,e,n)=>(t[n]=e,t),[]),Tm=Bl.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Bm(t){return t.reduce((e,n)=>(e+=$m[n],e),"")}function Pm(t){const e=[];for(const n of t){const r=Tm[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Cm=ds({prefix:"\u{1F680}",name:"base256emoji",encode:Bm,decode:Pm});var Rm=Object.freeze({__proto__:null,base256emoji:Cm}),Nm=Cl,Pl=128,Um=127,Fm=~Um,km=Math.pow(2,31);function Cl(t,e,n){e=e||[],n=n||0;for(var r=n;t>=km;)e[n++]=t&255|Pl,t/=128;for(;t&Fm;)e[n++]=t&255|Pl,t>>>=7;return e[n]=t|0,Cl.bytes=n-r+1,e}var Lm=Zo,Mm=128,Rl=127;function Zo(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Zo.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Rl)<<i:(o&Rl)*Math.pow(2,i),i+=7}while(o>=Mm);return Zo.bytes=s-r,n}var zm=Math.pow(2,7),qm=Math.pow(2,14),jm=Math.pow(2,21),Vm=Math.pow(2,28),Km=Math.pow(2,35),Hm=Math.pow(2,42),Wm=Math.pow(2,49),Gm=Math.pow(2,56),Ym=Math.pow(2,63),Zm=function(t){return t<zm?1:t<qm?2:t<jm?3:t<Vm?4:t<Km?5:t<Hm?6:t<Wm?7:t<Gm?8:t<Ym?9:10},Jm={encode:Nm,decode:Lm,encodingLength:Zm},Nl=Jm;const Ul=(t,e,n=0)=>(Nl.encode(t,e,n),e),Fl=t=>Nl.encodingLength(t),Jo=(t,e)=>{const n=e.byteLength,r=Fl(t),i=r+Fl(n),s=new Uint8Array(i+n);return Ul(t,s,0),Ul(n,s,r),s.set(e,i),new Xm(t,n,e,s)};class Xm{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const kl=({name:t,code:e,encode:n})=>new Qm(t,e,n);class Qm{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Jo(this.code,n):n.then(r=>Jo(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ll=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),eb=kl({name:"sha2-256",code:18,encode:Ll("SHA-256")}),tb=kl({name:"sha2-512",code:19,encode:Ll("SHA-512")});var nb=Object.freeze({__proto__:null,sha256:eb,sha512:tb});const Ml=0,rb="identity",zl=$l;var ib=Object.freeze({__proto__:null,identity:{code:Ml,name:rb,encode:zl,digest:t=>Jo(Ml,zl(t))}});new TextEncoder,new TextDecoder;const ql={...X1,...em,...nm,...im,...am,...wm,...vm,..._m,...Om,...Rm};({...nb,...ib});function jl(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Vl=jl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Xo=jl("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Dl(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Kl={utf8:Vl,"utf-8":Vl,hex:ql.base16,latin1:Xo,ascii:Xo,binary:Xo,...ql};function ps(t,e="utf8"){const n=Kl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}function br(t,e="utf8"){const n=Kl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Yo(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Hl(t){return gr(ps(br(t,fs),Il))}function gs(t){return ps(br(Hn(t),Il),fs)}function Wl(t){const e=br(k1,Al),n=F1+ps(Ol([e,t]),Al);return[N1,U1,n].join(R1)}function sb(t){return ps(t,fs)}function ob(t){return br(t,fs)}function ab(t){return br([gs(t.header),gs(t.payload)].join(hs),Sl)}function cb(t){return[gs(t.header),gs(t.payload),sb(t.signature)].join(hs)}function Qo(t){const e=t.split(hs),n=Hl(e[0]),r=Hl(e[1]),i=ob(e[2]),s=br(e.slice(0,2).join(hs),Sl);return{header:n,payload:r,signature:i,data:s}}function Gl(t=il(L1)){const e=_l.getPublicKey(t);return{secretKey:Ol([t,e]),publicKey:e}}async function ub(t,e,n,r,i=M.fromMiliseconds(Date.now())){const s={alg:P1,typ:C1},o=Wl(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=ab({header:s,payload:c}),l=_l.sign(u,r.secretKey.slice(0,32));return cb({header:s,payload:c,signature:l})}var Yl=function(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},lb=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),hb=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),fb=function(){function t(e,n,r,i){this.name=e,this.version=n,this.os=r,this.bot=i,this.type="bot-device"}return t}(),db=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),pb=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),gb=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,yb=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Zl=3,wb=[["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",gb]],Jl=[["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 mb(t){return t?Xl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pb:typeof navigator<"u"?Xl(navigator.userAgent):Eb()}function bb(t){return t!==""&&wb.reduce(function(e,n){var r=n[0],i=n[1];if(e)return e;var s=i.exec(t);return!!s&&[r,s]},!1)}function Xl(t){var e=bb(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new db;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<Zl&&(i=Yl(Yl([],i,!0),xb(Zl-i.length),!0)):i=[];var s=i.join("."),o=vb(t),a=yb.exec(t);return a&&a[1]?new fb(n,s,o,a[1]):new lb(n,s,o)}function vb(t){for(var e=0,n=Jl.length;e<n;e++){var r=Jl[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function Eb(){var t=typeof process<"u"&&process.version;return t?new hb(process.version.slice(1)):null}function xb(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var ue={};Object.defineProperty(ue,"__esModule",{value:!0}),ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=Ql=ue.getLocation=ue.getLocationOrThrow=ea=ue.getNavigator=ue.getNavigatorOrThrow=Yn=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function Gn(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=Gn;function vr(t){const e=Gn(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=vr;function _b(){return vr("document")}ue.getDocumentOrThrow=_b;function Ib(){return Gn("document")}var Yn=ue.getDocument=Ib;function Sb(){return vr("navigator")}ue.getNavigatorOrThrow=Sb;function Ab(){return Gn("navigator")}var ea=ue.getNavigator=Ab;function Db(){return vr("location")}ue.getLocationOrThrow=Db;function Ob(){return Gn("location")}var Ql=ue.getLocation=Ob;function $b(){return vr("crypto")}ue.getCryptoOrThrow=$b;function Tb(){return Gn("crypto")}ue.getCrypto=Tb;function Bb(){return vr("localStorage")}ue.getLocalStorageOrThrow=Bb;function Pb(){return Gn("localStorage")}ue.getLocalStorage=Pb;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});var eh=ta.getWindowMetadata=void 0;const th=ue;function Cb(){let t,e;try{t=th.getDocumentOrThrow(),e=th.getLocationOrThrow()}catch{return null}function n(){const h=t.getElementsByTagName("link"),f=[];for(let p=0;p<h.length;p++){const d=h[p],g=d.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=d.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let _=e.protocol+"//"+e.host;if(y.indexOf("/")===0)_+=y;else{const A=e.pathname.split("/");A.pop();const b=A.join("/");_+=b+"/"+y}f.push(_)}else if(y.indexOf("//")===0){const _=e.protocol+y;f.push(_)}else f.push(y)}}return f}function r(...h){const f=t.getElementsByTagName("meta");for(let p=0;p<f.length;p++){const d=f[p],g=["itemprop","property","name"].map(y=>d.getAttribute(y)).filter(y=>y?h.includes(y):!1);if(g.length&&g){const y=d.getAttribute("content");if(y)return y}}return""}function i(){let h=r("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return r("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=n();return{description:a,url:c,icons:u,name:o}}eh=ta.getWindowMetadata=Cb;function Yr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function na(t){return Yr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const nh="2.31.0";let ra={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${nh}`};class Zn extends Error{constructor(e,n={}){const r=n.cause instanceof Zn?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof Zn&&n.cause.docsPath||n.docsPath,s=ra.getDocsUrl?.({...n,docsPath:i}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...ra.version?[`Version: ${ra.version}`]:[]].join(`
15
+ `);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=nh}walk(e){return rh(this,e)}}function rh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?rh(t.cause,e):e?null:t}class ih extends Zn{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}}function Er(t,{dir:e,size:n=32}={}){return typeof t=="string"?Rb(t,{dir:e,size:n}):Nb(t,{dir:e,size:n})}function Rb(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new ih({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function Nb(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new ih({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s=e==="right";r[s?i:n-i-1]=t[s?i:t.length-i-1]}return r}class Ub extends Zn{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${n} to ${e})`:`(above ${n})`}`,{name:"IntegerOutOfRangeError"})}}class Fb extends Zn{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed ${n} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function xr(t,{size:e}){if(na(t)>e)throw new Fb({givenSize:na(t),maxSize:e})}function ia(t,e={}){const{signed:n}=e;e.size&&xr(t,{size:e.size});const r=BigInt(t);if(!n)return r;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return r<=s?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function kb(t,e={}){return Number(ia(t,e))}const Lb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sa(t,e={}){return typeof t=="number"||typeof t=="bigint"?oa(t,e):typeof t=="string"?qb(t,e):typeof t=="boolean"?Mb(t,e):sh(t,e)}function Mb(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{size:e.size})):n}function sh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=Lb[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(xr(r,{size:e.size}),Er(r,{dir:"right",size:e.size})):r}function oa(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new Ub({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:n,size:r,value:`${t}${c}`})}const a=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Er(a,{size:r}):a}const zb=new TextEncoder;function qb(t,e={}){const n=zb.encode(t);return sh(n,e)}const jb=new TextEncoder;function Vb(t,e={}){return typeof t=="number"||typeof t=="bigint"?Hb(t,e):typeof t=="boolean"?Kb(t,e):Yr(t)?ah(t,e):ch(t,e)}function Kb(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{size:e.size})):n}const Qt={zero:48,nine:57,A:65,F:70,a:97,f:102};function oh(t){if(t>=Qt.zero&&t<=Qt.nine)return t-Qt.zero;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function ah(t,e={}){let n=t;e.size&&(xr(n,{size:e.size}),n=Er(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=oh(r.charCodeAt(a++)),u=oh(r.charCodeAt(a++));if(c===void 0||u===void 0)throw new Zn(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);s[o]=c*16+u}return s}function Hb(t,e){const n=oa(t,e);return ah(n)}function ch(t,e={}){const n=jb.encode(t);return typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{dir:"right",size:e.size})):n}const ys=BigInt(2**32-1),uh=BigInt(32);function Wb(t,e=!1){return e?{h:Number(t&ys),l:Number(t>>uh&ys)}:{h:Number(t>>uh&ys)|0,l:Number(t&ys)|0}}function Gb(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Wb(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Yb=(t,e,n)=>t<<n|e>>>32-n,Zb=(t,e,n)=>e<<n|t>>>32-n,Jb=(t,e,n)=>e<<n-32|t>>>64-n,Xb=(t,e,n)=>t<<n-32|e>>>64-n,_r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Zr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Jn(t,...e){if(!Qb(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 e2(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Zr(t.outputLen),Zr(t.blockLen)}function Ir(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function lh(t,e){Jn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function t2(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Sr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function aa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function zt(t,e){return t<<32-e|t>>>e}const n2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function r2(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function i2(t){for(let e=0;e<t.length;e++)t[e]=r2(t[e]);return t}const hh=n2?t=>t:i2;function s2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ws(t){return typeof t=="string"&&(t=s2(t)),Jn(t),t}function o2(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Jn(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class ca{}function fh(t){const e=r=>t().update(ws(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function dh(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return Uint8Array.from(_r.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const a2=BigInt(0),Jr=BigInt(1),c2=BigInt(2),u2=BigInt(7),l2=BigInt(256),h2=BigInt(113),ph=[],gh=[],yh=[];for(let t=0,e=Jr,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],ph.push(2*(5*r+n)),gh.push((t+1)*(t+2)/2%64);let i=a2;for(let s=0;s<7;s++)e=(e<<Jr^(e>>u2)*h2)%l2,e&c2&&(i^=Jr<<(Jr<<BigInt(s))-Jr);yh.push(i)}const wh=Gb(yh,!0),f2=wh[0],d2=wh[1],mh=(t,e,n)=>n>32?Jb(t,e,n):Yb(t,e,n),bh=(t,e,n)=>n>32?Xb(t,e,n):Zb(t,e,n);function p2(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],h=mh(u,l,1)^n[a],f=bh(u,l,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=gh[o],c=mh(i,s,a),u=bh(i,s,a),l=ph[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=f2[r],t[1]^=d2[r]}Sr(n)}class ua extends ca{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Zr(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=t2(this.state)}clone(){return this._cloneInto()}keccak(){hh(this.state32),p2(this.state32,this.rounds),hh(this.state32),this.posOut=0,this.pos=0}update(e){Ir(this),e=ws(e),Jn(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Ir(this,!1),Jn(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(lh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Sr(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ua(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const g2=(t,e,n)=>fh(()=>new ua(e,t,n)),vh=g2(1,136,256/8);function Eh(t,e){const n=e||"hex",r=vh(Yr(t,{strict:!1})?Vb(t):t);return n==="bytes"?r:sa(r)}class xh extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const la=new xh(8192);function y2(t,e){if(la.has(`${t}.${e}`))return la.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=Eh(ch(n),"bytes"),i=(e?n.substring(`${e}0x`.length):n).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return la.set(`${t}.${e}`,s),s}function w2(t){const e=Eh(`0x${t.substring(4)}`).substring(26);return y2(`0x${e}`)}async function m2({hash:t,signature:e}){const n=Yr(t)?t:sa(t),{secp256k1:r}=await Promise.resolve().then(function(){return Mv});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:f}=e,p=Number(f??h),d=_h(p);return new r.Signature(ia(u),ia(l)).addRecoveryBit(d)}const o=Yr(e)?e:sa(e);if(na(o)!==65)throw new Error("invalid signature length");const a=kb(`0x${o.slice(130)}`),c=_h(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function _h(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 b2({hash:t,signature:e}){return w2(await m2({hash:t,signature:e}))}function v2(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function E2(t,e,n){return t&e^~t&n}function x2(t,e,n){return t&e^t&n^e&n}class _2 extends ca{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=aa(this.buffer)}update(e){Ir(this),e=ws(e),Jn(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=aa(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ir(this),lh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Sr(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;v2(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=aa(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const gn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),I2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yn=new Uint32Array(64);class S2 extends _2{constructor(e=32){super(64,e,8,!1),this.A=gn[0]|0,this.B=gn[1]|0,this.C=gn[2]|0,this.D=gn[3]|0,this.E=gn[4]|0,this.F=gn[5]|0,this.G=gn[6]|0,this.H=gn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)yn[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=yn[h-15],p=yn[h-2],d=zt(f,7)^zt(f,18)^f>>>3,g=zt(p,17)^zt(p,19)^p>>>10;yn[h]=g+yn[h-7]+d+yn[h-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=zt(a,6)^zt(a,11)^zt(a,25),p=l+f+E2(a,c,u)+I2[h]+yn[h]|0,g=(zt(r,2)^zt(r,13)^zt(r,22))+x2(r,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){Sr(yn)}destroy(){this.set(0,0,0,0,0,0,0,0),Sr(this.buffer)}}const ms=fh(()=>new S2),A2="0.1.1";function D2(){return A2}class He extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof He){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof He&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
+ `);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${D2()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Ih(this,e)}}function Ih(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Ih(t.cause,e):e?null:t}function O2(t,e){if(Dh(t)>e)throw new U2({givenSize:Dh(t),maxSize:e})}const en={zero:48,nine:57,A:65,F:70,a:97,f:102};function Sh(t){if(t>=en.zero&&t<=en.nine)return t-en.zero;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function $2(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new F2({size:t.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=t[o?s:t.length-s-1]}return i}function ha(t,e){if(da(t)>e)throw new V2({givenSize:da(t),maxSize:e})}function Ah(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const i=t.replace("0x","");if(i.length>r*2)throw new K2({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const T2=new TextEncoder;function B2(t){return t instanceof Uint8Array?t:typeof t=="string"?C2(t):P2(t)}function P2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function C2(t,e={}){const{size:n}=e;let r=t;n&&(ha(t,n),r=fa(t,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Sh(i.charCodeAt(c++)),l=Sh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new He(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function R2(t,e={}){const{size:n}=e,r=T2.encode(t);return typeof n=="number"?(O2(r,n),N2(r,n)):r}function N2(t,e){return $2(t,{dir:"right",size:e})}function Dh(t){return t.length}class U2 extends He{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class F2 extends He{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const k2=new TextEncoder,L2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oh(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function M2(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(ha(n,e.size),bs(n,e.size)):n}function $h(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=L2[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(ha(r,e.size),fa(r,e.size)):r}function z2(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new j2({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:n,size:r,value:`${t}${u}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?bs(c,r):c}function q2(t,e={}){return $h(k2.encode(t),e)}function bs(t,e){return Ah(t,{dir:"left",size:e})}function fa(t,e){return Ah(t,{dir:"right",size:e})}function da(t){return Math.ceil((t.length-2)/2)}class j2 extends He{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class V2 extends He{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class K2 extends He{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new xh(128),oa(0,{size:32});function H2(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=vh(B2(t));return n==="Bytes"?r:$h(r)}class W2 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const pa={checksum:new W2(8192)}.checksum,G2=/^0x[a-fA-F0-9]{40}$/;function Th(t,e={}){const{strict:n=!0}=e;if(!G2.test(t))throw new Bh({address:t,cause:new Z2});if(n){if(t.toLowerCase()===t)return;if(Y2(t)!==t)throw new Bh({address:t,cause:new J2})}}function Y2(t){if(pa.has(t))return pa.get(t);Th(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=H2(R2(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return pa.set(t,i),i}class Bh extends He{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Z2 extends He{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 J2 extends He{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const X2=/^(.*)\[([0-9]*)\]$/,Q2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ev=/^(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 ga(t,e){if(t.length!==e.length)throw new nv({expectedLength:t.length,givenLength:e.length});const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r];n.push(ga.encode(i,s))}return Oh(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return Th(c),bs(c.toLowerCase(),i?32:0)}if(n==="string")return q2(r);if(n==="bytes")return r;if(n==="bool")return bs(M2(r),i?32:1);const s=n.match(ev);if(s){const[c,u,l="256"]=s,h=Number.parseInt(l)/8;return z2(r,{size:i?32:h,signed:u==="int"})}const o=n.match(Q2);if(o){const[c,u]=o;if(Number.parseInt(u)!==(r.length-2)/2)throw new tv({expectedSize:Number.parseInt(u),value:r});return fa(r,i?32:0)}const a=n.match(X2);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let h=0;h<r.length;h++)l.push(e(u,r[h],!0));return l.length===0?"0x":Oh(...l)}throw new rv(n)}t.encode=e})(ga||(ga={}));class tv extends He{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${da(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class nv extends He{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
17
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class rv extends He{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 Ph extends ca{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,e2(e);const r=ws(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Sr(s)}update(e){return Ir(this),this.iHash.update(e),this}digestInto(e){Ir(this),Jn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ch=(t,e,n)=>new Ph(t,e).update(n).digest();Ch.create=(t,e)=>new Ph(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ya=BigInt(0),wa=BigInt(1);function Xr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wn(t){if(!Xr(t))throw new Error("Uint8Array expected")}function Qr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function vs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Rh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ya:BigInt("0x"+t)}const Nh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",iv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ei(t){if(wn(t),Nh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=iv[t[n]];return e}const tn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Uh(t){if(t>=tn._0&&t<=tn._9)return t-tn._0;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function Es(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Nh)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Uh(t.charCodeAt(s)),a=Uh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function qt(t){return Rh(ei(t))}function Fh(t){return wn(t),Rh(ei(Uint8Array.from(t).reverse()))}function Xn(t,e){return Es(t.toString(16).padStart(e*2,"0"))}function kh(t,e){return Xn(t,e).reverse()}function $e(t,e,n){let r;if(typeof e=="string")try{r=Es(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Xr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function yt(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];wn(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}function ma(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const ba=t=>typeof t=="bigint"&&ya<=t;function ti(t,e,n){return ba(t)&&ba(e)&&ba(n)&&e<=t&&t<n}function Qn(t,e,n,r){if(!ti(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function sv(t){let e;for(e=0;t>ya;t>>=wa,e+=1);return e}const xs=t=>(wa<<BigInt(t))-wa,va=t=>new Uint8Array(t),Lh=t=>Uint8Array.from(t);function ov(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=va(t),i=va(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...h)=>n(i,r,...h),c=(h=va(0))=>{i=a(Lh([0]),h),r=a(),h.length!==0&&(i=a(Lh([1]),h),r=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){r=a();const p=r.slice();f.push(p),h+=r.length}return yt(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(u()));)c();return o(),p}}const av={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"||Xr(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 ni(t,e,n={}){const r=(i,s,o)=>{const a=av[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function Mh(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Qe=BigInt(0),We=BigInt(1),er=BigInt(2),cv=BigInt(3),zh=BigInt(4),qh=BigInt(5),jh=BigInt(8);function Ae(t,e){const n=t%e;return n>=Qe?n:e+n}function wt(t,e,n){let r=t;for(;e-- >Qe;)r*=r,r%=n;return r}function Ea(t,e){if(t===Qe)throw new Error("invert: expected non-zero number");if(e<=Qe)throw new Error("invert: expected positive modulus, got "+e);let n=Ae(t,e),r=e,i=Qe,s=We;for(;n!==Qe;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==We)throw new Error("invert: does not exist");return Ae(i,e)}function Vh(t,e){const n=(t.ORDER+We)/zh,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function uv(t,e){const n=(t.ORDER-qh)/jh,r=t.mul(e,er),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,er),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function lv(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-We,n=0;for(;e%er===Qe;)e/=er,n++;let r=er;const i=xa(t);for(;Hh(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Vh;let s=i.pow(r,e);const o=(e+We)/er;return function(c,u){if(c.is0(u))return u;if(Hh(c,u)!==1)throw new Error("Cannot find square root");let l=n,h=c.mul(c.ONE,s),f=c.pow(u,e),p=c.pow(u,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,g=c.sqr(f);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");const y=We<<BigInt(l-d-1),_=c.pow(h,y);l=d,h=c.sqr(_),f=c.mul(f,h),p=c.mul(p,_)}return p}}function hv(t){return t%zh===cv?Vh:t%jh===qh?uv:lv(t)}const fv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kh(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=fv.reduce((r,i)=>(r[i]="function",r),e);return ni(t,n)}function dv(t,e,n){if(n<Qe)throw new Error("invalid exponent, negatives unsupported");if(n===Qe)return t.ONE;if(n===We)return e;let r=t.ONE,i=e;for(;n>Qe;)n&We&&(r=t.mul(r,i)),i=t.sqr(i),n>>=We;return r}function _s(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Hh(t,e){const n=(t.ORDER-We)/er,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Wh(t,e){e!==void 0&&Zr(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function xa(t,e,n=!1,r={}){if(t<=Qe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Wh(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:xs(i),ZERO:Qe,ONE:We,create:c=>Ae(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Qe<=c&&c<t},is0:c=>c===Qe,isOdd:c=>(c&We)===We,neg:c=>Ae(-c,t),eql:(c,u)=>c===u,sqr:c=>Ae(c*c,t),add:(c,u)=>Ae(c+u,t),sub:(c,u)=>Ae(c-u,t),mul:(c,u)=>Ae(c*u,t),pow:(c,u)=>dv(a,c,u),div:(c,u)=>Ae(c*Ea(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ea(c,t),sqrt:r.sqrt||(c=>(o||(o=hv(t)),o(a,c))),toBytes:c=>n?kh(c,s):Xn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?Fh(c):qt(c)},invertBatch:c=>_s(a,c),cmov:(c,u,l)=>l?u: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 pv(t,e,n=!1){const r=t.length,i=Gh(e),s=Yh(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Fh(t):qt(t),a=Ae(o,e-We)+We;return n?kh(a,i):Xn(a,i)}const Zh=BigInt(0),_a=BigInt(1);function Ia(t,e){const n=e.negate();return t?n: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 Sa(t,e){Jh(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=xs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Xh(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=_a);const u=e*r,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function gv(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function yv(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Aa=new WeakMap,Qh=new WeakMap;function Da(t){return Qh.get(t)||1}function wv(t,e){return{constTimeNegate:Ia,hasPrecomputes(n){return Da(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Zh;)r&_a&&(i=i.add(s)),s=s.double(),r>>=_a;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Sa(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){let s=t.ZERO,o=t.BASE;const a=Sa(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=Xh(i,c,a);i=u,h?o=o.add(Ia(p,r[d])):s=s.add(Ia(f,r[l]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=Sa(n,e);for(let a=0;a<o.windows&&i!==Zh;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=Xh(i,a,o);if(i=c,!l){const f=r[u];s=s.add(h?f.negate():f)}}return s},getPrecomputes(n,r,i){let s=Aa.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Aa.set(r,i(s))),s},wNAFCached(n,r,i){const s=Da(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Da(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Jh(r,e),Qh.set(n,r),Aa.delete(n)}}}function mv(t,e,n,r){gv(n,t),yv(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=sv(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=xs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(n[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),d=d.add(y);if(f=f.add(d),p!==0)for(let g=0;g<c;g++)f=f.double()}return f}function ef(t){return Kh(t.Fp),ni(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Wh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function tf(t){t.lowS!==void 0&&Qr("lowS",t.lowS),t.prehash!==void 0&&Qr("prehash",t.prehash)}function bv(t){const e=ef(t);ni(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class vv extends Error{constructor(e=""){super(e)}}const nn={Err:vv,_tlv:{encode:(t,e)=>{const{Err:n}=nn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=vs(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?vs(i.length/2|128):"";return vs(t)+s+i+e},decode(t,e){const{Err:n}=nn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=nn;if(t<Bt)throw new e("integer: negative integers are not allowed");let n=vs(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=nn;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 qt(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=nn,i=$e("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=nn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}};function Oa(t,e){return ei(Xn(t,e))}const Bt=BigInt(0),oe=BigInt(1),mn=BigInt(2),ri=BigInt(3),$a=BigInt(4);function Ev(t){const e=bv(t),{Fp:n}=e,r=xa(e.n,e.nBitLength),i=e.toBytes||((b,v,x)=>{const T=v.toAffine();return yt(Uint8Array.from([4]),n.toBytes(T.x),n.toBytes(T.y))}),s=e.fromBytes||(b=>{const v=b.subarray(1),x=n.fromBytes(v.subarray(0,n.BYTES)),T=n.fromBytes(v.subarray(n.BYTES,2*n.BYTES));return{x,y:T}});function o(b){const{a:v,b:x}=e,T=n.sqr(b),R=n.mul(T,b);return n.add(n.add(R,n.mul(b,v)),x)}function a(b,v){const x=n.sqr(v),T=o(b);return n.eql(x,T)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,ri),$a),u=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,u)))throw new Error("bad curve params: a or b");function l(b){return ti(b,oe,e.n)}function h(b){const{allowedPrivateKeyLengths:v,nByteLength:x,wrapPrivateKey:T,n:R}=e;if(v&&typeof b!="bigint"){if(Xr(b)&&(b=ei(b)),typeof b!="string"||!v.includes(b.length))throw new Error("invalid private key");b=b.padStart(x*2,"0")}let C;try{C=typeof b=="bigint"?b:qt($e("private key",b,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof b)}return T&&(C=Ae(C,R)),Qn("private key",C,oe,R),C}function f(b){if(!(b instanceof g))throw new Error("ProjectivePoint expected")}const p=Mh((b,v)=>{const{px:x,py:T,pz:R}=b;if(n.eql(R,n.ONE))return{x,y:T};const C=b.is0();v==null&&(v=C?n.ONE:n.inv(R));const m=n.mul(x,v),B=n.mul(T,v),S=n.mul(R,v);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(S,n.ONE))throw new Error("invZ was invalid");return{x:m,y:B}}),d=Mh(b=>{if(b.is0()){if(e.allowInfinityPoint&&!n.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:v,y:x}=b.toAffine();if(!n.isValid(v)||!n.isValid(x))throw new Error("bad point: x or y not FE");if(!a(v,x))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,x,T){if(v==null||!n.isValid(v))throw new Error("x required");if(x==null||!n.isValid(x)||n.is0(x))throw new Error("y required");if(T==null||!n.isValid(T))throw new Error("z required");this.px=v,this.py=x,this.pz=T,Object.freeze(this)}static fromAffine(v){const{x,y:T}=v||{};if(!v||!n.isValid(x)||!n.isValid(T))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const R=C=>n.eql(C,n.ZERO);return R(x)&&R(T)?g.ZERO:new g(x,T,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const x=_s(n,v.map(T=>T.pz));return v.map((T,R)=>T.toAffine(x[R])).map(g.fromAffine)}static fromHex(v){const x=g.fromAffine(s($e("pointHex",v)));return x.assertValidity(),x}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,x){return mv(g,r,v,x)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){d(this)}hasEvenY(){const{y:v}=this.toAffine();if(n.isOdd)return!n.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:x,py:T,pz:R}=this,{px:C,py:m,pz:B}=v,S=n.eql(n.mul(x,B),n.mul(C,R)),O=n.eql(n.mul(T,B),n.mul(m,R));return S&&O}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:v,b:x}=e,T=n.mul(x,ri),{px:R,py:C,pz:m}=this;let B=n.ZERO,S=n.ZERO,O=n.ZERO,P=n.mul(R,R),F=n.mul(C,C),E=n.mul(m,m),w=n.mul(R,C);return w=n.add(w,w),O=n.mul(R,m),O=n.add(O,O),B=n.mul(v,O),S=n.mul(T,E),S=n.add(B,S),B=n.sub(F,S),S=n.add(F,S),S=n.mul(B,S),B=n.mul(w,B),O=n.mul(T,O),E=n.mul(v,E),w=n.sub(P,E),w=n.mul(v,w),w=n.add(w,O),O=n.add(P,P),P=n.add(O,P),P=n.add(P,E),P=n.mul(P,w),S=n.add(S,P),E=n.mul(C,m),E=n.add(E,E),P=n.mul(E,w),B=n.sub(B,P),O=n.mul(E,F),O=n.add(O,O),O=n.add(O,O),new g(B,S,O)}add(v){f(v);const{px:x,py:T,pz:R}=this,{px:C,py:m,pz:B}=v;let S=n.ZERO,O=n.ZERO,P=n.ZERO;const F=e.a,E=n.mul(e.b,ri);let w=n.mul(x,C),I=n.mul(T,m),$=n.mul(R,B),D=n.add(x,T),N=n.add(C,m);D=n.mul(D,N),N=n.add(w,I),D=n.sub(D,N),N=n.add(x,R);let U=n.add(C,B);return N=n.mul(N,U),U=n.add(w,$),N=n.sub(N,U),U=n.add(T,R),S=n.add(m,B),U=n.mul(U,S),S=n.add(I,$),U=n.sub(U,S),P=n.mul(F,N),S=n.mul(E,$),P=n.add(S,P),S=n.sub(I,P),P=n.add(I,P),O=n.mul(S,P),I=n.add(w,w),I=n.add(I,w),$=n.mul(F,$),N=n.mul(E,N),I=n.add(I,$),$=n.sub(w,$),$=n.mul(F,$),N=n.add(N,$),w=n.mul(I,N),O=n.add(O,w),w=n.mul(U,N),S=n.mul(D,S),S=n.sub(S,w),w=n.mul(D,I),P=n.mul(U,P),P=n.add(P,w),new g(S,O,P)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return A.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:x,n:T}=e;Qn("scalar",v,Bt,T);const R=g.ZERO;if(v===Bt)return R;if(this.is0()||v===oe)return this;if(!x||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:C,k1:m,k2neg:B,k2:S}=x.splitScalar(v),O=R,P=R,F=this;for(;m>Bt||S>Bt;)m&oe&&(O=O.add(F)),S&oe&&(P=P.add(F)),F=F.double(),m>>=oe,S>>=oe;return C&&(O=O.negate()),B&&(P=P.negate()),P=new g(n.mul(P.px,x.beta),P.py,P.pz),O.add(P)}multiply(v){const{endo:x,n:T}=e;Qn("scalar",v,oe,T);let R,C;if(x){const{k1neg:m,k1:B,k2neg:S,k2:O}=x.splitScalar(v);let{p:P,f:F}=this.wNAF(B),{p:E,f:w}=this.wNAF(O);P=A.constTimeNegate(m,P),E=A.constTimeNegate(S,E),E=new g(n.mul(E.px,x.beta),E.py,E.pz),R=P.add(E),C=F.add(w)}else{const{p:m,f:B}=this.wNAF(v);R=m,C=B}return g.normalizeZ([R,C])[0]}multiplyAndAddUnsafe(v,x,T){const R=g.BASE,C=(B,S)=>S===Bt||S===oe||!B.equals(R)?B.multiplyUnsafe(S):B.multiply(S),m=C(this,x).add(C(v,T));return m.is0()?void 0:m}toAffine(v){return p(this,v)}isTorsionFree(){const{h:v,isTorsionFree:x}=e;if(v===oe)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:x}=e;return v===oe?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return Qr("isCompressed",v),this.assertValidity(),i(g,this,v)}toHex(v=!0){return Qr("isCompressed",v),ei(this.toRawBytes(v))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:y,nBitLength:_}=e,A=wv(g,y?Math.ceil(_/2):_);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:l}}function xv(t){const e=ef(t);return ni(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function _v(t){const e=xv(t),{Fp:n,n:r,nByteLength:i,nBitLength:s}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(E){return Ae(E,r)}function u(E){return Ea(E,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=Ev({...e,toBytes(E,w,I){const $=w.toAffine(),D=n.toBytes($.x),N=yt;return Qr("isCompressed",I),I?N(Uint8Array.from([w.hasEvenY()?2:3]),D):N(Uint8Array.from([4]),D,n.toBytes($.y))},fromBytes(E){const w=E.length,I=E[0],$=E.subarray(1);if(w===o&&(I===2||I===3)){const D=qt($);if(!ti(D,oe,n.ORDER))throw new Error("Point is not on curve");const N=f(D);let U;try{U=n.sqrt(N)}catch(V){const K=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+K)}const L=(U&oe)===oe;return(I&1)===1!==L&&(U=n.neg(U)),{x:D,y:U}}else if(w===a&&I===4){const D=n.fromBytes($.subarray(0,n.BYTES)),N=n.fromBytes($.subarray(n.BYTES,2*n.BYTES));return{x:D,y:N}}else{const D=o,N=a;throw new Error("invalid Point, expected length of "+D+", or uncompressed "+N+", got "+w)}}});function d(E){const w=r>>oe;return E>w}function g(E){return d(E)?c(-E):E}const y=(E,w,I)=>qt(E.slice(w,I));class _{constructor(w,I,$){Qn("r",w,oe,r),Qn("s",I,oe,r),this.r=w,this.s=I,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(w){const I=i;return w=$e("compactSignature",w,I*2),new _(y(w,0,I),y(w,I,2*I))}static fromDER(w){const{r:I,s:$}=nn.toSig($e("DER",w));return new _(I,$)}assertValidity(){}addRecoveryBit(w){return new _(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:$,recovery:D}=this,N=R($e("msgHash",w));if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");const U=D===2||D===3?I+e.n:I;if(U>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(D&1)===0?"02":"03",j=l.fromHex(L+Oa(U,n.BYTES)),V=u(U),K=c(-N*V),H=c($*V),Z=l.BASE.multiplyAndAddUnsafe(j,K,H);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Es(this.toDERHex())}toDERHex(){return nn.hexFromSig(this)}toCompactRawBytes(){return Es(this.toCompactHex())}toCompactHex(){const w=i;return Oa(this.r,w)+Oa(this.s,w)}}const A={isValidPrivateKey(E){try{return h(E),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const E=Yh(e.n);return pv(e.randomBytes(E),e.n)},precompute(E=8,w=l.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}};function b(E,w=!0){return l.fromPrivateKey(E).toRawBytes(w)}function v(E){if(typeof E=="bigint")return!1;if(E instanceof l)return!0;const I=$e("key",E).length,$=n.BYTES,D=$+1,N=2*$+1;if(!(e.allowedPrivateKeyLengths||i===D))return I===D||I===N}function x(E,w,I=!0){if(v(E)===!0)throw new Error("first arg must be private key");if(v(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(h(E)).toRawBytes(I)}const T=e.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");const w=qt(E),I=E.length*8-s;return I>0?w>>BigInt(I):w},R=e.bits2int_modN||function(E){return c(T(E))},C=xs(s);function m(E){return Qn("num < 2^"+s,E,Bt,C),Xn(E,i)}function B(E,w,I=S){if(["recovered","canonical"].some(W=>W in I))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:D}=e;let{lowS:N,prehash:U,extraEntropy:L}=I;N==null&&(N=!0),E=$e("msgHash",E),tf(I),U&&(E=$e("prehashed msgHash",$(E)));const j=R(E),V=h(w),K=[m(V),m(j)];if(L!=null&&L!==!1){const W=L===!0?D(n.BYTES):L;K.push($e("extraEntropy",W))}const H=yt(...K),Z=j;function Q(W){const ae=T(W);if(!p(ae))return;const ye=u(ae),gt=l.BASE.multiply(ae).toAffine(),Ot=c(gt.x);if(Ot===Bt)return;const $t=c(ye*c(Z+Ot*V));if($t===Bt)return;let Zt=(gt.x===Ot?0:2)|Number(gt.y&oe),go=$t;return N&&d($t)&&(go=g($t),Zt^=1),new _(Ot,go,Zt)}return{seed:H,k2sig:Q}}const S={lowS:e.lowS,prehash:!1},O={lowS:e.lowS,prehash:!1};function P(E,w,I=S){const{seed:$,k2sig:D}=B(E,w,I),N=e;return ov(N.hash.outputLen,N.nByteLength,N.hmac)($,D)}l.BASE._setWindowSize(8);function F(E,w,I,$=O){const D=E;w=$e("msgHash",w),I=$e("publicKey",I);const{lowS:N,prehash:U,format:L}=$;if(tf($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const j=typeof D=="string"||Xr(D),V=!j&&!L&&typeof D=="object"&&D!==null&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!j&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,H;try{if(V&&(K=new _(D.r,D.s)),j){try{L!=="compact"&&(K=_.fromDER(D))}catch(Zt){if(!(Zt instanceof nn.Err))throw Zt}!K&&L!=="der"&&(K=_.fromCompact(D))}H=l.fromHex(I)}catch{return!1}if(!K||N&&K.hasHighS())return!1;U&&(w=e.hash(w));const{r:Z,s:Q}=K,W=R(w),ae=u(Q),ye=c(W*ae),gt=c(Z*ae),Ot=l.BASE.multiplyAndAddUnsafe(H,ye,gt)?.toAffine();return Ot?c(Ot.x)===Z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:P,verify:F,ProjectivePoint:l,Signature:_,utils:A}}function Iv(t,e){const n=t.ORDER;let r=Bt;for(let d=n-oe;d%mn===Bt;d/=mn)r+=oe;const i=r,s=mn<<i-oe-oe,o=s*mn,a=(n-oe)/o,c=(a-oe)/mn,u=o-oe,l=s,h=t.pow(e,a),f=t.pow(e,(a+oe)/mn);let p=(d,g)=>{let y=h,_=t.pow(g,u),A=t.sqr(_);A=t.mul(A,g);let b=t.mul(d,A);b=t.pow(b,c),b=t.mul(b,_),_=t.mul(b,g),A=t.mul(b,d);let v=t.mul(A,_);b=t.pow(v,l);let x=t.eql(b,t.ONE);_=t.mul(A,f),b=t.mul(v,y),A=t.cmov(_,A,x),v=t.cmov(b,v,x);for(let T=i;T>oe;T--){let R=T-mn;R=mn<<R-oe;let C=t.pow(v,R);const m=t.eql(C,t.ONE);_=t.mul(A,y),y=t.mul(y,y),C=t.mul(v,y),A=t.cmov(_,A,m),v=t.cmov(C,v,m)}return{isValid:x,value:A}};if(t.ORDER%$a===ri){const d=(t.ORDER-ri)/$a,g=t.sqrt(t.neg(e));p=(y,_)=>{let A=t.sqr(_);const b=t.mul(y,_);A=t.mul(A,b);let v=t.pow(A,d);v=t.mul(v,b);const x=t.mul(v,g),T=t.mul(t.sqr(v),_),R=t.eql(T,y);let C=t.cmov(x,v,R);return{isValid:R,value:C}}}return p}function Sv(t,e){if(Kh(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=Iv(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,u,l,h;i=t.sqr(r),i=t.mul(i,e.Z),s=t.sqr(i),s=t.add(s,i),o=t.add(s,t.ONE),o=t.mul(o,e.B),a=t.cmov(e.Z,t.neg(s),!t.eql(s,t.ZERO)),a=t.mul(a,e.A),s=t.sqr(o),u=t.sqr(a),c=t.mul(u,e.A),s=t.add(s,c),s=t.mul(s,o),u=t.mul(u,a),c=t.mul(u,e.B),s=t.add(s,c),l=t.mul(i,o);const{isValid:f,value:p}=n(s,u);h=t.mul(i,r),h=t.mul(h,p),l=t.cmov(l,o,f),h=t.cmov(h,p,f);const d=t.isOdd(r)===t.isOdd(h);h=t.cmov(t.neg(h),h,d);const g=_s(t,[a],!0)[0];return l=t.mul(l,g),{x:l,y:h}}}function Av(t){return{hash:t,hmac:(e,...n)=>Ch(t,e,o2(...n)),randomBytes:dh}}function Dv(t,e){const n=r=>_v({...t,...Av(r)});return{...n(e),create:n}}const Ov=qt;function bn(t,e){if(ii(t),ii(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function $v(t,e){const n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function ii(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function Tv(t,e,n,r){wn(t),wn(e),ii(n),e.length>255&&(e=r(yt(ma("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=yt(e,bn(e.length,1)),c=bn(0,s),u=bn(n,2),l=new Array(o),h=r(yt(c,t,u,bn(0,1),a));l[0]=r(yt(h,bn(1,1),a));for(let p=1;p<=o;p++){const d=[$v(h,l[p-1]),bn(p+1,1),a];l[p]=r(yt(...d))}return yt(...l).slice(0,n)}function Bv(t,e,n,r,i){if(wn(t),wn(e),ii(n),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(ma("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(t).update(bn(n,2)).update(e).update(bn(e.length,1)).digest()}function nf(t,e,n){ni(n,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;wn(t),ii(e);const u=typeof c=="string"?ma(c):c,l=r.toString(2).length,h=Math.ceil((l+i)/8),f=e*s*h;let p;if(a==="xmd")p=Tv(t,u,f,o);else if(a==="xof")p=Bv(t,u,f,i,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let g=0;g<e;g++){const y=new Array(s);for(let _=0;_<s;_++){const A=h*(_+g*s),b=p.subarray(A,A+h);y[_]=Ae(Ov(b),r)}d[g]=y}return d}function Pv(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(h=>h.reduce((f,p)=>t.add(t.mul(f,r),p))),[u,l]=_s(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}function Cv(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const a=nf(s,2,{...n,DST:n.DST,...o}),c=r(a[0]),u=r(a[1]);return i(c.add(u))},encodeToCurve(s,o){const a=nf(s,1,{...n,DST:n.encodeDST,...o});return i(r(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))}}}const si=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Is=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ta=BigInt(0),oi=BigInt(1),Ss=BigInt(2),rf=(t,e)=>(t+e/Ss)/e;function sf(t){const e=si,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,h=wt(l,n,e)*l%e,f=wt(h,n,e)*l%e,p=wt(f,Ss,e)*u%e,d=wt(p,i,e)*p%e,g=wt(d,s,e)*d%e,y=wt(g,a,e)*g%e,_=wt(y,c,e)*y%e,A=wt(_,a,e)*g%e,b=wt(A,n,e)*l%e,v=wt(b,o,e)*d%e,x=wt(v,r,e)*u%e,T=wt(x,Ss,e);if(!vn.eql(vn.sqr(T),t))throw new Error("Cannot find square root");return T}const vn=xa(si,void 0,void 0,{sqrt:sf}),ai=Dv({a:Ta,b:BigInt(7),Fp:vn,n:Is,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Is,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-oi*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=rf(s*t,e),c=rf(-r*t,e);let u=Ae(t-a*n-c*i,e),l=Ae(-a*r-c*s,e);const h=u>o,f=l>o;if(h&&(u=e-u),f&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}}},ms),of={};function As(t,...e){let n=of[t];if(n===void 0){const r=ms(Uint8Array.from(t,i=>i.charCodeAt(0)));n=yt(r,r),of[t]=n}return ms(yt(n,...e))}const Ba=t=>t.toRawBytes(!0).slice(1),Pa=t=>Xn(t,32),Ca=t=>Ae(t,si),ci=t=>Ae(t,Is),Ra=ai.ProjectivePoint,Rv=(t,e,n)=>Ra.BASE.multiplyAndAddUnsafe(t,e,n);function Na(t){let e=ai.utils.normPrivateKeyToScalar(t),n=Ra.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:ci(-e),bytes:Ba(n)}}function af(t){Qn("x",t,oi,si);const e=Ca(t*t),n=Ca(e*t+BigInt(7));let r=sf(n);r%Ss!==Ta&&(r=Ca(-r));const i=new Ra(t,r,oi);return i.assertValidity(),i}const Ar=qt;function cf(...t){return ci(Ar(As("BIP0340/challenge",...t)))}function Nv(t){return Na(t).bytes}function Uv(t,e,n=dh(32)){const r=$e("message",t),{bytes:i,scalar:s}=Na(e),o=$e("auxRand",n,32),a=Pa(s^Ar(As("BIP0340/aux",o))),c=As("BIP0340/nonce",a,i,r),u=ci(Ar(c));if(u===Ta)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Na(u),f=cf(l,i,r),p=new Uint8Array(64);if(p.set(l,0),p.set(Pa(ci(h+f*s)),32),!uf(p,r,i))throw new Error("sign: Invalid signature produced");return p}function uf(t,e,n){const r=$e("signature",t,64),i=$e("message",e),s=$e("publicKey",n,32);try{const o=af(Ar(s)),a=Ar(r.subarray(0,32));if(!ti(a,oi,si))return!1;const c=Ar(r.subarray(32,64));if(!ti(c,oi,Is))return!1;const u=cf(Pa(a),Ba(o),i),l=Rv(o,c,ci(-u));return!(!l||!l.hasEvenY()||l.toAffine().x!==a)}catch{return!1}}const Fv={getPublicKey:Nv,sign:Uv,verify:uf,utils:{randomPrivateKey:ai.utils.randomPrivateKey,lift_x:af,pointToBytes:Ba,numberToBytesBE:Xn,bytesToNumberBE:qt,taggedHash:As,mod:Ae}},kv=Pv(vn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),Lv=Sv(vn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:vn.create(BigInt("-11"))}),Ua=Cv(ai.ProjectivePoint,t=>{const{x:e,y:n}=Lv(vn.create(t[0]));return kv(e,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:vn.ORDER,m:1,k:128,expand:"xmd",hash:ms});var Mv=Object.freeze({__proto__:null,secp256k1:ai,schnorr:Fv,secp256k1_hasher:Ua,hashToCurve:Ua.hashToCurve,encodeToCurve:Ua.encodeToCurve});function zv(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 n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,l++;const d=(p-f)*s+1>>>0,g=new Uint8Array(d);for(;f!==p;){let A=u[f],b=0;for(let v=d-1;(A!==0||b<h)&&v!==-1;v--,b++)A+=256*g[v]>>>0,g[v]=A%n>>>0,A=A/n>>>0;if(A!==0)throw new Error("Non-zero carry");h=b,f++}let y=d-h;for(;y!==d&&g[y]===0;)y++;let _=r.repeat(l);for(;y<d;++y)_+=t.charAt(g[y]);return _}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===r;)h++,l++;const p=(u.length-l)*i+1>>>0,d=new Uint8Array(p);for(;l<u.length;){const A=u.charCodeAt(l);if(A>255)return;let b=e[A];if(b===255)return;let v=0;for(let x=p-1;(b!==0||v<f)&&x!==-1;x--,v++)b+=n*d[x]>>>0,d[x]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=v,l++}let g=p-f;for(;g!==p&&d[g]===0;)g++;const y=new Uint8Array(h+(p-g));let _=h;for(;g!==p;)y[_++]=d[g++];return y}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var qv="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ui=zv(qv);function jv(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function Vv(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if((o&4294967168)===0){e[i++]=o;continue}else if((o&4294965248)===0)e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128):(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128)}e[i++]=o&63|128}}const Kv=new TextEncoder,Hv=50;function Wv(t,e,n){Kv.encodeInto(t,e.subarray(n))}function Gv(t,e,n){t.length>Hv?Wv(t,e,n):Vv(t,e,n)}const Yv=4096;function lf(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const a=t[r++];if((a&128)===0)s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,l=t[r++]&63;let h=(a&7)<<18|c<<12|u<<6|l;h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|h&1023),s.push(h)}else s.push(a);s.length>=Yv&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Zv=new TextDecoder,Jv=200;function Xv(t,e,n){const r=t.subarray(e,e+n);return Zv.decode(r)}function Qv(t,e,n){return n>Jv?Xv(t,e,n):lf(t,e,n)}class Ds{constructor(e,n){this.type=e,this.data=n}}class ct extends Error{constructor(e){super(e);const n=Object.create(ct.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const li=4294967295;function eE(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function hf(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function ff(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function tE(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const nE=-1,rE=4294967296-1,iE=17179869184-1;function sE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=iE)if(e===0&&t<=rE){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),hf(r,4,t),n}}function oE(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function aE(t){if(t instanceof Date){const e=oE(t);return sE(e)}else return null}function cE(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=ff(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function uE(t){const e=cE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const lE={type:nE,encode:aE,decode:uE};class Os{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(lE)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new Ds(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new Ds(o,s)}}}return e instanceof Ds?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new Ds(n,e)}}Os.defaultCodec=new Os;function hE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Fa(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):hE(t)?new Uint8Array(t):Uint8Array.from(t)}const fE=100,dE=2048;class ka{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Os.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??fE,this.initialBufferSize=e?.initialBufferSize??dE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new ka({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=jv(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Gv(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=Fa(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),eE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),hf(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function pE(t,e){return new ka(e).encodeSharedRef(t)}function La(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const gE=16,yE=16;class wE{constructor(e=gE,n=yE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=lf(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Ma="array",hi="map_key",df="map_value",mE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ct("The type of key must be string or number but "+typeof t)};class bE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Ma,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=hi,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ma){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===hi||e.type===df){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const fi=-1,za=new DataView(new ArrayBuffer(0)),vE=new Uint8Array(za.buffer);try{za.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const pf=new RangeError("Insufficient data"),EE=new wE;class qa{constructor(e){this.totalPos=0,this.pos=0,this.view=za,this.bytes=vE,this.headByte=fi,this.stack=new bE,this.entered=!1,this.extensionCodec=e?.extensionCodec??Os.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??li,this.maxBinLength=e?.maxBinLength??li,this.maxArrayLength=e?.maxArrayLength??li,this.maxMapLength=e?.maxMapLength??li,this.maxExtLength=e?.maxExtLength??li,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:EE,this.mapKeyConverter=e?.mapKeyConverter??mE}clone(){return new qa({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=fi,this.stack.reset()}setBuffer(e){const n=Fa(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===fi&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=Fa(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${La(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new ct(`Unrecognized type byte: ${La(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Ma)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===hi){if(n==="__proto__")throw new ct("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=df;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=hi;continue e}}return n}}readHeadByte(){return this.headByte===fi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=fi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ct(`Unrecognized array type byte: ${La(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw pf;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=Qv(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hi:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw pf;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=tE(this.view,this.pos);return this.pos+=8,e}readI64(){const e=ff(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function xE(t,e){return new qa(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ja(t,...e){if(!$s(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function gf(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function yf(t){if(typeof t!="function")throw new Error("function expected");return!0}function En(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function di(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ts(t){if(!Array.isArray(t))throw new Error("array expected")}function Bs(t,e){if(!gf(!0,e))throw new Error(`${t}: array of strings expected`)}function Va(t,e){if(!gf(!1,e))throw new Error(`${t}: array of numbers expected`)}function ut(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function lt(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Bs("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Ts(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Ts(i),i.map(s=>{En("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function ht(t=""){return En("join",t),{encode:e=>(Bs("join.decode",e),e.join(t)),decode:e=>(En("join.decode",e),e.split(t))}}function Ps(t,e="="){return di(t),En("padding",e),{encode(n){for(Bs("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Bs("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function wf(t){return yf(t),{encode:e=>e,decode:e=>t(e)}}function mf(t,e,n){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Ts(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(di(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=r;u<o;u++){const l=s[u],h=e*a,f=h+l;if(!Number.isSafeInteger(f)||h/e!==a||f-l!==h)throw new Error("convertRadix: carry overflow");const p=f/n;a=f%n;const d=Math.floor(p);if(s[u]=d,!Number.isSafeInteger(d)||d*n+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:r=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const bf=(t,e)=>e===0?t:bf(e,t%e),Cs=(t,e)=>t+(e-bf(t,e)),Rs=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ka(t,e,n,r){if(Ts(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Cs(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Cs(e,n)}`);let i=0,s=0;const o=Rs[e],a=Rs[n]-1,c=[];for(const u of t){if(di(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const l=Rs[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function _E(t){di(t);const e=2**8;return{encode:n=>{if(!$s(n))throw new Error("radix.encode input should be Uint8Array");return mf(Array.from(n),e,t)},decode:n=>(Va("radix.decode",n),Uint8Array.from(mf(n,t,e)))}}function mt(t,e=!1){if(di(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Cs(8,t)>32||Cs(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!$s(n))throw new Error("radix2.encode input should be Uint8Array");return Ka(Array.from(n),8,t,!e)},decode:n=>(Va("radix2.decode",n),Uint8Array.from(Ka(n,t,8,e)))}}function vf(t){return yf(t),function(...e){try{return t.apply(null,e)}catch{}}}const IE=ut(mt(5),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ps(5),ht("")),Ef=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",xf=(t,e)=>{En("base64",t);const n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Ha=t=>ut(_E(58),lt(t),ht("")),Wa=ut(lt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ht("")),_f=[996825010,642813549,513874426,1027748829,705979059];function pi(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<_f.length;r++)(e>>r&1)===1&&(n^=_f[r]);return n}function If(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=pi(i)^o>>5}i=pi(i);for(let s=0;s<r;s++)i=pi(i)^t.charCodeAt(s)&31;for(let s of e)i=pi(i)^s;for(let s=0;s<6;s++)i=pi(i);return i^=n,Wa.encode(Ka([i%Rs[30]],30,5,!1))}function Sf(t){const e=t==="bech32"?1:734539939,n=mt(5),r=n.decode,i=n.encode,s=vf(r);function o(h,f,p=90){En("bech32.encode prefix",h),$s(f)&&(f=Array.from(f)),Va("bech32.encode",f);const d=h.length;if(d===0)throw new TypeError(`Invalid prefix length ${d}`);const g=d+7+f.length;if(p!==!1&&g>p)throw new TypeError(`Length ${g} exceeds limit ${p}`);const y=h.toLowerCase(),_=If(y,f,e);return`${y}1${Wa.encode(f)}${_}`}function a(h,f=90){En("bech32.decode input",h);const p=h.length;if(p<8||f!==!1&&p>f)throw new TypeError(`invalid string length: ${p} (${h}). Expected (8..${f})`);const d=h.toLowerCase();if(h!==d&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=d.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=d.slice(0,g),_=d.slice(g+1);if(_.length<6)throw new Error("Data must be at least 6 characters long");const A=Wa.decode(_).slice(0,-6),b=If(y,A,e);if(!_.endsWith(b))throw new Error(`Invalid checksum in ${h}: expected "${b}"`);return{prefix:y,words:A}}const c=vf(a);function u(h){const{prefix:f,words:p}=a(h,!1);return{prefix:f,words:p,bytes:r(p)}}function l(h,f){return o(h,i(f))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const SE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",AE={encode(t){return ja(t),t.toHex()},decode(t){return En("hex",t),Uint8Array.fromHex(t)}};function Ga(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Af(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ga(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function gi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Af(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Ga(n)}function DE(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var OE=DE,$E=OE;const Df=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")},TE=t=>new TextEncoder().encode(t),BE=t=>new TextDecoder().decode(t);class PE{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class CE{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Of(this,e)}}class RE{constructor(e){this.decoders=e}or(e){return Of(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Of=(t,e)=>new RE({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class NE{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new PE(e,n,r),this.decoder=new CE(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ns=({name:t,prefix:e,encode:n,decode:r})=>new NE(t,e,n,r),yi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=$E(n,e);return Ns({prefix:t,name:e,encode:r,decode:s=>Df(i(s))})},UE=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},FE=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Te=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ns({prefix:e,name:t,encode(i){return FE(i,r,n)},decode(i){return UE(i,r,n,t)}}),kE=Ns({prefix:"\0",name:"identity",encode:t=>BE(t),decode:t=>TE(t)});var LE=Object.freeze({__proto__:null,identity:kE});const ME=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var zE=Object.freeze({__proto__:null,base2:ME});const qE=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jE=Object.freeze({__proto__:null,base8:qE});const VE=yi({prefix:"9",name:"base10",alphabet:"0123456789"});var KE=Object.freeze({__proto__:null,base10:VE});const HE=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),WE=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var GE=Object.freeze({__proto__:null,base16:HE,base16upper:WE});const YE=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZE=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),JE=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),XE=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),QE=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),e3=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),t3=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),n3=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),r3=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var i3=Object.freeze({__proto__:null,base32:YE,base32upper:ZE,base32pad:JE,base32padupper:XE,base32hex:QE,base32hexupper:e3,base32hexpad:t3,base32hexpadupper:n3,base32z:r3});const s3=yi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),o3=yi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var a3=Object.freeze({__proto__:null,base36:s3,base36upper:o3});const c3=yi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),u3=yi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var l3=Object.freeze({__proto__:null,base58btc:c3,base58flickr:u3});const h3=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),f3=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),d3=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),p3=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var g3=Object.freeze({__proto__:null,base64:h3,base64pad:f3,base64url:d3,base64urlpad:p3});const $f=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),y3=$f.reduce((t,e,n)=>(t[n]=e,t),[]),w3=$f.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function m3(t){return t.reduce((e,n)=>(e+=y3[n],e),"")}function b3(t){const e=[];for(const n of t){const r=w3[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const v3=Ns({prefix:"\u{1F680}",name:"base256emoji",encode:m3,decode:b3});var E3=Object.freeze({__proto__:null,base256emoji:v3}),x3=Bf,Tf=128,_3=127,I3=~_3,S3=Math.pow(2,31);function Bf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=S3;)e[n++]=t&255|Tf,t/=128;for(;t&I3;)e[n++]=t&255|Tf,t>>>=7;return e[n]=t|0,Bf.bytes=n-r+1,e}var A3=Ya,D3=128,Pf=127;function Ya(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Pf)<<i:(o&Pf)*Math.pow(2,i),i+=7}while(o>=D3);return Ya.bytes=s-r,n}var O3=Math.pow(2,7),$3=Math.pow(2,14),T3=Math.pow(2,21),B3=Math.pow(2,28),P3=Math.pow(2,35),C3=Math.pow(2,42),R3=Math.pow(2,49),N3=Math.pow(2,56),U3=Math.pow(2,63),F3=function(t){return t<O3?1:t<$3?2:t<T3?3:t<B3?4:t<P3?5:t<C3?6:t<R3?7:t<N3?8:t<U3?9:10},k3={encode:x3,decode:A3,encodingLength:F3},Cf=k3;const Rf=(t,e,n=0)=>(Cf.encode(t,e,n),e),Nf=t=>Cf.encodingLength(t),Za=(t,e)=>{const n=e.byteLength,r=Nf(t),i=r+Nf(n),s=new Uint8Array(i+n);return Rf(t,s,0),Rf(n,s,r),s.set(e,i),new L3(t,n,e,s)};class L3{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Uf=({name:t,code:e,encode:n})=>new M3(t,e,n);class M3{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Za(this.code,n):n.then(r=>Za(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ff=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),z3=Uf({name:"sha2-256",code:18,encode:Ff("SHA-256")}),q3=Uf({name:"sha2-512",code:19,encode:Ff("SHA-512")});var j3=Object.freeze({__proto__:null,sha256:z3,sha512:q3});const kf=0,V3="identity",Lf=Df;var K3=Object.freeze({__proto__:null,identity:{code:kf,name:V3,encode:Lf,digest:t=>Za(kf,Lf(t))}});new TextEncoder,new TextDecoder;const Mf={...LE,...zE,...jE,...KE,...GE,...i3,...a3,...l3,...g3,...E3};({...j3,...K3});function zf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const qf=zf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ja=zf("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Af(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),jf={utf8:qf,"utf-8":qf,hex:Mf.base16,latin1:Ja,ascii:Ja,binary:Ja,...Mf};function bt(t,e="utf8"){const n=jf[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ga(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function et(t,e="utf8"){const n=jf[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}const H3={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"}},W3="Input must be an string, Buffer or Uint8Array";function G3(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(W3);return e}function Y3(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Us(t){return(4294967296+t).toString(16).substring(1)}function Z3(t,e,n){let r=`
18
+ `+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=Us(e[i]).toUpperCase(),r+=" ",r+=Us(e[i+1]).toUpperCase();else if(n===64)r+=Us(e[i+1]).toUpperCase(),r+=Us(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
19
+ `+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function J3(t,e,n){let r=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=t(i),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var Vf={normalizeInput:G3,toHex:Y3,debugPrint:Z3,testSpeed:J3};const Fs=Vf;function ks(t,e,n){const r=t[e]+t[n];let i=t[e+1]+t[n+1];r>=4294967296&&i++,t[e]=r,t[e+1]=i}function Kf(t,e,n,r){let i=t[e]+n;n<0&&(i+=4294967296);let s=t[e+1]+r;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function Hf(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function xn(t,e,n,r,i,s){const o=wi[i],a=wi[i+1],c=wi[s],u=wi[s+1];ks(G,t,e),Kf(G,t,o,a);let l=G[r]^G[t],h=G[r+1]^G[t+1];G[r]=h,G[r+1]=l,ks(G,n,r),l=G[e]^G[n],h=G[e+1]^G[n+1],G[e]=l>>>24^h<<8,G[e+1]=h>>>24^l<<8,ks(G,t,e),Kf(G,t,c,u),l=G[r]^G[t],h=G[r+1]^G[t+1],G[r]=l>>>16^h<<16,G[r+1]=h>>>16^l<<16,ks(G,n,r),l=G[e]^G[n],h=G[e+1]^G[n+1],G[e]=h>>>31^l<<1,G[e+1]=l>>>31^h<<1}const Wf=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),X3=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Fe=new Uint8Array(X3.map(function(t){return t*2})),G=new Uint32Array(32),wi=new Uint32Array(32);function Gf(t,e){let n=0;for(n=0;n<16;n++)G[n]=t.h[n],G[n+16]=Wf[n];for(G[24]=G[24]^t.t,G[25]=G[25]^t.t/4294967296,e&&(G[28]=~G[28],G[29]=~G[29]),n=0;n<32;n++)wi[n]=Hf(t.b,4*n);for(n=0;n<12;n++)xn(0,8,16,24,Fe[n*16+0],Fe[n*16+1]),xn(2,10,18,26,Fe[n*16+2],Fe[n*16+3]),xn(4,12,20,28,Fe[n*16+4],Fe[n*16+5]),xn(6,14,22,30,Fe[n*16+6],Fe[n*16+7]),xn(0,10,20,30,Fe[n*16+8],Fe[n*16+9]),xn(2,12,22,24,Fe[n*16+10],Fe[n*16+11]),xn(4,14,16,26,Fe[n*16+12],Fe[n*16+13]),xn(6,8,18,28,Fe[n*16+14],Fe[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^G[n]^G[n+16]}const _n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function Yf(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};_n.fill(0),_n[0]=t,e&&(_n[1]=e.length),_n[2]=1,_n[3]=1,n&&_n.set(n,32),r&&_n.set(r,48);for(let s=0;s<16;s++)i.h[s]=Wf[s]^Hf(_n,s*4);return e&&(Xa(i,e),i.c=128),i}function Xa(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,Gf(t,!1),t.c=0),t.b[t.c++]=e[n]}function Zf(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;Gf(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3);return e}function Jf(t,e,n,r,i){n=n||64,t=Fs.normalizeInput(t),r&&(r=Fs.normalizeInput(r)),i&&(i=Fs.normalizeInput(i));const s=Yf(n,e,r,i);return Xa(s,t),Zf(s)}function Q3(t,e,n,r,i){const s=Jf(t,e,n,r,i);return Fs.toHex(s)}var ex={blake2b:Jf,blake2bHex:Q3,blake2bInit:Yf,blake2bUpdate:Xa,blake2bFinal:Zf};const Xf=Vf;function tx(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function In(t,e,n,r,i,s){ee[t]=ee[t]+ee[e]+i,ee[r]=Ls(ee[r]^ee[t],16),ee[n]=ee[n]+ee[r],ee[e]=Ls(ee[e]^ee[n],12),ee[t]=ee[t]+ee[e]+s,ee[r]=Ls(ee[r]^ee[t],8),ee[n]=ee[n]+ee[r],ee[e]=Ls(ee[e]^ee[n],7)}function Ls(t,e){return t>>>e^t<<32-e}const Qf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),ee=new Uint32Array(16),Be=new Uint32Array(16);function ed(t,e){let n=0;for(n=0;n<8;n++)ee[n]=t.h[n],ee[n+8]=Qf[n];for(ee[12]^=t.t,ee[13]^=t.t/4294967296,e&&(ee[14]=~ee[14]),n=0;n<16;n++)Be[n]=tx(t.b,4*n);for(n=0;n<10;n++)In(0,4,8,12,Be[ke[n*16+0]],Be[ke[n*16+1]]),In(1,5,9,13,Be[ke[n*16+2]],Be[ke[n*16+3]]),In(2,6,10,14,Be[ke[n*16+4]],Be[ke[n*16+5]]),In(3,7,11,15,Be[ke[n*16+6]],Be[ke[n*16+7]]),In(0,5,10,15,Be[ke[n*16+8]],Be[ke[n*16+9]]),In(1,6,11,12,Be[ke[n*16+10]],Be[ke[n*16+11]]),In(2,7,8,13,Be[ke[n*16+12]],Be[ke[n*16+13]]),In(3,4,9,14,Be[ke[n*16+14]],Be[ke[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=ee[n]^ee[n+8]}function td(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(Qf),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Qa(r,e),r.c=64),r}function Qa(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,ed(t,!1),t.c=0),t.b[t.c++]=e[n]}function nd(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;ed(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3)&255;return e}function rd(t,e,n){n=n||32,t=Xf.normalizeInput(t);const r=td(n,e);return Qa(r,t),nd(r)}function nx(t,e,n){const r=rd(t,e,n);return Xf.toHex(r)}var rx={blake2s:rd,blake2sHex:nx,blake2sInit:td,blake2sUpdate:Qa,blake2sFinal:nd};const mi=ex,bi=rx;var ix={blake2b:mi.blake2b,blake2bHex:mi.blake2bHex,blake2bInit:mi.blake2bInit,blake2bUpdate:mi.blake2bUpdate,blake2bFinal:mi.blake2bFinal,blake2s:bi.blake2s,blake2sHex:bi.blake2sHex,blake2sInit:bi.blake2sInit,blake2sUpdate:bi.blake2sUpdate,blake2sFinal:bi.blake2sFinal};const sx=":";function tr(t){const[e,n]=t.split(sx);return{namespace:e,reference:n}}function id(t,e){return t.includes(":")?[t]:e.chains||[]}var ox=Object.defineProperty,ax=Object.defineProperties,cx=Object.getOwnPropertyDescriptors,sd=Object.getOwnPropertySymbols,ux=Object.prototype.hasOwnProperty,lx=Object.prototype.propertyIsEnumerable,ec=(t,e,n)=>e in t?ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,od=(t,e)=>{for(var n in e||(e={}))ux.call(e,n)&&ec(t,n,e[n]);if(sd)for(var n of sd(e))lx.call(e,n)&&ec(t,n,e[n]);return t},hx=(t,e)=>ax(t,cx(e)),ad=(t,e,n)=>ec(t,typeof e!="symbol"?e+"":e,n);const fx="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},dx="js";function Ms(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Sn(){return!Yn()&&!!ea()&&navigator.product===fx}function px(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function gx(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Dr(){return!Ms()&&!!ea()&&!!Yn()}function vi(){return Sn()?ft.reactNative:Ms()?ft.node:Dr()?ft.browser:ft.unknown}function cd(){var t;try{return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function yx(t,e){const n=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&n.set(r,i)}return n.toString()}function wx(t){var e,n;const r=ud();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),hx(od(od({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function ud(){return eh()||{name:"",description:"",url:"",icons:[""]}}function mx(){if(vi()===ft.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=mb();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 bx(){var t;const e=vi();return e===ft.browser?[e,((t=Ql())==null?void 0:t.host)||"unknown"].join(":"):e}function ld(t,e,n){const r=mx(),i=bx();return[[t,e].join("-"),[dx,n].join("-"),r,i].join("/")}function vx({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=ld(t,e,r),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=yx(u[1]||"",h);return u[0]+"?"+f}function nr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function tc(t){return Object.fromEntries(t.entries())}function nc(t){return new Map(Object.entries(t))}function rr(t=M.FIVE_MINUTES,e){const n=M.toMiliseconds(t||M.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},n),r=a,i=c})}}function jt(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function hd(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 Ex(t){return hd("topic",t)}function xx(t){return hd("id",t)}function fd(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function Ee(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function An(t){return Date.now()>=M.toMiliseconds(t)}function re(t,e){return`${t}${e?`:${e}`:""}`}function ir(t=[],e=[]){return[...new Set([...t,...e])]}async function _x({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=Ix(s,t,e),a=vi();if(a===ft.browser){if(!((r=Yn())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Sx(o)}else a===ft.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function Ix(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${$x(r,!0)}`}else i=`${i}/wc?${r}`;return i}function Sx(t){let e="_self";Ox()?e="_top":(Dx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Ax(t,e){let n="";try{if(Dr()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function dd(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function pd(){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 rc(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Dx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Ox(){try{return window.self!==window.top}catch{return!1}}function $x(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function gd(t){return Buffer.from(t,"base64").toString("utf-8")}function Tx(t){return new Promise(e=>setTimeout(e,t))}class Bx{constructor({limit:e}){ad(this,"limit"),ad(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}}const zs=BigInt(2**32-1),yd=BigInt(32);function wd(t,e=!1){return e?{h:Number(t&zs),l:Number(t>>yd&zs)}:{h:Number(t>>yd&zs)|0,l:Number(t&zs)|0}}function md(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=wd(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const bd=(t,e,n)=>t>>>n,vd=(t,e,n)=>t<<32-n|e>>>n,Dn=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,Ei=(t,e,n)=>t<<64-n|e>>>n-32,xi=(t,e,n)=>t>>>n-32|e<<64-n,Px=(t,e)=>e,Cx=(t,e)=>t,Rx=(t,e,n)=>t<<n|e>>>32-n,Nx=(t,e,n)=>e<<n|t>>>32-n,Ux=(t,e,n)=>e<<n-32|t>>>64-n,Fx=(t,e,n)=>t<<n-32|e>>>64-n;function Pt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const ic=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),sc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,kx=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Lx=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Mx=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),zx=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Or=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function rn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!oc(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 ac(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");rn(t.outputLen),rn(t.blockLen)}function $n(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 cc(t,e){vt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function _i(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function uc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Vt(t,e){return t<<32-e|t>>>e}const Ed=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const sn=Ed?t=>t:t=>xd(t);function qx(t){for(let e=0;e<t.length;e++)t[e]=xd(t[e]);return t}const Tn=Ed?t=>t:qx,_d=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ii(t){if(vt(t),_d)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=jx[t[n]];return e}const on={_0:48,_9:57,A:65,F:70,a:97,f:102};function Id(t){if(t>=on._0&&t<=on._9)return t-on._0;if(t>=on.A&&t<=on.F)return t-(on.A-10);if(t>=on.a&&t<=on.f)return t-(on.a-10)}function lc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(_d)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Id(t.charCodeAt(s)),a=Id(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Vx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ct(t){return typeof t=="string"&&(t=Vx(t)),vt(t),t}function sr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];vt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class qs{}function Si(t){const e=r=>t().update(Ct(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Kx(t){const e=(r,i)=>t(i).update(Ct(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function $r(t=32){if(Or&&typeof Or.getRandomValues=="function")return Or.getRandomValues(new Uint8Array(t));if(Or&&typeof Or.randomBytes=="function")return Uint8Array.from(Or.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Hx=BigInt(0),Ai=BigInt(1),Wx=BigInt(2),Gx=BigInt(7),Yx=BigInt(256),Zx=BigInt(113),Sd=[],Ad=[],Dd=[];for(let t=0,e=Ai,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Sd.push(2*(5*r+n)),Ad.push((t+1)*(t+2)/2%64);let i=Hx;for(let s=0;s<7;s++)e=(e<<Ai^(e>>Gx)*Zx)%Yx,e&Wx&&(i^=Ai<<(Ai<<BigInt(s))-Ai);Dd.push(i)}const Od=md(Dd,!0),Jx=Od[0],Xx=Od[1],$d=(t,e,n)=>n>32?Ux(t,e,n):Rx(t,e,n),Td=(t,e,n)=>n>32?Fx(t,e,n):Nx(t,e,n);function Qx(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],h=$d(u,l,1)^n[a],f=Td(u,l,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Ad[o],c=$d(i,s,a),u=Td(i,s,a),l=Sd[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Jx[r],t[1]^=Xx[r]}Et(n)}class hc extends qs{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,rn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=_i(this.state)}clone(){return this._cloneInto()}keccak(){Tn(this.state32),Qx(this.state32,this.rounds),Tn(this.state32),this.posOut=0,this.pos=0}update(e){$n(this),e=Ct(e),vt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){$n(this,!1),vt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return rn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(cc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Et(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new hc(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const e_=(t,e,n)=>Si(()=>new hc(e,t,n)),t_=e_(1,136,256/8);function n_(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function r_(t,e,n){return t&e^~t&n}function i_(t,e,n){return t&e^t&n^e&n}class Bd extends qs{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=uc(this.buffer)}update(e){$n(this),e=Ct(e),vt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=uc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$n(this),cc(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Et(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;n_(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=uc(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:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Bn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),s_=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pn=new Uint32Array(64);class o_ extends Bd{constructor(e=32){super(64,e,8,!1),this.A=Bn[0]|0,this.B=Bn[1]|0,this.C=Bn[2]|0,this.D=Bn[3]|0,this.E=Bn[4]|0,this.F=Bn[5]|0,this.G=Bn[6]|0,this.H=Bn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)Pn[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=Pn[h-15],p=Pn[h-2],d=Vt(f,7)^Vt(f,18)^f>>>3,g=Vt(p,17)^Vt(p,19)^p>>>10;Pn[h]=g+Pn[h-7]+d+Pn[h-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Vt(a,6)^Vt(a,11)^Vt(a,25),p=l+f+r_(a,c,u)+s_[h]+Pn[h]|0,d=(Vt(r,2)^Vt(r,13)^Vt(r,22))+i_(r,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+d|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){Et(Pn)}destroy(){this.set(0,0,0,0,0,0,0,0),Et(this.buffer)}}const Pd=md(["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))),a_=Pd[0],c_=Pd[1],Cn=new Uint32Array(80),Rn=new Uint32Array(80);class fc extends Bd{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let b=0;b<16;b++,n+=4)Cn[b]=e.getUint32(n),Rn[b]=e.getUint32(n+=4);for(let b=16;b<80;b++){const v=Cn[b-15]|0,x=Rn[b-15]|0,T=Dn(v,x,1)^Dn(v,x,8)^bd(v,x,7),R=On(v,x,1)^On(v,x,8)^vd(v,x,7),C=Cn[b-2]|0,m=Rn[b-2]|0,B=Dn(C,m,19)^Ei(C,m,61)^bd(C,m,6),S=On(C,m,19)^xi(C,m,61)^vd(C,m,6),O=kx(R,S,Rn[b-7],Rn[b-16]),P=Lx(O,T,B,Cn[b-7],Cn[b-16]);Cn[b]=P|0,Rn[b]=O|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let b=0;b<80;b++){const v=Dn(h,f,14)^Dn(h,f,18)^Ei(h,f,41),x=On(h,f,14)^On(h,f,18)^xi(h,f,41),T=h&p^~h&g,R=f&d^~f&y,C=Mx(A,x,R,c_[b],Rn[b]),m=zx(C,_,v,T,a_[b],Cn[b]),B=C|0,S=Dn(r,i,28)^Ei(r,i,34)^Ei(r,i,39),O=On(r,i,28)^xi(r,i,34)^xi(r,i,39),P=r&s^r&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Pt(u|0,l|0,m|0,B|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const E=ic(B,O,F);r=sc(E,m,S,P),i=E|0}({h:r,l:i}=Pt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Pt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Pt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Pt(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Pt(this.Gh|0,this.Gl|0,g|0,y|0),{h:_,l:A}=Pt(this.Hh|0,this.Hl|0,_|0,A|0),this.set(r,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){Et(Cn,Rn)}destroy(){Et(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class u_ extends fc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const ze=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class l_ extends fc{constructor(){super(32),this.Ah=ze[0]|0,this.Al=ze[1]|0,this.Bh=ze[2]|0,this.Bl=ze[3]|0,this.Ch=ze[4]|0,this.Cl=ze[5]|0,this.Dh=ze[6]|0,this.Dl=ze[7]|0,this.Eh=ze[8]|0,this.El=ze[9]|0,this.Fh=ze[10]|0,this.Fl=ze[11]|0,this.Gh=ze[12]|0,this.Gl=ze[13]|0,this.Hh=ze[14]|0,this.Hl=ze[15]|0}}const js=Si(()=>new o_),h_=Si(()=>new fc),f_=Si(()=>new u_),d_=Si(()=>new l_),p_=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),xe=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),q=new Uint32Array(32);function Nn(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*n],p=q[2*n+1],d=q[2*r],g=q[2*r+1],y=ic(c,l,o);u=sc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Px(g,d),Dl:Cx(g)},{h:p,l:f}=Pt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:Dn(h,l,24),Bl:On(h,l,24)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*n]=f,q[2*n+1]=p,q[2*r]=d,q[2*r+1]=g}function Un(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*n],p=q[2*n+1],d=q[2*r],g=q[2*r+1],y=ic(c,l,o);u=sc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Dn(g,d,16),Dl:On(g,d,16)},{h:p,l:f}=Pt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:Ei(h,l,63),Bl:xi(h,l,63)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*n]=f,q[2*n+1]=p,q[2*r]=d,q[2*r+1]=g}function g_(t,e={},n,r,i){if(rn(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class y_ extends qs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,rn(e),rn(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=_i(this.buffer)}update(e){$n(this),e=Ct(e),vt(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(Tn(i),this.compress(i,0,!1),Tn(i),this.pos=0);const u=Math.min(n-this.pos,s-c),l=o+c;if(u===n&&!(l%4)&&c+u<s){const h=new Uint32Array(a,l,Math.floor((s-c)/4));Tn(h);for(let f=0;c+n<s;f+=i.length,c+=n)this.length+=n,this.compress(h,f,!1);Tn(h);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){$n(this),cc(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,Et(this.buffer.subarray(n)),Tn(r),this.compress(r,0,!0),Tn(r);const i=_i(e);this.get().forEach((s,o)=>i[o]=sn(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class w_ extends y_{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=xe[0]|0,this.v0h=xe[1]|0,this.v1l=xe[2]|0,this.v1h=xe[3]|0,this.v2l=xe[4]|0,this.v2h=xe[5]|0,this.v3l=xe[6]|0,this.v3h=xe[7]|0,this.v4l=xe[8]|0,this.v4h=xe[9]|0,this.v5l=xe[10]|0,this.v5h=xe[11]|0,this.v6l=xe[12]|0,this.v6h=xe[13]|0,this.v7l=xe[14]|0,this.v7h=xe[15]|0,g_(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Ct(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Ct(s);const a=_i(s);this.v4l^=sn(a[0]),this.v4h^=sn(a[1]),this.v5l^=sn(a[2]),this.v5h^=sn(a[3])}if(i!==void 0){i=Ct(i);const a=_i(i);this.v6l^=sn(a[0]),this.v6h^=sn(a[1]),this.v7l^=sn(a[2]),this.v7h^=sn(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:h,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=h|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=g|0,this.v7h=y|0}compress(e,n,r){this.get().forEach((c,u)=>q[u]=c),q.set(xe,16);let{h:i,l:s}=wd(BigInt(this.length));q[24]=xe[8]^s,q[25]=xe[9]^i,r&&(q[28]=~q[28],q[29]=~q[29]);let o=0;const a=p_;for(let c=0;c<12;c++)Nn(0,4,8,12,e,n+2*a[o++]),Un(0,4,8,12,e,n+2*a[o++]),Nn(1,5,9,13,e,n+2*a[o++]),Un(1,5,9,13,e,n+2*a[o++]),Nn(2,6,10,14,e,n+2*a[o++]),Un(2,6,10,14,e,n+2*a[o++]),Nn(3,7,11,15,e,n+2*a[o++]),Un(3,7,11,15,e,n+2*a[o++]),Nn(0,5,10,15,e,n+2*a[o++]),Un(0,5,10,15,e,n+2*a[o++]),Nn(1,6,11,12,e,n+2*a[o++]),Un(1,6,11,12,e,n+2*a[o++]),Nn(2,7,8,13,e,n+2*a[o++]),Un(2,7,8,13,e,n+2*a[o++]),Nn(3,4,9,14,e,n+2*a[o++]),Un(3,4,9,14,e,n+2*a[o++]);this.v0l^=q[0]^q[16],this.v0h^=q[1]^q[17],this.v1l^=q[2]^q[18],this.v1h^=q[3]^q[19],this.v2l^=q[4]^q[20],this.v2h^=q[5]^q[21],this.v3l^=q[6]^q[22],this.v3h^=q[7]^q[23],this.v4l^=q[8]^q[24],this.v4h^=q[9]^q[25],this.v5l^=q[10]^q[26],this.v5h^=q[11]^q[27],this.v6l^=q[12]^q[28],this.v6h^=q[13]^q[29],this.v7l^=q[14]^q[30],this.v7h^=q[15]^q[31],Et(q)}destroy(){this.destroyed=!0,Et(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const m_=Kx(t=>new w_(t)),b_="https://rpc.walletconnect.org/v1";function Cd(t){const e=`Ethereum Signed Message:
20
+ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(t_(n)).toString("hex")}async function v_(t,e,n,r,i,s){switch(n.t){case"eip191":return await E_(t,e,n.s);case"eip1271":return await x_(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}async function E_(t,e,n){return(await b2({hash:Cd(e),signature:n})).toLowerCase()===t.toLowerCase()}async function x_(t,e,n,r,i,s){const o=tr(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Cd(e)).substring(2),f=a+h+c+l+u,p=await fetch(`${s||b_}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:__(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:d}=await p.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function __(){return Date.now()+Math.floor(Math.random()*1e3)}function I_(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return ui.encode(s)}function S_(t){const e=new Uint8Array(Buffer.from(t,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const i=m_(r,{dkLen:32});return ui.encode(i)}function Rd(t){const e=new Uint8Array(js(A_(t)));return ui.encode(e)}function A_(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Nd(t){const e=Buffer.from(t,"base64"),n=xE(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=pE(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=d_(s);return IE.encode(o).replace(/=+$/,"")}function dc(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function D_(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(dc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(dc(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(dc(r.length)),i.push(r);const s=Buffer.concat(i),o=js(s);return Buffer.from(o).toString("hex").toUpperCase()}var O_=Object.defineProperty,$_=Object.defineProperties,T_=Object.getOwnPropertyDescriptors,Ud=Object.getOwnPropertySymbols,B_=Object.prototype.hasOwnProperty,P_=Object.prototype.propertyIsEnumerable,Fd=(t,e,n)=>e in t?O_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C_=(t,e)=>{for(var n in e||(e={}))B_.call(e,n)&&Fd(t,n,e[n]);if(Ud)for(var n of Ud(e))P_.call(e,n)&&Fd(t,n,e[n]);return t},R_=(t,e)=>$_(t,T_(e));const N_="did:pkh:",pc=t=>t?.split(":"),U_=t=>{const e=t&&pc(t);if(e)return t.includes(N_)?e[3]:e[1]},gc=t=>{const e=t&&pc(t);if(e)return e[2]+":"+e[3]},Vs=t=>{const e=t&&pc(t);if(e)return e.pop()};async function kd(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=Ld(i,i.iss),o=Vs(i.iss);return await v_(o,s,r,gc(i.iss),n)}const Ld=(t,e)=>{const n=`${t.domain} wants you to sign in with your Ethereum account:`,r=Vs(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: ${U_(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,f=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(g=>`
21
+ - ${g}`).join("")}`:void 0,d=Ks(t.resources);if(d){const g=Di(d);i=K_(i,g)}return[n,r,"",i,"",s,o,a,c,u,l,h,f,p].filter(g=>g!=null).join(`
22
+ `)};function F_(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function k_(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function or(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function L_(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:M_(e,n,r)}}}function M_(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function Md(t){return or(t),`urn:recap:${F_(t).replace(/=/g,"")}`}function Di(t){const e=k_(t.replace("urn:recap:",""));return or(e),e}function z_(t,e,n){const r=L_(t,e,n);return Md(r)}function q_(t){return t&&t.includes("urn:recap:")}function j_(t,e){const n=Di(t),r=Di(e),i=V_(n,r);return Md(i)}function V_(t,e){or(t),or(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;r.att[i]=R_(C_({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function K_(t="",e){or(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(i++,`(${i}) '${h}': '${u[h].join("', '")}' for '${a}'.`));r.push(l.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${t?t+" ":""}${o}`}function zd(t){var e;const n=Di(t);or(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function qd(t){const e=Di(t);or(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function Ks(t){if(!t)return;const e=t?.[t.length-1];return q_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function jd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function wc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function tt(t,...e){if(!jd(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 Vd(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 H_(t,e){tt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Fn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Tr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function W_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const G_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Y_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function mc(t){if(typeof t=="string")t=Y_(t);else if(jd(t))t=bc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Z_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function J_(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const X_=(t,e)=>{function n(r,...i){if(tt(r),!G_)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?tt(u):tt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&tt(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");tt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,tt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(tt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(n,t),n};function Kd(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!e8(e))throw new Error("invalid output, must be aligned");return e}function Hd(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Q_(t,e,n){yc(n);const r=new Uint8Array(16),i=W_(r);return Hd(i,0,BigInt(e),n),Hd(i,8,BigInt(t),n),r}function e8(t){return t.byteOffset%4===0}function bc(t){return Uint8Array.from(t)}const Wd=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),t8=Wd("expand 16-byte k"),n8=Wd("expand 32-byte k"),r8=Fn(t8),i8=Fn(n8);function te(t,e){return t<<e|t>>>32-e}function vc(t){return t.byteOffset%4===0}const Hs=64,s8=16,Gd=2**32-1,Yd=new Uint32Array;function o8(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(Hs),l=Fn(u),h=vc(i)&&vc(s),f=h?Fn(i):Yd,p=h?Fn(s):Yd;for(let d=0;d<c;o++){if(t(e,n,r,l,o,a),o>=Gd)throw new Error("arx: counter overflow");const g=Math.min(Hs,c-d);if(h&&g===Hs){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let _=0,A;_<s8;_++)A=y+_,p[A]=f[A]^l[_];d+=Hs;continue}for(let y=0,_;y<g;y++)_=d+y,s[_]=i[_]^u[y];d+=g}}function a8(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Z_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return wc(i),wc(o),yc(s),yc(n),(a,c,u,l,h=0)=>{tt(a),tt(c),tt(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),tt(l),wc(h),h<0||h>=Gd)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=bc(a)),y=i8;else if(d===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=r8,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);vc(c)||p.push(c=bc(c));const _=Fn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,_,Fn(c.subarray(0,16)),_),c=c.subarray(16)}const A=16-i;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){const v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,p.push(c)}const b=Fn(c);return o8(t,y,_,b,u,l,h,o),Tr(...p),l}}const Pe=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class c8{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=mc(e),tt(e,32);const n=Pe(e,0),r=Pe(e,2),i=Pe(e,4),s=Pe(e,6),o=Pe(e,8),a=Pe(e,10),c=Pe(e,12),u=Pe(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Pe(e,16+2*l)}process(e,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],_=Pe(e,n+0),A=Pe(e,n+2),b=Pe(e,n+4),v=Pe(e,n+6),x=Pe(e,n+8),T=Pe(e,n+10),R=Pe(e,n+12),C=Pe(e,n+14);let m=s[0]+(_&8191),B=s[1]+((_>>>13|A<<3)&8191),S=s[2]+((A>>>10|b<<6)&8191),O=s[3]+((b>>>7|v<<9)&8191),P=s[4]+((v>>>4|x<<12)&8191),F=s[5]+(x>>>1&8191),E=s[6]+((x>>>14|T<<2)&8191),w=s[7]+((T>>>11|R<<5)&8191),I=s[8]+((R>>>8|C<<8)&8191),$=s[9]+(C>>>5|i),D=0,N=D+m*a+B*(5*y)+S*(5*g)+O*(5*d)+P*(5*p);D=N>>>13,N&=8191,N+=F*(5*f)+E*(5*h)+w*(5*l)+I*(5*u)+$*(5*c),D+=N>>>13,N&=8191;let U=D+m*c+B*a+S*(5*y)+O*(5*g)+P*(5*d);D=U>>>13,U&=8191,U+=F*(5*p)+E*(5*f)+w*(5*h)+I*(5*l)+$*(5*u),D+=U>>>13,U&=8191;let L=D+m*u+B*c+S*a+O*(5*y)+P*(5*g);D=L>>>13,L&=8191,L+=F*(5*d)+E*(5*p)+w*(5*f)+I*(5*h)+$*(5*l),D+=L>>>13,L&=8191;let j=D+m*l+B*u+S*c+O*a+P*(5*y);D=j>>>13,j&=8191,j+=F*(5*g)+E*(5*d)+w*(5*p)+I*(5*f)+$*(5*h),D+=j>>>13,j&=8191;let V=D+m*h+B*l+S*u+O*c+P*a;D=V>>>13,V&=8191,V+=F*(5*y)+E*(5*g)+w*(5*d)+I*(5*p)+$*(5*f),D+=V>>>13,V&=8191;let K=D+m*f+B*h+S*l+O*u+P*c;D=K>>>13,K&=8191,K+=F*a+E*(5*y)+w*(5*g)+I*(5*d)+$*(5*p),D+=K>>>13,K&=8191;let H=D+m*p+B*f+S*h+O*l+P*u;D=H>>>13,H&=8191,H+=F*c+E*a+w*(5*y)+I*(5*g)+$*(5*d),D+=H>>>13,H&=8191;let Z=D+m*d+B*p+S*f+O*h+P*l;D=Z>>>13,Z&=8191,Z+=F*u+E*c+w*a+I*(5*y)+$*(5*g),D+=Z>>>13,Z&=8191;let Q=D+m*g+B*d+S*p+O*f+P*h;D=Q>>>13,Q&=8191,Q+=F*l+E*u+w*c+I*a+$*(5*y),D+=Q>>>13,Q&=8191;let W=D+m*y+B*g+S*d+O*p+P*f;D=W>>>13,W&=8191,W+=F*h+E*l+w*u+I*c+$*a,D+=W>>>13,W&=8191,D=(D<<2)+D|0,D=D+N|0,N=D&8191,D=D>>>13,U+=D,s[0]=N,s[1]=U,s[2]=L,s[3]=j,s[4]=V,s[5]=K,s[6]=H,s[7]=Z,s[8]=Q,s[9]=W}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Tr(r)}update(e){Vd(this),e=mc(e),tt(e);const{buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Tr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vd(this),H_(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function u8(t){const e=(r,i)=>t(i).update(mc(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const l8=u8(t=>new c8(t));function h8(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],_=e[7],A=i,b=n[0],v=n[1],x=n[2],T=o,R=a,C=c,m=u,B=l,S=h,O=f,P=p,F=d,E=g,w=y,I=_,$=A,D=b,N=v,U=x;for(let j=0;j<s;j+=2)T=T+B|0,$=te($^T,16),F=F+$|0,B=te(B^F,12),T=T+B|0,$=te($^T,8),F=F+$|0,B=te(B^F,7),R=R+S|0,D=te(D^R,16),E=E+D|0,S=te(S^E,12),R=R+S|0,D=te(D^R,8),E=E+D|0,S=te(S^E,7),C=C+O|0,N=te(N^C,16),w=w+N|0,O=te(O^w,12),C=C+O|0,N=te(N^C,8),w=w+N|0,O=te(O^w,7),m=m+P|0,U=te(U^m,16),I=I+U|0,P=te(P^I,12),m=m+P|0,U=te(U^m,8),I=I+U|0,P=te(P^I,7),T=T+S|0,U=te(U^T,16),w=w+U|0,S=te(S^w,12),T=T+S|0,U=te(U^T,8),w=w+U|0,S=te(S^w,7),R=R+O|0,$=te($^R,16),I=I+$|0,O=te(O^I,12),R=R+O|0,$=te($^R,8),I=I+$|0,O=te(O^I,7),C=C+P|0,D=te(D^C,16),F=F+D|0,P=te(P^F,12),C=C+P|0,D=te(D^C,8),F=F+D|0,P=te(P^F,7),m=m+B|0,N=te(N^m,16),E=E+N|0,B=te(B^E,12),m=m+B|0,N=te(N^m,8),E=E+N|0,B=te(B^E,7);let L=0;r[L++]=o+T|0,r[L++]=a+R|0,r[L++]=c+C|0,r[L++]=u+m|0,r[L++]=l+B|0,r[L++]=h+S|0,r[L++]=f+O|0,r[L++]=p+P|0,r[L++]=d+F|0,r[L++]=g+E|0,r[L++]=y+w|0,r[L++]=_+I|0,r[L++]=A+$|0,r[L++]=b+D|0,r[L++]=v+N|0,r[L++]=x+U|0}const f8=a8(h8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),d8=new Uint8Array(16),Zd=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(d8.subarray(n))},p8=new Uint8Array(32);function Jd(t,e,n,r,i){const s=t(e,n,p8),o=l8.create(s);i&&Zd(o,i),Zd(o,r);const a=Q_(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Tr(s,a),c}const g8=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=Kd(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Jd(t,e,n,a,r);return s.set(c,o),Tr(c),s},decrypt(i,s){s=Kd(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Jd(t,e,n,o,r);if(!J_(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Tr(c),s}}),Xd=X_({blockSize:64,nonceLength:12,tagLength:16},g8(f8));class Qd extends qs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ac(e);const r=Ct(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Et(s)}update(e){return $n(this),this.iHash.update(e),this}digestInto(e){$n(this),vt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ws=(t,e,n)=>new Qd(t,e).update(n).digest();Ws.create=(t,e)=>new Qd(t,e);function y8(t,e,n){return ac(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ws(t,Ct(n),Ct(e))}const Ec=Uint8Array.from([0]),ep=Uint8Array.of();function w8(t,e,n,r=32){ac(t),rn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=ep);const o=new Uint8Array(s*i),a=Ws.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Ec[0]=l+1,c.update(l===0?ep:u).update(n).update(Ec).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),Et(u,Ec),o.slice(0,r)}const m8=(t,e,n,r,i)=>w8(t,y8(t,e,n),r,i),Gs=js,xc=BigInt(0),_c=BigInt(1);function Ys(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Zs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function tp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xc:BigInt("0x"+t)}function Js(t){return tp(Ii(t))}function Xs(t){return vt(t),tp(Ii(Uint8Array.from(t).reverse()))}function Ic(t,e){return lc(t.toString(16).padStart(e*2,"0"))}function Sc(t,e){return Ic(t,e).reverse()}function nt(t,e,n){let r;if(typeof e=="string")try{r=lc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(oc(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Ac=t=>typeof t=="bigint"&&xc<=t;function b8(t,e,n){return Ac(t)&&Ac(e)&&Ac(n)&&e<=t&&t<n}function Dc(t,e,n,r){if(!b8(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function v8(t){let e;for(e=0;t>xc;t>>=_c,e+=1);return e}const Qs=t=>(_c<<BigInt(t))-_c;function E8(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...f)=>n(o,s,...f),l=(f=r(0))=>{o=u(i(0),f),s=u(),f.length!==0&&(o=u(i(1),f),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){s=u();const d=s.slice();p.push(d),f+=s.length}return sr(...p)};return(f,p)=>{c(),l(f);let d;for(;!(d=p(h()));)l();return c(),d}}function eo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function np(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const rt=BigInt(0),Ge=BigInt(1),ar=BigInt(2),x8=BigInt(3),rp=BigInt(4),ip=BigInt(5),sp=BigInt(8);function xt(t,e){const n=t%e;return n>=rt?n:e+n}function Rt(t,e,n){let r=t;for(;e-- >rt;)r*=r,r%=n;return r}function op(t,e){if(t===rt)throw new Error("invert: expected non-zero number");if(e<=rt)throw new Error("invert: expected positive modulus, got "+e);let n=xt(t,e),r=e,i=rt,s=Ge;for(;n!==rt;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==Ge)throw new Error("invert: does not exist");return xt(i,e)}function ap(t,e){const n=(t.ORDER+Ge)/rp,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function _8(t,e){const n=(t.ORDER-ip)/sp,r=t.mul(e,ar),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,ar),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function I8(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ge,n=0;for(;e%ar===rt;)e/=ar,n++;let r=ar;const i=Br(t);for(;up(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ap;let s=i.pow(r,e);const o=(e+Ge)/ar;return function(a,c){if(a.is0(c))return c;if(up(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let p=1,d=a.sqr(h);for(;!a.eql(d,a.ONE);)if(p++,d=a.sqr(d),p===u)throw new Error("Cannot find square root");const g=Ge<<BigInt(u-p-1),y=a.pow(l,g);u=p,l=a.sqr(y),h=a.mul(h,l),f=a.mul(f,y)}return f}}function S8(t){return t%rp===x8?ap:t%sp===ip?_8:I8(t)}const A8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function D8(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=A8.reduce((r,i)=>(r[i]="function",r),e);return eo(t,n),t}function O8(t,e,n){if(n<rt)throw new Error("invalid exponent, negatives unsupported");if(n===rt)return t.ONE;if(n===Ge)return e;let r=t.ONE,i=e;for(;n>rt;)n&Ge&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ge;return r}function cp(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function up(t,e){const n=(t.ORDER-Ge)/ar,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function $8(t,e){e!==void 0&&rn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Br(t,e,n=!1,r={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const l=e;l.BITS&&(i=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(n=l.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:o,nByteLength:a}=$8(t,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const u=Object.freeze({ORDER:t,isLE:n,BITS:o,BYTES:a,MASK:Qs(o),ZERO:rt,ONE:Ge,create:l=>xt(l,t),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return rt<=l&&l<t},is0:l=>l===rt,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&Ge)===Ge,neg:l=>xt(-l,t),eql:(l,h)=>l===h,sqr:l=>xt(l*l,t),add:(l,h)=>xt(l+h,t),sub:(l,h)=>xt(l-h,t),mul:(l,h)=>xt(l*h,t),pow:(l,h)=>O8(u,l,h),div:(l,h)=>xt(l*op(h,t),t),sqrN:l=>l*l,addN:(l,h)=>l+h,subN:(l,h)=>l-h,mulN:(l,h)=>l*h,inv:l=>op(l,t),sqrt:s||(l=>(c||(c=S8(t)),c(u,l))),toBytes:l=>n?Sc(l,a):Ic(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return n?Xs(l):Js(l)},invertBatch:l=>cp(u,l),cmov:(l,h,f)=>f?h:l});return Object.freeze(u)}function lp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function hp(t){const e=lp(t);return e+Math.ceil(e/2)}function T8(t,e,n=!1){const r=t.length,i=lp(e),s=hp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Xs(t):Js(t),a=xt(o,e-Ge)+Ge;return n?Sc(a,i):Ic(a,i)}const Pr=BigInt(0),cr=BigInt(1);function Oi(t,e){const n=e.negate();return t?n:e}function B8(t,e,n){const r=e==="pz"?s=>s.pz:s=>s.ez,i=cp(t.Fp,n.map(r));return n.map((s,o)=>s.toAffine(i[o])).map(t.fromAffine)}function fp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Oc(t,e){fp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Qs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function dp(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=cr);const u=e*r,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function P8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function C8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const $c=new WeakMap,pp=new WeakMap;function Tc(t){return pp.get(t)||1}function gp(t){if(t!==Pr)throw new Error("invalid wNAF")}function R8(t,e){return{constTimeNegate:Oi,hasPrecomputes(n){return Tc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Pr;)r&cr&&(i=i.add(s)),s=s.double(),r>>=cr;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Oc(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){let s=t.ZERO,o=t.BASE;const a=Oc(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=dp(i,c,a);i=u,h?o=o.add(Oi(p,r[d])):s=s.add(Oi(f,r[l]))}return gp(i),{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=Oc(n,e);for(let a=0;a<o.windows&&i!==Pr;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=dp(i,a,o);if(i=c,!l){const f=r[u];s=s.add(h?f.negate():f)}}return gp(i),s},getPrecomputes(n,r,i){let s=$c.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&(typeof i=="function"&&(s=i(s)),$c.set(r,s))),s},wNAFCached(n,r,i){const s=Tc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Tc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){fp(r,e),pp.set(n,r),$c.delete(n)}}}function N8(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Pr||r>Pr;)n&cr&&(s=s.add(i)),r&cr&&(o=o.add(i)),i=i.double(),n>>=cr,r>>=cr;return{p1:s,p2:o}}function U8(t,e,n,r){P8(n,t),C8(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=v8(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Qs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(n[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),d=d.add(y);if(f=f.add(d),p!==0)for(let g=0;g<c;g++)f=f.double()}return f}function yp(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return D8(e),e}else return Br(t)}function F8(t,e,n={}){if(!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const o of["p","n","h"]){const a=e[o];if(!(typeof a=="bigint"&&a>Pr))throw new Error(`CURVE.${o} must be positive bigint`)}const r=yp(e.p,n.Fp),i=yp(e.n,n.Fn),s=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const o of s)if(!r.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const $i=BigInt(0),Cr=BigInt(1),to=BigInt(2);function k8(t){return eo(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function L8(t){const e=k8(t),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||$r,u=a?255:448,l=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?to**BigInt(254):to**BigInt(447),d=a?BigInt(8)*to**BigInt(251)-Cr:BigInt(4)*to**BigInt(445)-Cr,g=p+d+Cr,y=m=>xt(m,n),_=A(h);function A(m){return Sc(y(m),l)}function b(m){const B=nt("u coordinate",m,l);return a&&(B[31]&=127),y(Xs(B))}function v(m){return Xs(i(nt("scalar",m,l)))}function x(m,B){const S=C(b(B),v(m));if(S===$i)throw new Error("invalid private or public key received");return A(S)}function T(m){return x(m,_)}function R(m,B,S){const O=y(m*(B-S));return B=y(B-O),S=y(S+O),{x_2:B,x_3:S}}function C(m,B){Dc("u",m,$i,n),Dc("scalar",B,p,g);const S=B,O=m;let P=Cr,F=$i,E=m,w=Cr,I=$i;for(let D=BigInt(u-1);D>=$i;D--){const N=S>>D&Cr;I^=N,{x_2:P,x_3:E}=R(I,P,E),{x_2:F,x_3:w}=R(I,F,w),I=N;const U=P+F,L=y(U*U),j=P-F,V=y(j*j),K=L-V,H=E+w,Z=E-w,Q=y(Z*U),W=y(H*j),ae=Q+W,ye=Q-W;E=y(ae*ae),w=y(O*y(ye*ye)),P=y(L*V),F=y(K*(L+y(f*K)))}({x_2:P,x_3:E}=R(I,P,E)),{x_2:F,x_3:w}=R(I,F,w);const $=s(F);return y(P*$)}return{scalarMult:x,scalarMultBase:T,getSharedSecret:(m,B)=>x(m,B),getPublicKey:m=>T(m),utils:{randomPrivateKey:()=>c(l)},GuBytes:_.slice()}}BigInt(0);const M8=BigInt(1),wp=BigInt(2),z8=BigInt(3),q8=BigInt(5),j8=BigInt(8),mp={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:j8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function V8(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=mp.p,o=t*t%s*t%s,a=Rt(o,wp,s)*o%s,c=Rt(a,M8,s)*t%s,u=Rt(c,q8,s)*c%s,l=Rt(u,e,s)*u%s,h=Rt(l,n,s)*l%s,f=Rt(h,r,s)*h%s,p=Rt(f,i,s)*f%s,d=Rt(p,i,s)*f%s,g=Rt(d,e,s)*u%s;return{pow_p_5_8:Rt(g,wp,s)*t%s,b2:o}}function K8(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Bc=(()=>{const t=mp.p;return L8({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=V8(e);return xt(Rt(n,z8,t)*r,t)},adjustScalarBytes:K8})})();function bp(t){t.lowS!==void 0&&Ys("lowS",t.lowS),t.prehash!==void 0&&Ys("prehash",t.prehash)}class H8 extends Error{constructor(e=""){super(e)}}const an={Err:H8,_tlv:{encode:(t,e)=>{const{Err:n}=an;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Zs(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Zs(i.length/2|128):"";return Zs(t)+s+i+e},decode(t,e){const{Err:n}=an;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=an;if(t<Ti)throw new e("integer: negative integers are not allowed");let n=Zs(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=an;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 Js(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=an,i=nt("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=an,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Ti=BigInt(0),Bi=BigInt(1),W8=BigInt(2),no=BigInt(3),G8=BigInt(4);function Y8(t,e,n){function r(i){const s=t.sqr(i),o=t.mul(s,i);return t.add(t.add(o,t.mul(i,e)),n)}return r}function vp(t,e,n){const{BYTES:r}=t;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=nt("private key",s);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{o=t.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof s}`)}}if(n&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function Z8(t,e={}){const{Fp:n,Fn:r}=F8("weierstrass",t,e),{h:i,n:s}=t;eo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!n.is0(t.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(C,m,B){const{x:S,y:O}=m.toAffine(),P=n.toBytes(S);if(Ys("isCompressed",B),B){a();const F=!n.isOdd(O);return sr(Ep(F),P)}else return sr(Uint8Array.of(4),P,n.toBytes(O))}function u(C){vt(C);const m=n.BYTES,B=m+1,S=2*m+1,O=C.length,P=C[0],F=C.subarray(1);if(O===B&&(P===2||P===3)){const E=n.fromBytes(F);if(!n.isValid(E))throw new Error("bad point: is not on curve, wrong x");const w=f(E);let I;try{I=n.sqrt(w)}catch(D){const N=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}a();const $=n.isOdd(I);return(P&1)===1!==$&&(I=n.neg(I)),{x:E,y:I}}else if(O===S&&P===4){const E=n.fromBytes(F.subarray(m*0,m*1)),w=n.fromBytes(F.subarray(m*1,m*2));if(!p(E,w))throw new Error("bad point: is not on curve");return{x:E,y:w}}else throw new Error(`bad point: got length ${O}, expected compressed=${B} or uncompressed=${S}`)}const l=e.toBytes||c,h=e.fromBytes||u,f=Y8(n,t.a,t.b);function p(C,m){const B=n.sqr(m),S=f(C);return n.eql(B,S)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const d=n.mul(n.pow(t.a,no),G8),g=n.mul(n.sqr(t.b),BigInt(27));if(n.is0(n.add(d,g)))throw new Error("bad curve params: a or b");function y(C,m,B=!1){if(!n.isValid(m)||B&&n.is0(m))throw new Error(`bad point coordinate ${C}`);return m}function _(C){if(!(C instanceof x))throw new Error("ProjectivePoint expected")}const A=np((C,m)=>{const{px:B,py:S,pz:O}=C;if(n.eql(O,n.ONE))return{x:B,y:S};const P=C.is0();m==null&&(m=P?n.ONE:n.inv(O));const F=n.mul(B,m),E=n.mul(S,m),w=n.mul(O,m);if(P)return{x:n.ZERO,y:n.ZERO};if(!n.eql(w,n.ONE))throw new Error("invZ was invalid");return{x:F,y:E}}),b=np(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.py))return;throw new Error("bad point: ZERO")}const{x:m,y:B}=C.toAffine();if(!n.isValid(m)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!p(m,B))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(C,m,B,S,O){return B=new x(n.mul(B.px,C),B.py,B.pz),m=Oi(S,m),B=Oi(O,B),m.add(B)}class x{constructor(m,B,S){this.px=y("x",m),this.py=y("y",B,!0),this.pz=y("z",S),Object.freeze(this)}static fromAffine(m){const{x:B,y:S}=m||{};if(!m||!n.isValid(B)||!n.isValid(S))throw new Error("invalid affine point");if(m instanceof x)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(S)?x.ZERO:new x(B,S,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){return B8(x,"pz",m)}static fromBytes(m){return vt(m),x.fromHex(m)}static fromHex(m){const B=x.fromAffine(h(nt("pointHex",m)));return B.assertValidity(),B}static fromPrivateKey(m){const B=vp(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return x.BASE.multiply(B(m))}static msm(m,B){return U8(x,r,m,B)}precompute(m=8,B=!0){return R.setWindowSize(this,m),B||this.multiply(no),this}_setWindowSize(m){this.precompute(m)}assertValidity(){b(this)}hasEvenY(){const{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){_(m);const{px:B,py:S,pz:O}=this,{px:P,py:F,pz:E}=m,w=n.eql(n.mul(B,E),n.mul(P,O)),I=n.eql(n.mul(S,E),n.mul(F,O));return w&&I}negate(){return new x(this.px,n.neg(this.py),this.pz)}double(){const{a:m,b:B}=t,S=n.mul(B,no),{px:O,py:P,pz:F}=this;let E=n.ZERO,w=n.ZERO,I=n.ZERO,$=n.mul(O,O),D=n.mul(P,P),N=n.mul(F,F),U=n.mul(O,P);return U=n.add(U,U),I=n.mul(O,F),I=n.add(I,I),E=n.mul(m,I),w=n.mul(S,N),w=n.add(E,w),E=n.sub(D,w),w=n.add(D,w),w=n.mul(E,w),E=n.mul(U,E),I=n.mul(S,I),N=n.mul(m,N),U=n.sub($,N),U=n.mul(m,U),U=n.add(U,I),I=n.add($,$),$=n.add(I,$),$=n.add($,N),$=n.mul($,U),w=n.add(w,$),N=n.mul(P,F),N=n.add(N,N),$=n.mul(N,U),E=n.sub(E,$),I=n.mul(N,D),I=n.add(I,I),I=n.add(I,I),new x(E,w,I)}add(m){_(m);const{px:B,py:S,pz:O}=this,{px:P,py:F,pz:E}=m;let w=n.ZERO,I=n.ZERO,$=n.ZERO;const D=t.a,N=n.mul(t.b,no);let U=n.mul(B,P),L=n.mul(S,F),j=n.mul(O,E),V=n.add(B,S),K=n.add(P,F);V=n.mul(V,K),K=n.add(U,L),V=n.sub(V,K),K=n.add(B,O);let H=n.add(P,E);return K=n.mul(K,H),H=n.add(U,j),K=n.sub(K,H),H=n.add(S,O),w=n.add(F,E),H=n.mul(H,w),w=n.add(L,j),H=n.sub(H,w),$=n.mul(D,K),w=n.mul(N,j),$=n.add(w,$),w=n.sub(L,$),$=n.add(L,$),I=n.mul(w,$),L=n.add(U,U),L=n.add(L,U),j=n.mul(D,j),K=n.mul(N,K),L=n.add(L,j),j=n.sub(U,j),j=n.mul(D,j),K=n.add(K,j),U=n.mul(L,K),I=n.add(I,U),U=n.mul(H,K),w=n.mul(V,w),w=n.sub(w,U),U=n.mul(V,L),$=n.mul(H,$),$=n.add($,U),new x(w,I,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(x.ZERO)}multiply(m){const{endo:B}=e;if(!r.isValidNot0(m))throw new Error("invalid scalar: out of range");let S,O;const P=F=>R.wNAFCached(this,F,x.normalizeZ);if(B){const{k1neg:F,k1:E,k2neg:w,k2:I}=B.splitScalar(m),{p:$,f:D}=P(E),{p:N,f:U}=P(I);O=D.add(U),S=v(B.beta,$,N,F,w)}else{const{p:F,f:E}=P(m);S=F,O=E}return x.normalizeZ([S,O])[0]}multiplyUnsafe(m){const{endo:B}=e,S=this;if(!r.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ti||S.is0())return x.ZERO;if(m===Bi)return S;if(R.hasPrecomputes(this))return this.multiply(m);if(B){const{k1neg:O,k1:P,k2neg:F,k2:E}=B.splitScalar(m),{p1:w,p2:I}=N8(x,S,P,E);return v(B.beta,w,I,O,F)}else return R.wNAFCachedUnsafe(S,m)}multiplyAndAddUnsafe(m,B,S){const O=this.multiplyUnsafe(B).add(m.multiplyUnsafe(S));return O.is0()?void 0:O}toAffine(m){return A(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return i===Bi?!0:m?m(x,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:m}=e;return i===Bi?this:m?m(x,this):this.multiplyUnsafe(i)}toBytes(m=!0){return Ys("isCompressed",m),this.assertValidity(),l(x,this,m)}toRawBytes(m=!0){return this.toBytes(m)}toHex(m=!0){return Ii(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}x.BASE=new x(t.Gx,t.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=r;const T=r.BITS,R=R8(x,e.endo?Math.ceil(T/2):T);return x}function Ep(t){return Uint8Array.of(t?2:3)}function J8(t,e,n={}){eo(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=e.randomBytes||$r,i=e.hmac||((S,...O)=>Ws(e.hash,S,sr(...O))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o;function u(S){const O=a>>Bi;return S>O}function l(S){return u(S)?o.neg(S):S}function h(S,O){if(!o.isValidNot0(O))throw new Error(`invalid signature ${S}: out of range 1..CURVE.n`)}class f{constructor(O,P,F){h("r",O),h("s",P),this.r=O,this.s=P,F!=null&&(this.recovery=F),Object.freeze(this)}static fromCompact(O){const P=o.BYTES,F=nt("compactSignature",O,P*2);return new f(o.fromBytes(F.subarray(0,P)),o.fromBytes(F.subarray(P,P*2)))}static fromDER(O){const{r:P,s:F}=an.toSig(nt("DER",O));return new f(P,F)}assertValidity(){}addRecoveryBit(O){return new f(this.r,this.s,O)}recoverPublicKey(O){const P=s.ORDER,{r:F,s:E,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*W8<P&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");const I=w===2||w===3?F+a:F;if(!s.isValid(I))throw new Error("recovery id 2 or 3 invalid");const $=s.toBytes(I),D=t.fromHex(sr(Ep((w&1)===0),$)),N=o.inv(I),U=b(nt("msgHash",O)),L=o.create(-U*N),j=o.create(E*N),V=t.BASE.multiplyUnsafe(L).add(D.multiplyUnsafe(j));if(V.is0())throw new Error("point at infinify");return V.assertValidity(),V}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o.neg(this.s),this.recovery):this}toBytes(O){if(O==="compact")return sr(o.toBytes(this.r),o.toBytes(this.s));if(O==="der")return lc(an.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ii(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ii(this.toBytes("compact"))}}const p=vp(o,n.allowedPrivateKeyLengths,n.wrapPrivateKey),d={isValidPrivateKey(S){try{return p(S),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const S=a;return T8(r(hp(S)),S)},precompute(S=8,O=t.BASE){return O.precompute(S,!1)}};function g(S,O=!0){return t.fromPrivateKey(S).toBytes(O)}function y(S){if(typeof S=="bigint")return!1;if(S instanceof t)return!0;const O=nt("key",S).length,P=s.BYTES,F=P+1,E=2*P+1;if(!(n.allowedPrivateKeyLengths||o.BYTES===F))return O===F||O===E}function _(S,O,P=!0){if(y(S)===!0)throw new Error("first arg must be private key");if(y(O)===!1)throw new Error("second arg must be public key");return t.fromHex(O).multiply(p(S)).toBytes(P)}const A=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");const O=Js(S),P=S.length*8-c;return P>0?O>>BigInt(P):O},b=e.bits2int_modN||function(S){return o.create(A(S))},v=Qs(c);function x(S){return Dc("num < 2^"+c,S,Ti,v),o.toBytes(S)}function T(S,O,P=R){if(["recovered","canonical"].some(V=>V in P))throw new Error("sign() legacy options not supported");const{hash:F}=e;let{lowS:E,prehash:w,extraEntropy:I}=P;E==null&&(E=!0),S=nt("msgHash",S),bp(P),w&&(S=nt("prehashed msgHash",F(S)));const $=b(S),D=p(O),N=[x(D),x($)];if(I!=null&&I!==!1){const V=I===!0?r(s.BYTES):I;N.push(nt("extraEntropy",V))}const U=sr(...N),L=$;function j(V){const K=A(V);if(!o.isValidNot0(K))return;const H=o.inv(K),Z=t.BASE.multiply(K).toAffine(),Q=o.create(Z.x);if(Q===Ti)return;const W=o.create(H*o.create(L+Q*D));if(W===Ti)return;let ae=(Z.x===Q?0:2)|Number(Z.y&Bi),ye=W;return E&&u(W)&&(ye=l(W),ae^=1),new f(Q,ye,ae)}return{seed:U,k2sig:j}}const R={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function m(S,O,P=R){const{seed:F,k2sig:E}=T(S,O,P);return E8(e.hash.outputLen,o.BYTES,i)(F,E)}t.BASE.precompute(8);function B(S,O,P,F=C){const E=S;O=nt("msgHash",O),P=nt("publicKey",P),bp(F);const{lowS:w,prehash:I,format:$}=F;if("strict"in F)throw new Error("options.strict was renamed to lowS");if($!==void 0&&!["compact","der","js"].includes($))throw new Error('format must be "compact", "der" or "js"');const D=typeof E=="string"||oc(E),N=!D&&!$&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!D&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,L;try{if(N)if($===void 0||$==="js")U=new f(E.r,E.s);else throw new Error("invalid format");if(D){try{$!=="compact"&&(U=f.fromDER(E))}catch(ae){if(!(ae instanceof an.Err))throw ae}!U&&$!=="der"&&(U=f.fromCompact(E))}L=t.fromHex(P)}catch{return!1}if(!U||w&&U.hasHighS())return!1;I&&(O=e.hash(O));const{r:j,s:V}=U,K=b(O),H=o.inv(V),Z=o.create(K*H),Q=o.create(j*H),W=t.BASE.multiplyUnsafe(Z).add(L.multiplyUnsafe(Q));return W.is0()?!1:o.create(W.x)===j}return Object.freeze({getPublicKey:g,getSharedSecret:_,sign:m,verify:B,utils:d,Point:t,Signature:f})}function X8(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=Br(e.n,t.nBitLength),i={Fp:n,Fn:r,allowedPrivateKeyLengths:t.allowedPrivateKeyLengths,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,wrapPrivateKey:t.wrapPrivateKey,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function Q8(t){const{CURVE:e,curveOpts:n}=X8(t),r={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,ecdsaOpts:r}}function eI(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function tI(t){const{CURVE:e,curveOpts:n,ecdsaOpts:r}=Q8(t),i=Z8(e,n),s=J8(i,r,n);return eI(t,s)}function Pc(t,e){const n=r=>tI({...t,hash:r});return{...n(e),create:n}}const xp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},_p={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ip={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},nI=Br(xp.p),rI=Br(_p.p),iI=Br(Ip.p),sI=Pc({...xp,Fp:nI,lowS:!1},js);Pc({..._p,Fp:rI,lowS:!1},f_),Pc({...Ip,Fp:iI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},h_);const oI=sI,Sp="base10",Ye="base16",it="base64pad",kn="base64url",Pi="utf8",Ap=0,cn=1,Ci=2,aI=0,Dp=1,Ri=12,Cc=32;function cI(){const t=Bc.utils.randomPrivateKey(),e=Bc.getPublicKey(t);return{privateKey:et(t,Ye),publicKey:et(e,Ye)}}function Rc(){const t=$r(Cc);return et(t,Ye)}function uI(t,e){const n=Bc.getSharedSecret(bt(t,Ye),bt(e,Ye)),r=m8(Gs,n,void 0,void 0,Cc);return et(r,Ye)}function ro(t){const e=Gs(bt(t,Ye));return et(e,Ye)}function _t(t){const e=Gs(bt(t,Pi));return et(e,Ye)}function Op(t){return bt(`${t}`,Sp)}function ur(t){return Number(et(t,Sp))}function $p(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Tp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function lI(t){const e=Op(typeof t.type<"u"?t.type:Ap);if(ur(e)===cn&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?bt(t.senderPublicKey,Ye):void 0,r=typeof t.iv<"u"?bt(t.iv,Ye):$r(Ri),i=bt(t.symKey,Ye),s=Xd(i,r).encrypt(bt(t.message,Pi)),o=Bp({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===kn?$p(o):o}function hI(t){const e=bt(t.symKey,Ye),{sealed:n,iv:r}=Ni({encoded:t.encoded,encoding:t.encoding}),i=Xd(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return et(i,Pi)}function fI(t,e){const n=Op(Ci),r=$r(Ri),i=bt(t,Pi),s=Bp({type:n,sealed:i,iv:r});return e===kn?$p(s):s}function dI(t,e){const{sealed:n}=Ni({encoded:t,encoding:e});return et(n,Pi)}function Bp(t){if(ur(t.type)===Ci)return et(gi([t.type,t.sealed]),it);if(ur(t.type)===cn){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return et(gi([t.type,t.senderPublicKey,t.iv,t.sealed]),it)}return et(gi([t.type,t.iv,t.sealed]),it)}function Ni(t){const e=(t.encoding||it)===kn?Tp(t.encoded):t.encoded,n=bt(e,it),r=n.slice(aI,Dp),i=Dp;if(ur(r)===cn){const c=i+Cc,u=c+Ri,l=n.slice(i,c),h=n.slice(c,u),f=n.slice(u);return{type:r,sealed:f,iv:h,senderPublicKey:l}}if(ur(r)===Ci){const c=n.slice(i),u=$r(Ri);return{type:r,sealed:c,iv:u}}const s=i+Ri,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function pI(t,e){const n=Ni({encoded:t,encoding:e?.encoding});return Pp({type:ur(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?et(n.senderPublicKey,Ye):void 0,receiverPublicKey:e?.receiverPublicKey})}function Pp(t){const e=t?.type||Ap;if(e===cn){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 Cp(t){return t.type===cn&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Rp(t){return t.type===Ci}function gI(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return gi([new Uint8Array([4]),e,n])}function yI(t,e){const[n,r,i]=t.split("."),s=Buffer.from(Tp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,u=Gs(c),l=gI(e);if(!oI.verify(gi([o,a]),u,l))throw new Error("Invalid signature");return Qo(t).payload}const wI="irn";function io(t){return t?.relay||{protocol:wI}}function Rr(t){const e=H3[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function mI(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=t[i];n[s]=o}}),n}function Np(t){if(!t.includes("wc:")){const u=gd(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,n).split("@"),s=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(s),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:bI(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:mI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function bI(t){return t.startsWith("//")?t.substring(2):t}function vI(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(i=>{const s=i,o=n+e+s;t[s]&&(r[o]=t[s])}),r}function Up(t){const e=new URLSearchParams,n=vI(t.relay);Object.keys(n).sort().forEach(i=>{e.set(i,n[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function so(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var EI=Object.defineProperty,xI=Object.defineProperties,_I=Object.getOwnPropertyDescriptors,Fp=Object.getOwnPropertySymbols,II=Object.prototype.hasOwnProperty,SI=Object.prototype.propertyIsEnumerable,kp=(t,e,n)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,AI=(t,e)=>{for(var n in e||(e={}))II.call(e,n)&&kp(t,n,e[n]);if(Fp)for(var n of Fp(e))SI.call(e,n)&&kp(t,n,e[n]);return t},DI=(t,e)=>xI(t,_I(e));function Nr(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function OI(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Nr(n.accounts))}),e}function $I(t,e){const n=[];return Object.values(t).forEach(r=>{Nr(r.accounts).includes(e)&&n.push(...r.methods)}),n}function TI(t,e){const n=[];return Object.values(t).forEach(r=>{Nr(r.accounts).includes(e)&&n.push(...r.events)}),n}function Lp(t){return t.includes(":")}function BI(t){return Lp(t)?t.split(":")[0]:t}function Mp(t){var e,n,r;const i={};if(!Ui(t))return i;for(const[s,o]of Object.entries(t)){const a=Lp(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=BI(s);i[l]=DI(AI({},i[l]),{chains:ir(a,(e=i[l])==null?void 0:e.chains),methods:ir(c,(n=i[l])==null?void 0:n.methods),events:ir(u,(r=i[l])==null?void 0:r.events)})}return i}function PI(t){const e={};return t?.forEach(n=>{var r;const[i,s]=n.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(n),(r=e[i].chains)==null||r.push(`${i}:${s}`)}),e}function zp(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=PI(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=ir(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function CI(t,e){var n,r,i,s,o,a;const c=Mp(t),u=Mp(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:ir((n=c[f])==null?void 0:n.chains,(r=u[f])==null?void 0:r.chains),methods:ir((i=c[f])==null?void 0:i.methods,(s=u[f])==null?void 0:s.methods),events:ir((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}const RI={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}},NI={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function z(t,e){const{message:n,code:r}=NI[t];return{message:e?`${n} ${e}`:n,code:r}}function fe(t,e){const{message:n,code:r}=RI[t];return{message:e?`${n} ${e}`:n,code:r}}function Ur(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ui(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function we(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function Nc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function UI(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return nr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Nr(a),h=n[o];(!nr(id(o,h),l)||!nr(h.methods,c)||!nr(h.events,u))&&(s=!1)}),s):!1}function Fi(t){return we(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function FI(t){if(we(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Fi(n)}}return!1}function kI(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(we(t,!1)){if(e(t))return!0;const n=gd(t);return e(n)}}catch{}return!1}function LI(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function MI(t){return t?.topic}function zI(t,e){let n=null;return we(t?.publicKey,!1)||(n=z("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function qp(t){let e=!0;return Ur(t)?t.length&&(e=t.every(n=>we(n,!1))):e=!1,e}function qI(t,e,n){let r=null;return Ur(e)&&e.length?e.forEach(i=>{r||Fi(i)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Fi(t)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function jI(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=qI(i,id(i,s),`${e} ${n}`);o&&(r=o)}),r}function VI(t,e){let n=null;return Ur(t)?t.forEach(r=>{n||FI(r)||(n=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function KI(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=VI(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function HI(t,e){let n=null;return qp(t?.methods)?qp(t?.events)||(n=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function jp(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=HI(r,`${e}, namespace`);i&&(n=i)}),n}function WI(t,e,n){let r=null;if(t&&Ui(t)){const i=jp(t,e);i&&(r=i);const s=jI(t,e,n);s&&(r=s)}else r=z("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function Uc(t,e){let n=null;if(t&&Ui(t)){const r=jp(t,e);r&&(n=r);const i=KI(t,e);i&&(n=i)}else n=z("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function Vp(t){return we(t.protocol,!0)}function GI(t,e){let n=!1;return e&&!t?n=!0:t&&Ur(t)&&t.length&&t.forEach(r=>{n=Vp(r)}),n}function YI(t){return typeof t=="number"}function st(t){return typeof t<"u"&&typeof t!==null}function ZI(t){return!(!t||typeof t!="object"||!t.code||!Nc(t.code,!1)||!t.message||!we(t.message,!1))}function JI(t){return!(_e(t)||!we(t.method,!1))}function XI(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!Nc(t.id,!1)||!we(t.jsonrpc,!1))}function QI(t){return!(_e(t)||!we(t.name,!1))}function Kp(t,e){return!(!Fi(e)||!OI(t).includes(e))}function eS(t,e,n){return we(n,!1)?$I(t,e).includes(n):!1}function tS(t,e,n){return we(n,!1)?TI(t,e).includes(n):!1}function Hp(t,e,n){let r=null;const i=nS(t),s=rS(e),o=Object.keys(i),a=Object.keys(s),c=Wp(Object.keys(t)),u=Wp(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
23
23
  Required: ${l.toString()}
24
- Received: ${Object.keys(e).toString()}`)),sr(o,a)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
24
+ Received: ${Object.keys(e).toString()}`)),nr(o,a)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
25
25
  Required: ${o.toString()}
26
- Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||r)return;const h=Hr(e[f].accounts);h.includes(f)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${f}
27
- Required: ${f}
28
- Approved: ${h.toString()}`))}),o.forEach(f=>{r||(sr(i[f].methods,s[f].methods)?sr(i[f].events,s[f].events)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${f}`)):r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${f}`))}),r}function jS(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(i=>{e[i]={methods:t[n].methods,events:t[n].events}})}),e}function yg(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function qS(t){const e={};return Object.keys(t).forEach(n=>{if(n.includes(":"))e[n]=t[n];else{const r=Hr(t[n].accounts);r?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}}),e}function zS(t,e){return jc(t,!1)&&t<=e.max&&t>=e.min}function wg(){const t=Di();return new Promise(e=>{switch(t){case gt.browser:e(KS());break;case gt.reactNative:e(VS());break;case gt.node:e(HS());break;default:e(!0)}})}function KS(){return Fr()&&navigator?.onLine}async function VS(){if(Sn()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t?.isConnected}return!0}function HS(){return!0}function WS(t){switch(Di()){case gt.browser:GS(t);break;case gt.reactNative:ZS(t);break}}function GS(t){!Sn()&&Fr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function ZS(t){Sn()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function YS(){var t;return Fr()&&Xn()?((t=Xn())==null?void 0:t.visibilityState)==="visible":!0}const zc={};class ji{static get(e){return zc[e]}static set(e,n){zc[e]=n}static delete(e){delete zc[e]}}function XS(t){const e=pi.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function JS({publicKey:t,signature:e,payload:n}){var r;const i=Kc(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=t6(n.address),a=n.era==="00"?new Uint8Array([0]):Kc(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${e6(n.tip)}`),f=r6(l),h=new Uint8Array([0,...t,o,...e,...a,...u,...f,...i]),d=n6(h.length+1);return new Uint8Array([...d,s,...h])}function QS(t){const e=Kc(t),n=P_.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function Kc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function e6(t){return t.startsWith("0x")?t.slice(2):t}function t6(t){const e=pi.decode(t)[0];return e===42?0:e===60?2:1}function n6(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function r6(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function i6(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=XS(t.transaction.address),r=JS({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return QS(i)}const s6="PARSE_ERROR",o6="INVALID_REQUEST",a6="METHOD_NOT_FOUND",c6="INVALID_PARAMS",bg="INTERNAL_ERROR",Vc="SERVER_ERROR",u6=[-32700,-32600,-32601,-32602,-32603],qi={[s6]:{code:-32700,message:"Parse error"},[o6]:{code:-32600,message:"Invalid Request"},[a6]:{code:-32601,message:"Method not found"},[c6]:{code:-32602,message:"Invalid params"},[bg]:{code:-32603,message:"Internal error"},[Vc]:{code:-32e3,message:"Server error"}},mg=Vc;function l6(t){return u6.includes(t)}function vg(t){return Object.keys(qi).includes(t)?qi[t]:qi[mg]}function h6(t){const e=Object.values(qi).find(n=>n.code===t);return e||qi[mg]}function f6(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var Eg={};/*! *****************************************************************************
26
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const f=Nr(e[h].accounts);f.includes(h)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${h}
27
+ Required: ${h}
28
+ Approved: ${f.toString()}`))}),o.forEach(h=>{r||(nr(i[h].methods,s[h].methods)?nr(i[h].events,s[h].events)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${h}`)):r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function nS(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(i=>{e[i]={methods:t[n].methods,events:t[n].events}})}),e}function Wp(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function rS(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:Nr(t[n].accounts)?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}),e}function iS(t,e){return Nc(t,!1)&&t<=e.max&&t>=e.min}function Gp(){const t=vi();return new Promise(e=>{switch(t){case ft.browser:e(sS());break;case ft.reactNative:e(oS());break;case ft.node:e(aS());break;default:e(!0)}})}function sS(){return Dr()&&navigator?.onLine}async function oS(){return Sn()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function aS(){return!0}function cS(t){switch(vi()){case ft.browser:uS(t);break;case ft.reactNative:lS(t);break}}function uS(t){!Sn()&&Dr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function lS(t){Sn()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function hS(){var t;return Dr()&&Yn()?((t=Yn())==null?void 0:t.visibilityState)==="visible":!0}const Fc={};class ki{static get(e){return Fc[e]}static set(e,n){Fc[e]=n}static delete(e){delete Fc[e]}}function fS(t){const e=ui.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function dS({publicKey:t,signature:e,payload:n}){var r;const i=kc(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=yS(n.address),a=n.era==="00"?new Uint8Array([0]):kc(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${gS(n.tip)}`),h=mS(l),f=new Uint8Array([0,...t,o,...e,...a,...u,...h,...i]),p=wS(f.length+1);return new Uint8Array([...p,s,...f])}function pS(t){const e=kc(t),n=ix.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function kc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function gS(t){return t.startsWith("0x")?t.slice(2):t}function yS(t){const e=ui.decode(t)[0];return e===42?0:e===60?2:1}function wS(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function mS(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function bS(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=fS(t.transaction.address),r=dS({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return pS(i)}const vS="PARSE_ERROR",ES="INVALID_REQUEST",xS="METHOD_NOT_FOUND",_S="INVALID_PARAMS",Yp="INTERNAL_ERROR",Lc="SERVER_ERROR",IS=[-32700,-32600,-32601,-32602,-32603],Li={[vS]:{code:-32700,message:"Parse error"},[ES]:{code:-32600,message:"Invalid Request"},[xS]:{code:-32601,message:"Method not found"},[_S]:{code:-32602,message:"Invalid params"},[Yp]:{code:-32603,message:"Internal error"},[Lc]:{code:-32e3,message:"Server error"}},Zp=Lc;function SS(t){return IS.includes(t)}function Jp(t){return Object.keys(Li).includes(t)?Li[t]:Li[Zp]}function AS(t){const e=Object.values(Li).find(n=>n.code===t);return e||Li[Zp]}function DS(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var Xp={};/*! *****************************************************************************
29
29
  Copyright (c) Microsoft Corporation.
30
30
 
31
31
  Permission to use, copy, modify, and/or distribute this software for any
@@ -38,5 +38,5 @@ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Rx(n)).toStr
38
38
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
39
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
40
  PERFORMANCE OF THIS SOFTWARE.
41
- ***************************************************************************** */var Hc=function(t,e){return Hc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Hc(t,e)};function d6(t,e){Hc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Wc=function(){return Wc=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Wc.apply(this,arguments)};function p6(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function g6(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function y6(t,e){return function(n,r){e(n,r,t)}}function w6(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function b6(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function m6(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function v6(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function E6(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Gc(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function _g(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function _6(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(_g(arguments[e]));return t}function x6(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function zi(t){return this instanceof zi?(this.v=t,this):new zi(t)}function I6(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(r[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof zi?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function S6(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:zi(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function D6(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Gc=="function"?Gc(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function A6(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function O6(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function $6(t){return t&&t.__esModule?t:{default:t}}function B6(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function T6(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var P6=Object.freeze({__proto__:null,__extends:d6,get __assign(){return Wc},__rest:p6,__decorate:g6,__param:y6,__metadata:w6,__awaiter:b6,__generator:m6,__createBinding:v6,__exportStar:E6,__values:Gc,__read:_g,__spread:_6,__spreadArrays:x6,__await:zi,__asyncGenerator:I6,__asyncDelegator:S6,__asyncValues:D6,__makeTemplateObject:A6,__importStar:O6,__importDefault:$6,__classPrivateFieldGet:B6,__classPrivateFieldSet:T6}),R6=mu(P6),hn={},xg;function C6(){if(xg)return hn;xg=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.isBrowserCryptoAvailable=hn.getSubtleCrypto=hn.getBrowerCrypto=void 0;function t(){return kt?.crypto||kt?.msCrypto||{}}hn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}hn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return hn.isBrowserCryptoAvailable=n,hn}var fn={},Ig;function N6(){if(Ig)return fn;Ig=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.isBrowser=fn.isNode=fn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}fn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}fn.isNode=e;function n(){return!t()&&!e()}return fn.isBrowser=n,fn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=R6;e.__exportStar(C6(),t),e.__exportStar(N6(),t)})(Eg);function ct(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function jn(t=6){return BigInt(ct(t))}function dn(t,e,n){return{id:n||ct(),jsonrpc:"2.0",method:t,params:e}}function yo(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Zc(t,e,n){return{id:t,jsonrpc:"2.0",error:U6(e,n)}}function U6(t,e){return typeof t>"u"?vg(bg):(typeof t=="string"&&(t=Object.assign(Object.assign({},vg(Vc)),{message:t})),typeof e<"u"&&(t.data=e),l6(t.code)&&(t=h6(t.code)),t)}class F6{}class k6 extends F6{constructor(){super()}}class L6 extends k6{constructor(e){super()}}const M6="^wss?:";function j6(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function q6(t,e){const n=j6(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function Sg(t){return q6(t,M6)}function z6(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Dg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yc(t){return Dg(t)&&"method"in t}function wo(t){return Dg(t)&&(Ht(t)||Dt(t))}function Ht(t){return"result"in t}function Dt(t){return"error"in t}class K6 extends L6{constructor(e){super(e),this.events=new He.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(dn(e.method,e.params||[],e.id||jn().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Dt(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),wo(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 V6=()=>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"),H6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Ag=t=>t.split("?")[0],Og=10,W6=V6();class G6{constructor(e){if(this.url=e,this.events=new He.exports.EventEmitter,this.registering=!1,!Sg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Gn(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Sg(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=Eg.isReactNative()?void 0:{rejectUnauthorized:!z6(e)},s=new W6(e,[],i);H6()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?mr(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Zc(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return f6(e,Ag(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Og&&this.events.setMaxListeners(Og)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Ag(this.url)}`));return this.events.emit("register_error",n),n}}var Z6=Object.defineProperty,$g=Object.getOwnPropertySymbols,Y6=Object.prototype.hasOwnProperty,X6=Object.prototype.propertyIsEnumerable,Bg=(t,e,n)=>e in t?Z6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Je=(t,e)=>{for(var n in e||(e={}))Y6.call(e,n)&&Bg(t,n,e[n]);if($g)for(var n of $g(e))X6.call(e,n)&&Bg(t,n,e[n]);return t};const Tg="wc",Pg=2,bo="core",Wt=`${Tg}@2:${bo}:`,J6={name:bo,logger:"error"},Q6={database:":memory:"},e4="crypto",Rg="client_ed25519_seed",t4=M.ONE_DAY,n4="keychain",r4="0.3",i4="messages",s4="0.3",o4=M.SIX_HOURS,a4="publisher",Cg="irn",c4="error",Ng="wss://relay.walletconnect.org",u4="relayer",ge={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"},l4="_subscription",At={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},h4=.1,Xc="2.21.8",le={link_mode:"link_mode",relay:"relay"},mo={inbound:"inbound",outbound:"outbound"},f4="0.3",d4="WALLETCONNECT_CLIENT_ID",Ug="WALLETCONNECT_LINK_MODE_APPS",wt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},p4="subscription",g4="0.3",y4="pairing",w4="0.3",Ki={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},pr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ut={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},b4="history",m4="0.3",v4="expirer",Ot={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},E4="0.3",_4="verify-api",x4="https://verify.walletconnect.com",Fg="https://verify.walletconnect.org",Vi=Fg,I4=`${Vi}/v3`,S4=[x4,Fg],D4="echo",A4="https://echo.walletconnect.com",Gt={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"},pn={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"},qn={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"},Hi={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"},gr={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"},Wi={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"},O4=.1,$4="event-client",B4=86400,T4="https://pulse.walletconnect.org/batch";function P4(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var R4=P4,C4=R4;const kg=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")},N4=t=>new TextEncoder().encode(t),U4=t=>new TextDecoder().decode(t);class F4{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class k4{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Lg(this,e)}}class L4{constructor(e){this.decoders=e}or(e){return Lg(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Lg=(t,e)=>new L4(Je(Je({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class M4{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new F4(e,n,r),this.decoder=new k4(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const vo=({name:t,prefix:e,encode:n,decode:r})=>new M4(t,e,n,r),Gi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=C4(n,e);return vo({prefix:t,name:e,encode:r,decode:s=>kg(i(s))})},j4=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},q4=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Be=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>vo({prefix:e,name:t,encode(i){return q4(i,r,n)},decode(i){return j4(i,r,n,t)}}),z4=vo({prefix:"\0",name:"identity",encode:t=>U4(t),decode:t=>N4(t)});var K4=Object.freeze({__proto__:null,identity:z4});const V4=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var H4=Object.freeze({__proto__:null,base2:V4});const W4=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var G4=Object.freeze({__proto__:null,base8:W4});const Z4=Gi({prefix:"9",name:"base10",alphabet:"0123456789"});var Y4=Object.freeze({__proto__:null,base10:Z4});const X4=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),J4=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Q4=Object.freeze({__proto__:null,base16:X4,base16upper:J4});const eD=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),tD=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nD=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),rD=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),iD=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),sD=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),oD=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),aD=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),cD=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var uD=Object.freeze({__proto__:null,base32:eD,base32upper:tD,base32pad:nD,base32padupper:rD,base32hex:iD,base32hexupper:sD,base32hexpad:oD,base32hexpadupper:aD,base32z:cD});const lD=Gi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),hD=Gi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var fD=Object.freeze({__proto__:null,base36:lD,base36upper:hD});const dD=Gi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),pD=Gi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var gD=Object.freeze({__proto__:null,base58btc:dD,base58flickr:pD});const yD=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),wD=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),bD=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),mD=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var vD=Object.freeze({__proto__:null,base64:yD,base64pad:wD,base64url:bD,base64urlpad:mD});const Mg=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}"),ED=Mg.reduce((t,e,n)=>(t[n]=e,t),[]),_D=Mg.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function xD(t){return t.reduce((e,n)=>(e+=ED[n],e),"")}function ID(t){const e=[];for(const n of t){const r=_D[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const SD=vo({prefix:"\u{1F680}",name:"base256emoji",encode:xD,decode:ID});var DD=Object.freeze({__proto__:null,base256emoji:SD}),AD=qg,jg=128,OD=127,$D=~OD,BD=Math.pow(2,31);function qg(t,e,n){e=e||[],n=n||0;for(var r=n;t>=BD;)e[n++]=t&255|jg,t/=128;for(;t&$D;)e[n++]=t&255|jg,t>>>=7;return e[n]=t|0,qg.bytes=n-r+1,e}var TD=Jc,PD=128,zg=127;function Jc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Jc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&zg)<<i:(o&zg)*Math.pow(2,i),i+=7}while(o>=PD);return Jc.bytes=s-r,n}var RD=Math.pow(2,7),CD=Math.pow(2,14),ND=Math.pow(2,21),UD=Math.pow(2,28),FD=Math.pow(2,35),kD=Math.pow(2,42),LD=Math.pow(2,49),MD=Math.pow(2,56),jD=Math.pow(2,63),qD=function(t){return t<RD?1:t<CD?2:t<ND?3:t<UD?4:t<FD?5:t<kD?6:t<LD?7:t<MD?8:t<jD?9:10},zD={encode:AD,decode:TD,encodingLength:qD},Kg=zD;const Vg=(t,e,n=0)=>(Kg.encode(t,e,n),e),Hg=t=>Kg.encodingLength(t),Qc=(t,e)=>{const n=e.byteLength,r=Hg(t),i=r+Hg(n),s=new Uint8Array(i+n);return Vg(t,s,0),Vg(n,s,r),s.set(e,i),new KD(t,n,e,s)};class KD{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Wg=({name:t,code:e,encode:n})=>new VD(t,e,n);class VD{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Qc(this.code,n):n.then(r=>Qc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Gg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),HD=Wg({name:"sha2-256",code:18,encode:Gg("SHA-256")}),WD=Wg({name:"sha2-512",code:19,encode:Gg("SHA-512")});var GD=Object.freeze({__proto__:null,sha256:HD,sha512:WD});const Zg=0,ZD="identity",Yg=kg;var YD=Object.freeze({__proto__:null,identity:{code:Zg,name:ZD,encode:Yg,digest:t=>Qc(Zg,Yg(t))}});new TextEncoder,new TextDecoder;const Xg=Je(Je(Je(Je(Je(Je(Je(Je(Je(Je({},K4),H4),G4),Y4),Q4),uD),fD),gD),vD),DD);Je(Je({},GD),YD);function Jg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function XD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Jg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Qg(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const e0=Qg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),eu=Qg("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=XD(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),JD=Je({utf8:e0,"utf-8":e0,hex:Xg.base16,latin1:eu,ascii:eu,binary:eu},Xg);function QD(t,e="utf8"){const n=JD[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Jg(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var eA=Object.defineProperty,tA=(t,e,n)=>e in t?eA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zt=(t,e,n)=>tA(t,typeof e!="symbol"?e+"":e,n);class nA{constructor(e,n){this.core=e,this.logger=n,Zt(this,"keychain",new Map),Zt(this,"name",n4),Zt(this,"version",r4),Zt(this,"initialized",!1),Zt(this,"storagePrefix",Wt),Zt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Zt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Zt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Zt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=j("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),Zt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=We(n,this.name)}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,sc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?oc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rA=Object.defineProperty,iA=(t,e,n)=>e in t?rA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>iA(t,typeof e!="symbol"?e+"":e,n);class sA{constructor(e,n,r){this.core=e,this.logger=n,Te(this,"name",e4),Te(this,"keychain"),Te(this,"randomSessionIdentifier",Lc()),Te(this,"initialized",!1),Te(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Te(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Te(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Ql(i);return Jl(s.publicKey)}),Te(this,"generateKeyPair",()=>{this.isInitialized();const i=jI();return this.setPrivateKey(i.publicKey,i.privateKey)}),Te(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Ql(s),a=this.randomSessionIdentifier;return await Cm(a,i,t4,o)}),Te(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=qI(a,s);return this.setSymKey(c,o)}),Te(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||fo(i);return await this.keychain.set(o,i),o}),Te(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Qp(o),c=Gn(s);if(tg(a))return VI(c,o?.encoding);if(eg(a)){const h=a.senderPublicKey,d=a.receiverPublicKey;i=await this.generateSharedKey(h,d)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return zI({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Te(this,"decode",async(i,s,o)=>{this.isInitialized();const a=WI(s,o);if(tg(a)){const c=HI(s,o?.encoding);return mr(c)}if(eg(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=KI({symKey:c,encoded:s,encoding:o?.encoding});return mr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Te(this,"getPayloadType",(i,s=ot)=>{const o=ki({encoded:i,encoding:s});return dr(o.type)}),Te(this,"getPayloadSenderPublicKey",(i,s=ot)=>{const o=ki({encoded:i,encoding:s});return o.senderPublicKey?rt(o.senderPublicKey,Xe):void 0}),this.core=e,this.logger=We(n,this.name),this.keychain=r||new nA(this.core,this.logger)}get context(){return et(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Rg)}catch{e=Lc(),await this.keychain.set(Rg,e)}return QD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var oA=Object.defineProperty,aA=Object.defineProperties,cA=Object.getOwnPropertyDescriptors,t0=Object.getOwnPropertySymbols,uA=Object.prototype.hasOwnProperty,lA=Object.prototype.propertyIsEnumerable,tu=(t,e,n)=>e in t?oA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,hA=(t,e)=>{for(var n in e||(e={}))uA.call(e,n)&&tu(t,n,e[n]);if(t0)for(var n of t0(e))lA.call(e,n)&&tu(t,n,e[n]);return t},fA=(t,e)=>aA(t,cA(e)),bt=(t,e,n)=>tu(t,typeof e!="symbol"?e+"":e,n);class dA extends Rw{constructor(e,n){super(e,n),this.logger=e,this.core=n,bt(this,"messages",new Map),bt(this,"messagesWithoutClientAck",new Map),bt(this,"name",i4),bt(this,"version",s4),bt(this,"initialized",!1),bt(this,"storagePrefix",Wt),bt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),bt(this,"set",async(r,i,s)=>{this.isInitialized();const o=St(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===mo.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,fA(hA({},c),{[o]:i}))}return await this.persist(),o}),bt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),bt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),bt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=St(i);return typeof s[o]<"u"}),bt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),bt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=We(e,this.name),this.core=n}get context(){return et(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,sc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,sc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?oc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?oc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pA=Object.defineProperty,gA=Object.defineProperties,yA=Object.getOwnPropertyDescriptors,n0=Object.getOwnPropertySymbols,wA=Object.prototype.hasOwnProperty,bA=Object.prototype.propertyIsEnumerable,nu=(t,e,n)=>e in t?pA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gr=(t,e)=>{for(var n in e||(e={}))wA.call(e,n)&&nu(t,n,e[n]);if(n0)for(var n of n0(e))bA.call(e,n)&&nu(t,n,e[n]);return t},r0=(t,e)=>gA(t,yA(e)),$t=(t,e,n)=>nu(t,typeof e!="symbol"?e+"":e,n);class mA extends Cw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,$t(this,"events",new He.exports.EventEmitter),$t(this,"name",a4),$t(this,"queue",new Map),$t(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),$t(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),$t(this,"needsTransportRestart",!1),$t(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const f=s?.ttl||o4,h=s?.prompt||!1,d=s?.tag||0,p=s?.id||jn().toString(),g=Vr(po().protocol),y={id:p,method:s?.publishMethod||g.publish,params:Gr({topic:r,message:i,ttl:f,prompt:h,tag:d,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),_e((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const D=new Promise(async E=>{const $=({id:C})=>{var U;((U=y.id)==null?void 0:U.toString())===C.toString()&&(this.removeRequestFromQueue(C),this.relayer.events.removeListener(ge.publish,$),E())};this.relayer.events.on(ge.publish,$);const R=Kt(new Promise((C,U)=>{this.rpcPublish(y,s).then(C).catch(N=>{this.logger.warn(N,N?.message),U(N)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await R,this.events.removeListener(ge.publish,$)}catch(C){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(C,C?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await Kt(D,this.publishTimeout,I)}catch(D){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(D),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw D}finally{this.queue.delete(p)}}),$t(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:l={}}=r,{attestation:f,tvf:h,publishMethod:d,prompt:p,tag:g,ttl:y=M.FIVE_MINUTES}=l,I=l.id||jn().toString(),D=Vr(po().protocol),E=d||D.publish,$={id:I,method:E,params:Gr(r0(Gr({},u),{ttl:y,prompt:p,tag:g,attestation:f}),h)},R=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((i=$.params)==null?void 0:i.prompt)&&((s=$.params)==null||delete s.prompt),_e((o=$.params)==null?void 0:o.tag)&&((a=$.params)==null||delete a.tag);const C=new Promise(async U=>{const N=({id:G})=>{var W;((W=$.id)==null?void 0:W.toString())===G.toString()&&(this.removeRequestFromQueue(G),this.relayer.events.removeListener(ge.publish,N),U())};this.relayer.events.on(ge.publish,N);const O=Kt(new Promise((G,W)=>{this.rpcPublish($,l).then(G).catch(P=>{this.logger.warn(P,P?.message),W(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${I} tag:${g}`);try{await O,this.events.removeListener(ge.publish,N)}catch(G){this.queue.set(I,{request:$,opts:l,attempt:1}),this.logger.warn(G,G?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:I,payload:u,opts:l}}),await Kt(C,this.publishTimeout,R)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw C}finally{this.queue.delete(I)}}),$t(this,"on",(r,i)=>{this.events.on(r,i)}),$t(this,"once",(r,i)=>{this.events.once(r,i)}),$t(this,"off",(r,i)=>{this.events.off(r,i)}),$t(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=We(n,this.name),this.registerEventListeners()}get context(){return et(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(ge.publish,Gr(Gr({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,r0(Gr({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Hn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ge.connection_stalled);return}this.checkQueue()}),this.relayer.on(ge.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var vA=Object.defineProperty,EA=(t,e,n)=>e in t?vA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zr=(t,e,n)=>EA(t,typeof e!="symbol"?e+"":e,n);class _A{constructor(){Zr(this,"map",new Map),Zr(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Zr(this,"get",e=>this.map.get(e)||[]),Zr(this,"exists",(e,n)=>this.get(e).includes(n)),Zr(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Zr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var xA=Object.defineProperty,IA=Object.defineProperties,SA=Object.getOwnPropertyDescriptors,i0=Object.getOwnPropertySymbols,DA=Object.prototype.hasOwnProperty,AA=Object.prototype.propertyIsEnumerable,ru=(t,e,n)=>e in t?xA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zi=(t,e)=>{for(var n in e||(e={}))DA.call(e,n)&&ru(t,n,e[n]);if(i0)for(var n of i0(e))AA.call(e,n)&&ru(t,n,e[n]);return t},iu=(t,e)=>IA(t,SA(e)),ae=(t,e,n)=>ru(t,typeof e!="symbol"?e+"":e,n);class OA extends Fw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,ae(this,"subscriptions",new Map),ae(this,"topicMap",new _A),ae(this,"events",new He.exports.EventEmitter),ae(this,"name",p4),ae(this,"version",g4),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",Wt),ae(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=po(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ae(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),ae(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),ae(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ae(this,"on",(r,i)=>{this.events.on(r,i)}),ae(this,"once",(r,i)=>{this.events.once(r,i)}),ae(this,"off",(r,i)=>{this.events.off(r,i)}),ae(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Hn.pulse,async()=>{await this.checkPending()}),this.events.on(wt.created,async r=>{const i=wt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(wt.deleted,async r=>{const i=wt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=We(n,this.name),this.clientId=""}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=po(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Vr(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async f=>{const h=d=>{d.topic===e&&(this.events.removeListener(wt.created,h),f(d.id))};this.events.on(wt.created,h);try{const d=await Kt(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(wt.created,h),f(d)}catch{}}),l=await Kt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ge.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Vr(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await Kt(new Promise(i=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Vr(n.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await Kt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Vr(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,iu(Zi({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Zi({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,Zi({},n)),this.topicMap.set(n.topic,e),this.events.emit(wt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(wt.deleted,iu(Zi({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(wt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(wt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async n=>iu(Zi({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await ux(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=j("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 $A=Object.defineProperty,s0=Object.getOwnPropertySymbols,BA=Object.prototype.hasOwnProperty,TA=Object.prototype.propertyIsEnumerable,su=(t,e,n)=>e in t?$A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,o0=(t,e)=>{for(var n in e||(e={}))BA.call(e,n)&&su(t,n,e[n]);if(s0)for(var n of s0(e))TA.call(e,n)&&su(t,n,e[n]);return t},re=(t,e,n)=>su(t,typeof e!="symbol"?e+"":e,n);class PA extends Nw{constructor(e){super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new He.exports.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",u4),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),re(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const s=n.id||jn().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${s}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),re(this,"resetPingTimeout",()=>{Hs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),re(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(ge.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(ge.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),re(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"?We(e.logger,this.name):Lt(Lo({level:e.logger||c4})),this.messages=new dA(this.logger,e.core),this.subscriber=new OA(this,this.logger),this.publisher=new mA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ng,W_()?this.packageName=_d():G_()&&(this.bundleId=_d()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return et(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:le.relay},mo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(wt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(wt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,o0({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&f(h)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Kt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await wg())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const i=ve(M.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(ge.message,e),await this.recordMessageEvent(e,mo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(At.disconnect,s),await Kt(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=()=>{i(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,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,M.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Hs())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new K6(new G6(Q_({sdkVersion:Xc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Yc(e)){if(!e.method.endsWith(l4))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(o0({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else wo(e)&&this.events.emit(ge.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,mo.inbound),this.events.emit(ge.message,e))}async acknowledgePayload(e){const n=yo(e.id,!0);await this.provider.connection.send(n)}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 wg();WS(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Hn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&YS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ge.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},M.toMiliseconds(h4)))))}isInitialized(){if(!this.initialized){const{message:e}=j("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 RA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function a0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function c0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const CA="[object RegExp]",NA="[object String]",UA="[object Number]",FA="[object Boolean]",u0="[object Arguments]",kA="[object Symbol]",LA="[object Date]",MA="[object Map]",jA="[object Set]",qA="[object Array]",zA="[object Function]",KA="[object ArrayBuffer]",ou="[object Object]",VA="[object Error]",HA="[object DataView]",WA="[object Uint8Array]",GA="[object Uint8ClampedArray]",ZA="[object Uint16Array]",YA="[object Uint32Array]",XA="[object BigUint64Array]",JA="[object Int8Array]",QA="[object Int16Array]",eO="[object Int32Array]",tO="[object BigInt64Array]",nO="[object Float32Array]",rO="[object Float64Array]";function iO(){}function l0(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 sO(t,e,n){return Yi(t,e,void 0,void 0,void 0,void 0,n)}function Yi(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Xi(t,e,s,o)}return Xi(t,e,s,o)}function Xi(t,e,n,r){if(Object.is(t,e))return!0;let i=c0(t),s=c0(e);if(i===u0&&(i=ou),s===u0&&(s=ou),i!==s)return!1;switch(i){case NA:return t.toString()===e.toString();case UA:{const c=t.valueOf(),u=e.valueOf();return RA(c,u)}case FA:case LA:case kA:return Object.is(t.valueOf(),e.valueOf());case CA:return t.source===e.source&&t.flags===e.flags;case zA:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case MA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Yi(u,e.get(c),c,t,e,n,r))return!1;return!0}case jA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const f=c[l],h=u.findIndex(d=>Yi(f,d,void 0,t,e,n,r));if(h===-1)return!1;u.splice(h,1)}return!0}case qA:case WA:case GA:case ZA:case YA:case XA:case JA:case QA:case eO:case tO:case nO:case rO:{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(!Yi(t[c],e[c],c,t,e,n,r))return!1;return!0}case KA:return t.byteLength!==e.byteLength?!1:Xi(new Uint8Array(t),new Uint8Array(e),n,r);case HA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Xi(new Uint8Array(t),new Uint8Array(e),n,r);case VA:return t.name===e.name&&t.message===e.message;case ou:{if(!(Xi(t.constructor,e.constructor,n,r)||l0(t)&&l0(e)))return!1;const c=[...Object.keys(t),...a0(t)],u=[...Object.keys(e),...a0(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],h=t[f];if(!Object.hasOwn(e,f))return!1;const d=e[f];if(!Yi(h,d,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function oO(t,e){return sO(t,e,iO)}var aO=Object.defineProperty,h0=Object.getOwnPropertySymbols,cO=Object.prototype.hasOwnProperty,uO=Object.prototype.propertyIsEnumerable,au=(t,e,n)=>e in t?aO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f0=(t,e)=>{for(var n in e||(e={}))cO.call(e,n)&&au(t,n,e[n]);if(h0)for(var n of h0(e))uO.call(e,n)&&au(t,n,e[n]);return t},ut=(t,e,n)=>au(t,typeof e!="symbol"?e+"":e,n);class yr extends Uw{constructor(e,n,r,i=Wt,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,ut(this,"map",new Map),ut(this,"version",f4),ut(this,"cached",[]),ut(this,"initialized",!1),ut(this,"getKey"),ut(this,"storagePrefix",Wt),ut(this,"recentlyDeleted",[]),ut(this,"recentlyDeletedLimit",200),ut(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):IS(o)?this.map.set(o.id,o):SS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ut(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())}),ut(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ut(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>oO(a[c],o[c]))):this.values)),ut(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=f0(f0({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ut(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=We(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=j("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var lO=Object.defineProperty,hO=(t,e,n)=>e in t?lO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Q=(t,e,n)=>hO(t,typeof e!="symbol"?e+"":e,n);class fO{constructor(e,n){this.core=e,this.logger=n,Q(this,"name",y4),Q(this,"version",w4),Q(this,"events",new He.exports),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",Wt),Q(this,"ignoredPayloadTypes",[ln]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),Q(this,"create",async r=>{this.isInitialized();const i=Lc(),s=await this.core.crypto.setSymKey(i),o=ve(M.FIVE_MINUTES),a={protocol:Cg},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=sg({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(pr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:u}}),Q(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Gt.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=ig(r.uri);i.props.properties.topic=s,i.addTrace(Gt.pairing_uri_validation_success),i.addTrace(Gt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Gt.existing_pairing),l.active)throw i.setError(pn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Gt.pairing_not_expired)}const f=c||ve(M.FIVE_MINUTES),h={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,h),i.addTrace(Gt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(pr.create,h),i.addTrace(Gt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Gt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(pn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw i.setError(pn.subscribe_pairing_topic_failure),d}return i.addTrace(Gt.subscribe_pairing_topic_success),h}),Q(this,"activate",async({topic:r})=>{this.isInitialized();const i=ve(M.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),Q(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=or();this.events.once(ie("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Q(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),Q(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),Q(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return sg({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(r,i,s)=>{const o=dn(i,s),a=await this.core.crypto.encode(r,o),c=Ki[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),Q(this,"sendResult",async(r,i,s)=>{const o=yo(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ki[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"sendError",async(r,i,s)=>{const o=Zc(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ki[c]?Ki[c].res:Ki.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),Q(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Dn(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),Q(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Q(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(pr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{Ht(i)?this.events.emit(ie("pairing_ping",s),{}):Dt(i)&&this.events.emit(ie("pairing_ping",s),{error:i.error})},500)}),Q(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(pr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),Q(this,"isValidPair",(r,i)=>{var s;if(!at(r)){const{message:a}=j("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(!xS(r.uri)){const{message:a}=j("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(pn.malformed_pairing_uri),new Error(a)}const o=ig(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(pn.pairing_expired);const{message:a}=j("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async r=>{if(!at(r)){const{message:s}=j("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),Q(this,"isValidDisconnect",async r=>{if(!at(r)){const{message:s}=j("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),Q(this,"isValidPairingTopic",async r=>{if(!ye(r,!1)){const{message:i}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Dn(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=j("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=We(n,this.name),this.pairings=new yr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return et(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ge.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Yc(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):wo(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Ot.expired,async e=>{const{topic:n}=Dd(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(pr.expire,{topic:n}))})}}var dO=Object.defineProperty,pO=(t,e,n)=>e in t?dO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pe=(t,e,n)=>pO(t,typeof e!="symbol"?e+"":e,n);class gO extends Pw{constructor(e,n){super(e,n),this.core=e,this.logger=n,Pe(this,"records",new Map),Pe(this,"events",new He.exports.EventEmitter),Pe(this,"name",b4),Pe(this,"version",m4),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Wt),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Pe(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:ve(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ut.created,o)}),Pe(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Dt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Ut.updated,i))}),Pe(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Pe(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Ut.deleted,s)}}),this.persist()}),Pe(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Pe(this,"on",(r,i)=>{this.events.on(r,i)}),Pe(this,"once",(r,i)=>{this.events.once(r,i)}),Pe(this,"off",(r,i)=>{this.events.off(r,i)}),Pe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=We(n,this.name)}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:dn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ut.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Ut.created,e=>{const n=Ut.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Ut.updated,e=>{const n=Ut.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Ut.deleted,e=>{const n=Ut.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Hn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{M.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(Ut.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var yO=Object.defineProperty,wO=(t,e,n)=>e in t?yO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ze=(t,e,n)=>wO(t,typeof e!="symbol"?e+"":e,n);class bO extends kw{constructor(e,n){super(e,n),this.core=e,this.logger=n,ze(this,"expirations",new Map),ze(this,"events",new He.exports.EventEmitter),ze(this,"name",v4),ze(this,"version",E4),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Wt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),ze(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Ot.created,{target:s,expiration:o})}),ze(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),ze(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Ot.deleted,{target:i,expiration:s})}}),ze(this,"on",(r,i)=>{this.events.on(r,i)}),ze(this,"once",(r,i)=>{this.events.once(r,i)}),ze(this,"off",(r,i)=>{this.events.off(r,i)}),ze(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=We(n,this.name)}get context(){return et(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 ex(e);if(typeof e=="number")return tx(e);const{message:n}=j("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;M.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Ot.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Hn.pulse,()=>this.checkExpirations()),this.events.on(Ot.created,e=>{const n=Ot.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Ot.expired,e=>{const n=Ot.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Ot.deleted,e=>{const n=Ot.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mO=Object.defineProperty,vO=(t,e,n)=>e in t?mO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,we=(t,e,n)=>vO(t,typeof e!="symbol"?e+"":e,n);class EO extends Lw{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,we(this,"name",_4),we(this,"abortController"),we(this,"isDevEnv"),we(this,"verifyUrlV3",I4),we(this,"storagePrefix",Wt),we(this,"version",Pg),we(this,"publicKey"),we(this,"fetchPromise"),we(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),we(this,"register",async i=>{if(!Fr()||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=Xn(),l=this.startAbortTimer(M.ONE_SECOND*5),f=await new Promise((h,d)=>{const p=()=>{window.removeEventListener("message",y),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=I=>{if(I.data&&typeof I.data=="string")try{const D=JSON.parse(I.data);if(D.type==="verify_attestation"){if(oa(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",f),f}catch(u){this.logger.warn(u)}return""}),we(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(oa(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),we(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),we(this,"getVerifyUrl",i=>{let s=i||Vi;return S4.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Vi}`),s=Vi),s}),we(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),we(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),we(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),we(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),we(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),we(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),we(this,"validateAttestation",(i,s)=>{const o=ZI(i,s.publicKey),a={hasExpired:M.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=We(n,this.name),this.abortController=new AbortController,this.isDevEnv=ac(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return et(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var _O=Object.defineProperty,xO=(t,e,n)=>e in t?_O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,d0=(t,e,n)=>xO(t,typeof e!="symbol"?e+"":e,n);class IO extends Mw{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,d0(this,"context",D4),d0(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${A4}/${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=We(n,this.context)}}var SO=Object.defineProperty,p0=Object.getOwnPropertySymbols,DO=Object.prototype.hasOwnProperty,AO=Object.prototype.propertyIsEnumerable,cu=(t,e,n)=>e in t?SO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ji=(t,e)=>{for(var n in e||(e={}))DO.call(e,n)&&cu(t,n,e[n]);if(p0)for(var n of p0(e))AO.call(e,n)&&cu(t,n,e[n]);return t},Se=(t,e,n)=>cu(t,typeof e!="symbol"?e+"":e,n);class OO extends jw{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Se(this,"context",$4),Se(this,"storagePrefix",Wt),Se(this,"storageVersion",O4),Se(this,"events",new Map),Se(this,"shouldPersist",!1),Se(this,"init",async()=>{if(!ac())try{const i={eventId:Od(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Id(this.core.relayer.protocol,this.core.relayer.version,Xc)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Se(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=Od(),l=this.core.projectId||"",f=Date.now(),h=Ji({eventId:u,timestamp:f,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,h),this.shouldPersist=!0),h}),Se(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ji(Ji({},a),this.setMethods(a.eventId))}),Se(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Se(this,"setEventListeners",()=>{this.core.heartbeat.on(Hn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>B4&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Se(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Se(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Se(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ji(Ji({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Se(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Se(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${T4}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Xc}${s}`,{method:"POST",body:JSON.stringify(i)})}),Se(this,"getAppDomain",()=>xd().url),this.logger=We(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var $O=Object.defineProperty,g0=Object.getOwnPropertySymbols,BO=Object.prototype.hasOwnProperty,TO=Object.prototype.propertyIsEnumerable,uu=(t,e,n)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,y0=(t,e)=>{for(var n in e||(e={}))BO.call(e,n)&&uu(t,n,e[n]);if(g0)for(var n of g0(e))TO.call(e,n)&&uu(t,n,e[n]);return t},ue=(t,e,n)=>uu(t,typeof e!="symbol"?e+"":e,n);class lu extends Ow{constructor(e){var n;super(e),ue(this,"protocol",Tg),ue(this,"version",Pg),ue(this,"name",bo),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new He.exports.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Ng,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Lo({level:typeof e?.logger=="string"&&e.logger?e.logger:J6.logger,name:bo}),{logger:s,chunkLoggerController:o}=Sw({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=We(s,this.name),this.heartbeat=new Po,this.crypto=new sA(this,this.logger,e?.keychain),this.history=new gO(this,this.logger),this.expirer=new bO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Xy(y0(y0({},Q6),e?.storageOptions)),this.relayer=new PA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new fO(this,this.logger),this.verify=new EO(this,this.logger,this.storage),this.echoClient=new IO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new OO(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new lu(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(d4,r),n}get context(){return et(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(Ug,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(Ug)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const PO=lu,w0="wc",b0=2,m0="client",hu=`${w0}@${b0}:${m0}:`,fu={name:m0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},v0="WALLETCONNECT_DEEPLINK_CHOICE",RO="proposal",E0="Proposal expired",CO="session",Yr=M.SEVEN_DAYS,NO="engine",Re={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},du={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Yt={idle:"IDLE",active:"ACTIVE"},UO={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},FO="request",kO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],LO="wc",MO="auth",jO="authKeys",qO="pairingTopics",zO="requests",Eo=`${LO}@${1.5}:${MO}:`,_o=`${Eo}:PUB_KEY`;var KO=Object.defineProperty,VO=Object.defineProperties,HO=Object.getOwnPropertyDescriptors,_0=Object.getOwnPropertySymbols,WO=Object.prototype.hasOwnProperty,GO=Object.prototype.propertyIsEnumerable,pu=(t,e,n)=>e in t?KO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e)=>{for(var n in e||(e={}))WO.call(e,n)&&pu(t,n,e[n]);if(_0)for(var n of _0(e))GO.call(e,n)&&pu(t,n,e[n]);return t},Ke=(t,e)=>VO(t,HO(e)),F=(t,e,n)=>pu(t,typeof e!="symbol"?e+"":e,n);class ZO extends Vw{constructor(e){super(e),F(this,"name",NO),F(this,"events",new He.exports),F(this,"initialized",!1),F(this,"requestQueue",{state:Yt.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Yt.idle,queue:[]}),F(this,"emittedSessionRequests",new lx({limit:500})),F(this,"requestQueueDelay",M.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Re)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=Ke(se({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=bS(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=r;let l=i,f,h=!1;try{if(l){const C=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=C.active}}catch(C){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),C}if(!l||!h){const{topic:C,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=C,f=U}if(!l){const{message:C}=j("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(C)}const d=await this.client.core.crypto.generateKeyPair(),p=Re.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=ve(p),y=Ke(se(se({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Cg}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:ct()}),I=ie("session_connect",y.id),{reject:D,resolve:E,done:$}=or(p,E0),R=({id:C})=>{C===y.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(y.id),this.events.emit(I,{error:{message:E0,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(I,({error:C,session:U})=>{this.client.events.off("proposal_expire",R),C?D(C):U&&E(U)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:f,approval:$}}),F(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),F(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[qn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(O){throw o.setError(Hi.no_internet_connection),O}try{await this.isValidProposalId(n?.id)}catch(O){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Hi.proposal_not_found),O}try{await this.isValidApprove(n)}catch(O){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Hi.session_approve_namespace_validation_failure),O}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=n,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:y,optionalNamespaces:I}=d;let D=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:p});D||(D=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:qn.session_approve_started,properties:{topic:p,trace:[qn.session_approve_started,qn.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),$=g.publicKey,R=await this.client.core.crypto.generateSharedKey(E,$),C=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:ve(Yr)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),U=le.relay;D.addTrace(qn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:U,internal:{skipSubscribe:!0}})}catch(O){throw D.setError(Hi.subscribe_session_topic_failure),O}D.addTrace(qn.subscribe_session_topic_success);const N=Ke(se({},C),{topic:R,requiredNamespaces:y,optionalNamespaces:I,pairingTopic:p,acknowledged:!1,self:C.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:E,transportType:le.relay});await this.client.session.set(R,N),D.addTrace(qn.store_session);try{await this.sendApproveSession({sessionTopic:R,proposal:d,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:E},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),D.addTrace(qn.session_approve_publish_success)}catch(O){throw this.client.logger.error(O),this.client.session.delete(R,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),O}return this.client.core.eventClient.deleteEvent({eventId:D.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(R,ve(Yr)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),F(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Re.wc_sessionPropose.reject}),await this.deleteProposal(r)}),F(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=or(),c=ct(),u=jn().toString(),l=this.client.session.get(r).namespaces;return this.events.once(ie("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:l}),a(f)}),{acknowledged:s}}),F(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=ct(),{done:s,resolve:o,reject:a}=or();return this.events.once(ie("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,ve(Yr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),F(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Re.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const c=ct(),u=jn().toString(),{done:l,resolve:f,reject:h}=or(o,"Request expired. Please try again.");this.events.once(ie("session_request",c),({error:y,result:I})=>{y?h(y):f(I)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:Ke(se({},i),{expiryTimestamp:ve(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:Ke(se({},i),{expiryTimestamp:ve(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(I=>h(I)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const D=await sx(this.client.core.storage,v0);await nx({id:c,topic:s,wcDeepLink:D})}y()}),l()]).then(y=>y[2])}),F(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:s}=i,o=this.client.session.get(r);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Ht(i)?await this.sendResult({id:s,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Dt(i)&&await this.sendError({id:s,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(n)}),F(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ct(),s=jn().toString(),{done:o,resolve:a,reject:c}=or();this.events.once(ie("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),F(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=jn().toString(),a=ct();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=j("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),F(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>ES(r,n)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:h,exp:d,nbf:p,methods:g=[],expiry:y}=n,I=[...n.resources||[]],{topic:D,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:E}});const $=await this.client.core.crypto.generateKeyPair(),R=fo($);if(await Promise.all([this.client.auth.authKeys.set(_o,{responseTopic:R,publicKey:$}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:D})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),g.length>0){const{namespace:_}=ir(a[0]);let S=v8(_,"request",g);eo(I)&&(S=_8(S,I.pop())),I.push(S)}const C=y&&y>Re.wc_sessionAuthenticate.req.ttl?y:Re.wc_sessionAuthenticate.req.ttl,U={authPayload:{type:h??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:d,nbf:p,resources:I},requester:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:ve(C)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},O={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:ve(Re.wc_sessionPropose.req.ttl),id:ct()},{done:G,resolve:W,reject:P}=or(C,"Request expired"),v=ct(),m=ie("session_connect",O.id),w=ie("session_request",v),b=async({error:_,session:S})=>{this.events.off(w,x),_?P(_):S&&W({session:S})},x=async _=>{var S,B,T;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),_.error){const V=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===V.code?void 0:(this.events.off(m,b),P(_.error.message))}await this.deleteProposal(O.id),this.events.off(m,b);const{cacaos:q,responder:L}=_.result,k=[],z=[];for(const V of q){await Qd({cacao:V,projectId:this.client.core.projectId})||(this.client.logger.error(V,"Signature verification failed"),P(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=V,he=eo(Y.resources),Ve=[yc(Y.iss)],mt=Qs(Y.iss);if(he){const gn=np(he),wu=rp(he);k.push(...gn),Ve.push(...wu)}for(const gn of Ve)z.push(`${gn}:${mt}`)}const H=await this.client.core.crypto.generateSharedKey($,L.publicKey);let Z;k.length>0&&(Z={topic:H,acknowledged:!0,self:{publicKey:$,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:ve(Yr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:lg([...new Set(k)],[...new Set(z)]),transportType:o},await this.client.core.relayer.subscribe(H,{transportType:o}),await this.client.session.set(H,Z),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:L.metadata}),Z=this.client.session.get(H)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(B=L.metadata.redirect)!=null&&B.linkMode&&(T=L.metadata.redirect)!=null&&T.universal&&r&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(H,{transportType:le.link_mode})),W({auths:q,session:Z})};this.events.once(m,b),this.events.once(w,x);let A;try{if(s){const _=dn("wc_sessionAuthenticate",U,v);this.client.core.history.set(D,_);const S=await this.client.core.crypto.encode("",_,{type:Ui,encoding:Mn});A=go(r,D,S)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:U,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:O,expiry:Re.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:O.id})])}catch(_){throw this.events.off(m,b),this.events.off(w,x),_}return await this.setProposal(O.id,O),await this.setAuthRequest(v,{request:Ke(se({},U),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:A??E,response:G}}),F(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[gr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Wi.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Wi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=fo(c),f={type:ln,receiverPublicKey:c,senderPublicKey:u},h=[],d=[];for(const y of i){if(!await Qd({cacao:y,projectId:this.client.core.projectId})){s.setError(Wi.invalid_cacao);const R=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:R,encodeOpts:f}),new Error(R.message)}s.addTrace(gr.cacaos_verified);const{p:I}=y,D=eo(I.resources),E=[yc(I.iss)],$=Qs(I.iss);if(D){const R=np(D),C=rp(D);h.push(...R),E.push(...C)}for(const R of E)d.push(`${R}:${$}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(gr.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ve(Yr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:lg([...new Set(h)],[...new Set(d)]),transportType:a},s.addTrace(gr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Wi.subscribe_authenticated_session_topic_failure),y}s.addTrace(gr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(gr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(gr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Wi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),F(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=fo(o),u={type:ln,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Re.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),F(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return ep(r,i)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),F(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),F(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(v0).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),F(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Hi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),F(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=Yt.idle,this.client.events.emit("session_request_expire",{id:n}))}),F(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),F(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),F(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,ve(Re.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),F(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=le.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||ve(Re.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),F(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:h={}}=n,d=dn(i,s,c);let p;const g=!!l;try{const D=g?Mn:ot;p=await this.client.core.crypto.encode(r,d,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),D}let y;if(kO.includes(i)){const D=St(JSON.stringify(d)),E=St(p);y=await this.client.core.verify.register({id:E,decryptedId:D})}const I=se(se({},Re[i].req),h);if(I.attestation=y,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(r,d),g){const D=go(l,r,p);await global.Linking.openURL(D,this.client.name)}else I.tvf=Ke(se({},f),{correlationId:d.id}),u?(I.internal=Ke(se({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,I)):this.client.core.relayer.publish(r,p,I).catch(D=>this.client.logger.error(D));return d.id}),F(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=dn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:ot}),a=St(JSON.stringify(s)),c=St(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Ke(se({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),F(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=yo(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:ot}),l=dn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:ot});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:Ke(se({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=yo(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Mn:ot;l=await this.client.core.crypto.encode(i,u,Ke(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,d;try{h=await this.client.core.history.get(i,r);const p=h.request;try{d=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(f){const p=go(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Re[p].res;g.tvf=Ke(se({},d),{correlationId:r}),o?(g.internal=Ke(se({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),F(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Zc(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=f?Mn:ot;l=await this.client.core.crypto.encode(i,u,Ke(se({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let h;try{h=await this.client.core.history.get(i,r)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),d}if(f){const d=go(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=h.request.method,p=a||Re[d].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),F(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Dn(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Dn(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),F(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),F(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Yt.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=Yt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Yt.idle}),F(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=j("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),F(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(pn.proposal_listener_not_found)),this.isValidConnect(se({},i.params));const l=a.expiryTimestamp||ve(Re.wc_sessionPropose.req.ttl),f=se({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const h=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(Gt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:h})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Re.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),F(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(Ht(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const f=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(Dt(r)){await this.deleteProposal(s);const o=ie("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),F(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=r.params,d=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!d)return this.client.logger.error(`Pending session not found for topic ${n}`);const p=this.client.proposal.get(d.proposalId),g=Ke(se(se(se({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),{transportType:le.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ie("session_connect",d.proposalId),{session:g}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;Ht(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(ie("session_approve",i),{})):Dt(r)&&(await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.events.emit(ie("session_approve",i),{error:r.error}))}),F(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:n},i));try{ji.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw ji.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=ie("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Ht(r)?this.events.emit(ie("session_update",i),{}):Dt(r)&&this.events.emit(ie("session_update",i),{error:r.error})}),F(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,ve(Yr)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),F(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=ie("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Ht(r)?this.events.emit(ie("session_extend",i),{}):Dt(r)&&this.events.emit(ie("session_extend",i),{error:r.error})}),F(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),F(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=ie("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Ht(r)?this.events.emit(ie("session_ping",i),{}):Dt(r)&&this.events.emit(ie("session_ping",i),{error:r.error})},500)}),F(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(ge.publish,async()=>{s(await this.deleteSession({topic:n,id:i}))})}),this.sendResult({id:i,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),F(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:h}=a;try{await this.isValidRequest(se({topic:o},h));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify(dn("wc_sessionRequest",h,f))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:f,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),l===le.link_mode&&(r=d.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=d.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:f,topic:o,error:d}),this.client.logger.error(d)}}),F(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=ie("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Ht(r)?this.events.emit(ie("session_request",i),{result:r.result}):Dt(r)&&this.events.emit(ie("session_request",i),{error:r.error})}),F(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(se({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),ji.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),Ht(r)?this.events.emit(ie("session_request",i),{result:r.result}):Dt(r)&&this.events.emit(ie("session_request",i),{error:r.error})}),F(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,h=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:h,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:d,pairingTopic:i,transportType:c}),c===le.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:ln,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:d,rpcOpts:Re.wc_sessionAuthenticate.autoReject,appLink:h})}}),F(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),F(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Yt.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ie("session_request",s.request.id),{error:r})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Yt.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),F(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=Yt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),F(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:dn("wc_sessionPropose",Ke(se({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),F(this,"isValidConnect",async n=>{if(!at(n)){const{message:u}=j("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(_e(r)||await this.isValidPairingTopic(r),!RS(c,!0)){const{message:u}=j("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!_e(i)&&Li(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!_e(s)&&Li(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),F(this,"validateNamespaces",(n,r)=>{const i=PS(n,"connect()",r);if(i)throw new Error(i.message)}),F(this,"isValidApprove",async n=>{if(!at(n))throw new Error(j("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=qc(i,"approve()");if(u)throw new Error(u.message);const l=gg(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ye(s,!0)){const{message:f}=j("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(h=>f.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),F(this,"isValidReject",async n=>{if(!at(n)){const{message:s}=j("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!NS(i)){const{message:s}=j("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),F(this,"isValidSessionSettleRequest",n=>{if(!at(n)){const{message:u}=j("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!dg(r)){const{message:u}=j("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=DS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=qc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Dn(o)){const{message:u}=j("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),F(this,"isValidUpdate",async n=>{if(!at(n)){const{message:c}=j("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=qc(i,"update()");if(o)throw new Error(o.message);const a=gg(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),F(this,"isValidRequest",async n=>{if(!at(n)){const{message:c}=j("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!pg(a,s)){const{message:c}=j("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!US(i)){const{message:c}=j("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!LS(a,s,i.method)){const{message:c}=j("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!zS(o,du)){const{message:c}=j("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${du.min} and ${du.max}`);throw new Error(c)}}),F(this,"isValidRespond",async n=>{var r;if(!at(n)){const{message:o}=j("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!FS(s)){const{message:o}=j("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),F(this,"isValidPing",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidEmit",async n=>{if(!at(n)){const{message:a}=j("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!pg(o,s)){const{message:a}=j("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!kS(i)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!MS(o,s,i.name)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ye(i,!1))throw new Error("uri is required parameter");if(!ye(s,!1))throw new Error("domain is required parameter");if(!ye(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>ir(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ir(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Vi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=j("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),F(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=j("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),F(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,h;return!n||r!==le.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),F(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=Ad(n,"topic")||"",i=decodeURIComponent(Ad(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),F(this,"registerLinkModeListeners",async()=>{var n;if(ac()||Sn()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),F(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),F(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=UO[s];if(s==="sui_signTransaction")return[r8(r.transactionBytes)];if(s==="near_signTransaction")return[Zd(r)];if(s==="near_signTransactions")return r.map(c=>Zd(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[i6({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Wr(r)?r.map(c=>Yd(c)):[Yd(r)];if(s==="cosmos_signDirect")return[s8(r)];if(s==="wallet_sendCalls")return o8(r);if(typeof r=="string")return[r];const a=r[o.key];if(Wr(a))return s==="solana_signAllTransactions"?a.map(c=>n8(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ge.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(_o)?this.client.auth.authKeys.get(_o):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===le.link_mode?Mn:ot});Yc(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:St(r)})):wo(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ot.expired,async e=>{const{topic:n,id:r}=Dd(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,j("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,j("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(pr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(pr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ye(e,!1)){const{message:n}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=j("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!ye(e,!1)){const{message:n}=j("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=j("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=j("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ye(e,!1)){const{message:n}=j("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=j("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!CS(e)){const{message:n}=j("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=j("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class YO extends yr{constructor(e,n){super(e,n,RO,hu),this.core=e,this.logger=n}}class XO extends yr{constructor(e,n){super(e,n,CO,hu),this.core=e,this.logger=n}}class JO extends yr{constructor(e,n){super(e,n,FO,hu,r=>r.id),this.core=e,this.logger=n}}class QO extends yr{constructor(e,n){super(e,n,jO,Eo,()=>_o),this.core=e,this.logger=n}}class e$ extends yr{constructor(e,n){super(e,n,qO,Eo),this.core=e,this.logger=n}}class t$ extends yr{constructor(e,n){super(e,n,zO,Eo,r=>r.id),this.core=e,this.logger=n}}var n$=Object.defineProperty,r$=(t,e,n)=>e in t?n$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gu=(t,e,n)=>r$(t,typeof e!="symbol"?e+"":e,n);class i${constructor(e,n){this.core=e,this.logger=n,gu(this,"authKeys"),gu(this,"pairingTopics"),gu(this,"requests"),this.authKeys=new QO(this.core,this.logger),this.pairingTopics=new e$(this.core,this.logger),this.requests=new t$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var s$=Object.defineProperty,o$=(t,e,n)=>e in t?s$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ee=(t,e,n)=>o$(t,typeof e!="symbol"?e+"":e,n);class yu extends Kw{constructor(e){super(e),ee(this,"protocol",w0),ee(this,"version",b0),ee(this,"name",fu.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new He.exports.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(r,i)=>this.events.on(r,i)),ee(this,"once",(r,i)=>this.events.once(r,i)),ee(this,"off",(r,i)=>this.events.off(r,i)),ee(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ee(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ee(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ee(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||fu.name,this.metadata=Y_(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Lt(Lo({level:e?.logger||fu.logger}));this.core=e?.core||new PO(e),this.logger=We(n,this.name),this.session=new XO(this.core,this.logger),this.proposal=new YO(this.core,this.logger),this.pendingRequest=new JO(this.core,this.logger),this.engine=new ZO(this),this.auth=new i$(this.core,this.logger)}static async init(e){const n=new yu(e);return await n.initialize(),n}get context(){return et(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const a$=yu;class x0{constructor(e){this.opts=e}}class I0{constructor(e){this.client=e}}const S0=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Mi(r?.chainId))return!1;const{namespace:a}=ir(r.chainId),c=e.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(u=>u.toLowerCase()).includes(s?.toLowerCase()))throw new Error(`Unsupported token standard: ${s} for namespace: ${a}`);return!0},c$=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!S0({supportedNamespaces:e,token:r}))},u$=[{assetNamespaces:["erc20","slip44"],capabilities:null,events:[],methods:["eth_sendTransaction"],name:"eip155"},{assetNamespaces:["token","slip44"],capabilities:null,events:[],methods:["solana_signAndSendTransaction"],name:"solana"},{assetNamespaces:["trc20","slip44"],capabilities:null,events:[],methods:["tron_signTransaction"],name:"tron"}];var l$=Object.defineProperty,h$=(t,e,n)=>e in t?l$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,de=(t,e,n)=>h$(t,typeof e!="symbol"?e+"":e,n);class f$ extends I0{constructor(e){var n;super(e),de(this,"signClient"),de(this,"tokens",[]),de(this,"paymentIntentsMap",new Map),de(this,"paymentIntentToTransactionsMap",new Map),de(this,"supportedNamespaces",u$),de(this,"logger"),de(this,"init",async()=>{var r,i;this.signClient=await a$.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((r=this.client.opts.storageOptions)==null?void 0:r.databaseName)||Tu.database},logger:(i=this.client.opts.loggerOptions)==null?void 0:i.signLevel});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest(JSON.stringify({id:ct(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}));this.logger.debug("Received supported namespaces/networks",{supportedNamespaces:s.result.namespaces}),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error("Failed to fetch supported namespaces/networks",s)}}),de(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug("Setting tokens",{tokens:i}),i.forEach(s=>{if(!S0({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=i,s()}),this.logger.debug("Tokens set",{tokens:i})}),de(this,"createPaymentIntent",async r=>{const{paymentIntents:i}=r;if(this.logger.debug("Creating payment intent",{paymentIntents:i}),i.length===0)throw new Error("No payment intents provided");i.forEach(u=>{if(!c$({paymentIntent:u,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(u)}`)}),this.logger.debug("Payment intent validation success",{paymentIntents:i});const s=this.composeNamespaces(i),{uri:o,approval:a}=await this.signClient.connect({optionalNamespaces:s});if(this.logger.debug("Connected to the WalletConnect network",{uri:o}),!o)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001}}),new Error("Failed to connect to the WalletConnect network");const c=ct();this.paymentIntentsMap.set(c,i),this.logger.debug("Payment intents map set",{intentId:c,paymentIntents:i}),this.emit("await_approval",{approval:a,intentId:c}),this.logger.debug("Emitted await_approval event",{intentId:c}),this.emit("qr_ready",{uri:o}),this.logger.debug("Emitted qr_ready event",{uri:o})}),de(this,"restart",async r=>{if(this.logger.debug("Restarting",{params:r}),r!=null&&r.reinit){this.tokens=[],this.paymentIntentsMap.clear(),this.paymentIntentToTransactionsMap.clear(),this.logger.debug("Restarted: Cleared payment intents map and payment intent to transactions map");return}const i=Array.from(this.paymentIntentsMap.values()).flat();await this.createPaymentIntent({paymentIntents:i}),this.logger.debug("Restarted: Created payment intent flow from the beginning",{paymentIntents:i})}),de(this,"emit",(r,i)=>(this.logger.debug("Emit",{event:r,args:i}),this.client.events.emit(r,i))),de(this,"on",(r,i)=>(this.logger.debug("On",{event:r,listener:i}),this.client.events.on(r,i))),de(this,"once",(r,i)=>(this.logger.debug("Once",{event:r,listener:i}),this.client.events.once(r,i))),de(this,"off",(r,i)=>(this.logger.debug("Off",{event:r,listener:i}),this.client.events.off(r,i))),de(this,"removeListener",(r,i)=>(this.logger.debug("Remove listener",{event:r,listener:i}),this.client.events.removeListener(r,i))),de(this,"prepareTransactionsFromPaymentIntents",async r=>{this.logger.debug("Preparing transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic});const{intentId:i,session:s}=r,o=this.paymentIntentsMap.get(i);if(!o)throw new Error(`Payment intents not found for id: ${i}`);const a=[];for(const f of o){const{token:h,amount:d,recipient:p}=f,{namespace:g}=ir(h.network.chainId),y=s.namespaces[g].accounts.find(I=>I.includes(`${h.network.chainId}:`));if(!y)throw new Error(`Address not found in session for chain id: ${h.network.chainId}, approved addresses: ${s.namespaces[g].accounts.join(", ")}`);a.push({asset:`${h.network.chainId}/${h.standard.toLowerCase()}:${h.address}`,recipient:p,amount:d,sender:y})}this.logger.debug("Prepared transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic,transactions:a});const c={id:ct(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:a}};this.logger.debug("Fetching wc_pos_buildTransactions",{payload:c});const u=await this.fetchRpcRequest(JSON.stringify(c));this.logger.debug("Received wc_pos_buildTransactions",{response:u});const l=u.result.transactions;return this.paymentIntentToTransactionsMap.set(i,l),this.logger.debug("Payment intent to transactions map set",{intentId:r.intentId,transactions:l}),l}),de(this,"onSessionConnected",async r=>{const{intentId:i,session:s}=r;this.logger.debug("On session connected",{intentId:i,sessionTopic:s.topic}),this.emit("connected",{}),this.logger.debug("Emitted connected event");const o=await this.prepareTransactionsFromPaymentIntents({intentId:i,session:s});this.logger.debug("Transactions prepared",{transactions:o}),this.sendTransactionsToWallet({transactions:o,session:s,intentId:i})}),de(this,"sendTransactionsToWallet",async r=>{const{transactions:i,session:s,intentId:o}=r;this.logger.debug("Sending transactions to wallet",{transactions:i,sessionTopic:s.topic,intentId:o});const a=this.paymentIntentsMap.get(o);if(!a)throw new Error(`Payment intents not found for id: ${o}`);for(let c=0;c<i.length;c++){const u=i[c],l=a[c];try{this.emit("payment_requested",{}),this.logger.debug("Emitted payment_requested event",{transactionId:u.id});let f;try{f=await this.signClient.request({topic:s.topic,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug("Wallet responded to payment request",{transactionId:u.id,result:f})}catch(h){throw this.logger.error("error",h),this.emit("payment_rejected",{error:{message:h?.message,code:4001},paymentIntent:l}),h}this.emit("payment_broadcasted",f),this.logger.debug("Emitted payment_broadcasted event",{transactionId:u.id}),this.awaitPaymentConfirmed({transactionId:u.id,result:f}),await new Promise(h=>setTimeout(h,1e3))}catch(f){this.logger.error("error",f)}}}),de(this,"awaitPaymentConfirmed",async r=>{try{const{transactionId:i,result:s}=r;this.logger.debug("Awaiting payment confirmed",{transactionId:i,result:s});const o={id:ct(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let a=0,c;for(;!c;){if(a>=Ru)throw new Error(`Transaction status not found for id: ${i}`);a++;const u=await this.fetchRpcRequest(JSON.stringify(o));if(this.logger.debug("Received wc_pos_checkTransaction",{transactionId:i,response:u}),u.result.status==="CONFIRMED"){this.logger.debug("Transaction status confirmed",{response:u}),this.emit("payment_successful",{transaction:s}),c=u.result;break}else if(u.result.status==="FAILED"){this.logger.debug("Transaction failed",{response:u}),this.emit("payment_failed",{error:{message:u.result.error,code:4001},transaction:s}),c=u.result;break}else u.result.status==="PENDING"&&(this.logger.debug("Transaction pending",{response:u}),await new Promise(l=>setTimeout(l,u.result.checkIn||1e3)))}}catch(i){this.logger.error("Error while awaiting payment confirmations",i)}}),de(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,intentId:i})=>{try{this.logger.debug("On await_approval",{intentId:i});const s=await r();this.onSessionConnected({intentId:i,session:s})}catch(s){this.logger.error("Error while awaiting approval",s),this.emit("connection_rejected",{error:{message:s?.message,code:4001}})}})}),de(this,"fetchRpcRequest",async r=>{var i,s;this.logger.debug("Fetching RPC request",{url:this.getRpcUrl(),payload:r});const o=await fetch(this.getRpcUrl(),{method:"POST",body:r});if(!o.ok)throw new Error(`Failed to fetch RPC request: ${o.statusText}`);const a=await o.json();if(this.logger.debug("Received RPC request response",{data:a}),a.error)throw this.emit("payment_failed",{error:{message:(i=a.error)==null?void 0:i.message,code:4001},transaction:""}),new Error(`Failed to fetch RPC request: ${(s=a.error)==null?void 0:s.message}`);return a}),de(this,"getRpcUrl",()=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${this.client.opts.projectId}&st=node&sv=js-pos-${Pu}`),this.signClient={},this.logger=Lt({name:this.client.name,level:(n=this.client.opts.loggerOptions)==null?void 0:n.posLevel}),this.setupEventHandlers()}composeNamespaces(e){this.logger.debug("Composing namespaces",{paymentIntents:e});const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=ir(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug("Composed namespaces",{namespaces:n}),n}}var d$=Object.defineProperty,p$=(t,e,n)=>e in t?d$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ft=(t,e,n)=>p$(t,typeof e!="symbol"?e+"":e,n);class xo extends x0{constructor(e){super(e),Ft(this,"name"),Ft(this,"events",new He.exports),Ft(this,"engine"),Ft(this,"metadata"),Ft(this,"on",(n,r)=>this.engine.on(n,r)),Ft(this,"once",(n,r)=>this.engine.once(n,r)),Ft(this,"off",(n,r)=>this.engine.off(n,r)),Ft(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),Ft(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ft(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ft(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=Io,this.engine=new f$(this)}static async init(e){const n=new xo(e);return await n.initialize(),n}async initialize(){try{await this.engine.init(),this.engine.signClient.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.signClient.logger.info("POSClient Initialization Failure"),this.engine.signClient.logger.error(e.message),e}}}const g$=xo;Ce.CLIENT_CONTEXT=Io,Ce.CLIENT_STORAGE_OPTIONS=Tu,Ce.CLIENT_STORAGE_PREFIX=M0,Ce.IPOSClient=x0,Ce.IPOSClientEngine=I0,Ce.MAX_TRANSACTION_STATUS_CHECKS=Ru,Ce.POSClient=g$,Ce.POS_CLIENT_VERSION=Pu,Ce.PROTOCOL=Bu,Ce.PROTOCOL_VERSION=L0,Ce.default=xo,Object.defineProperty(Ce,"__esModule",{value:!0})});
41
+ ***************************************************************************** */var Mc=function(t,e){return Mc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Mc(t,e)};function OS(t,e){Mc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var zc=function(){return zc=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},zc.apply(this,arguments)};function $S(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function TS(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function BS(t,e){return function(n,r){e(n,r,t)}}function PS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CS(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function RS(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function NS(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function US(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function qc(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qp(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function FS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qp(arguments[e]));return t}function kS(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Mi(t){return this instanceof Mi?(this.v=t,this):new Mi(t)}function LS(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){r[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Mi?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function MS(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Mi(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function zS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof qc=="function"?qc(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function qS(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 n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function VS(t){return t&&t.__esModule?t:{default:t}}function KS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function HS(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var WS=Object.freeze({__proto__:null,__extends:OS,get __assign(){return zc},__rest:$S,__decorate:TS,__param:BS,__metadata:PS,__awaiter:CS,__generator:RS,__createBinding:NS,__exportStar:US,__values:qc,__read:Qp,__spread:FS,__spreadArrays:kS,__await:Mi,__asyncGenerator:LS,__asyncDelegator:MS,__asyncValues:zS,__makeTemplateObject:qS,__importStar:jS,__importDefault:VS,__classPrivateFieldGet:KS,__classPrivateFieldSet:HS}),GS=fu(WS),un={},eg;function YS(){if(eg)return un;eg=1,Object.defineProperty(un,"__esModule",{value:!0}),un.isBrowserCryptoAvailable=un.getSubtleCrypto=un.getBrowerCrypto=void 0;function t(){return Ft?.crypto||Ft?.msCrypto||{}}un.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}un.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return un.isBrowserCryptoAvailable=n,un}var ln={},tg;function ZS(){if(tg)return ln;tg=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.isBrowser=ln.isNode=ln.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ln.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}ln.isNode=e;function n(){return!t()&&!e()}return ln.isBrowser=n,ln}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=GS;e.__exportStar(YS(),t),e.__exportStar(ZS(),t)})(Xp);function ot(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Ln(t=6){return BigInt(ot(t))}function hn(t,e,n){return{id:n||ot(),jsonrpc:"2.0",method:t,params:e}}function oo(t,e){return{id:t,jsonrpc:"2.0",result:e}}function jc(t,e,n){return{id:t,jsonrpc:"2.0",error:JS(e,n)}}function JS(t,e){return typeof t>"u"?Jp(Yp):(typeof t=="string"&&(t=Object.assign(Object.assign({},Jp(Lc)),{message:t})),typeof e<"u"&&(t.data=e),SS(t.code)&&(t=AS(t.code)),t)}class XS{}class QS extends XS{constructor(){super()}}class e6 extends QS{constructor(e){super()}}const t6="^wss?:";function n6(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function r6(t,e){const n=n6(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function ng(t){return r6(t,t6)}function i6(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function rg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Vc(t){return rg(t)&&"method"in t}function ao(t){return rg(t)&&(Kt(t)||It(t))}function Kt(t){return"result"in t}function It(t){return"error"in t}class s6 extends e6{constructor(e){super(e),this.events=new Ve.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(hn(e.method,e.params||[],e.id||Ln().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{It(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const o6=()=>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"),a6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",ig=t=>t.split("?")[0],sg=10,c6=o6();class u6{constructor(e){if(this.url=e,this.events=new Ve.exports.EventEmitter,this.registering=!1,!ng(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Hn(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!ng(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=Xp.isReactNative()?void 0:{rejectUnauthorized:!i6(e)},s=new c6(e,[],i);a6()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?gr(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=jc(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return DS(e,ig(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>sg&&this.events.setMaxListeners(sg)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${ig(this.url)}`));return this.events.emit("register_error",n),n}}const og="wc",ag=2,co="core",Ht=`${og}@2:${co}:`,l6={name:co,logger:"error"},h6={database:":memory:"},f6="crypto",cg="client_ed25519_seed",d6=M.ONE_DAY,p6="keychain",g6="0.3",y6="messages",w6="0.3",m6=M.SIX_HOURS,b6="publisher",ug="irn",v6="error",lg="wss://relay.walletconnect.org",E6="relayer",ge={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"},x6="_subscription",St={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},_6=.1,Kc="2.21.8",he={link_mode:"link_mode",relay:"relay"},uo={inbound:"inbound",outbound:"outbound"},I6="0.3",S6="WALLETCONNECT_CLIENT_ID",hg="WALLETCONNECT_LINK_MODE_APPS",dt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},A6="subscription",D6="0.3",O6="pairing",$6="0.3",zi={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},lr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Nt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},T6="history",B6="0.3",P6="expirer",At={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},C6="0.3",R6="verify-api",N6="https://verify.walletconnect.com",fg="https://verify.walletconnect.org",qi=fg,U6=`${qi}/v3`,F6=[N6,fg],k6="echo",L6="https://echo.walletconnect.com",Wt={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"},fn={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"},Mn={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"},ji={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"},hr={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"},Vi={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"},M6=.1,z6="event-client",q6=86400,j6="https://pulse.walletconnect.org/batch";function V6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var K6=V6,H6=K6;const dg=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")},W6=t=>new TextEncoder().encode(t),G6=t=>new TextDecoder().decode(t);class Y6{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Z6{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return pg(this,e)}}class J6{constructor(e){this.decoders=e}or(e){return pg(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const pg=(t,e)=>new J6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class X6{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new Y6(e,n,r),this.decoder=new Z6(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const lo=({name:t,prefix:e,encode:n,decode:r})=>new X6(t,e,n,r),Ki=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=H6(n,e);return lo({prefix:t,name:e,encode:r,decode:s=>dg(i(s))})},Q6=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},e4=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Ce=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>lo({prefix:e,name:t,encode(i){return e4(i,r,n)},decode(i){return Q6(i,r,n,t)}}),t4=lo({prefix:"\0",name:"identity",encode:t=>G6(t),decode:t=>W6(t)});var n4=Object.freeze({__proto__:null,identity:t4});const r4=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i4=Object.freeze({__proto__:null,base2:r4});const s4=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var o4=Object.freeze({__proto__:null,base8:s4});const a4=Ki({prefix:"9",name:"base10",alphabet:"0123456789"});var c4=Object.freeze({__proto__:null,base10:a4});const u4=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),l4=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var h4=Object.freeze({__proto__:null,base16:u4,base16upper:l4});const f4=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),d4=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),p4=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),g4=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),y4=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),w4=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),m4=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),b4=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),v4=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var E4=Object.freeze({__proto__:null,base32:f4,base32upper:d4,base32pad:p4,base32padupper:g4,base32hex:y4,base32hexupper:w4,base32hexpad:m4,base32hexpadupper:b4,base32z:v4});const x4=Ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_4=Ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var I4=Object.freeze({__proto__:null,base36:x4,base36upper:_4});const S4=Ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),A4=Ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var D4=Object.freeze({__proto__:null,base58btc:S4,base58flickr:A4});const O4=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$4=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),T4=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),B4=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var P4=Object.freeze({__proto__:null,base64:O4,base64pad:$4,base64url:T4,base64urlpad:B4});const gg=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}"),C4=gg.reduce((t,e,n)=>(t[n]=e,t),[]),R4=gg.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function N4(t){return t.reduce((e,n)=>(e+=C4[n],e),"")}function U4(t){const e=[];for(const n of t){const r=R4[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const F4=lo({prefix:"\u{1F680}",name:"base256emoji",encode:N4,decode:U4});var k4=Object.freeze({__proto__:null,base256emoji:F4}),L4=wg,yg=128,M4=127,z4=~M4,q4=Math.pow(2,31);function wg(t,e,n){e=e||[],n=n||0;for(var r=n;t>=q4;)e[n++]=t&255|yg,t/=128;for(;t&z4;)e[n++]=t&255|yg,t>>>=7;return e[n]=t|0,wg.bytes=n-r+1,e}var j4=Hc,V4=128,mg=127;function Hc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Hc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&mg)<<i:(o&mg)*Math.pow(2,i),i+=7}while(o>=V4);return Hc.bytes=s-r,n}var K4=Math.pow(2,7),H4=Math.pow(2,14),W4=Math.pow(2,21),G4=Math.pow(2,28),Y4=Math.pow(2,35),Z4=Math.pow(2,42),J4=Math.pow(2,49),X4=Math.pow(2,56),Q4=Math.pow(2,63),eA=function(t){return t<K4?1:t<H4?2:t<W4?3:t<G4?4:t<Y4?5:t<Z4?6:t<J4?7:t<X4?8:t<Q4?9:10},tA={encode:L4,decode:j4,encodingLength:eA},bg=tA;const vg=(t,e,n=0)=>(bg.encode(t,e,n),e),Eg=t=>bg.encodingLength(t),Wc=(t,e)=>{const n=e.byteLength,r=Eg(t),i=r+Eg(n),s=new Uint8Array(i+n);return vg(t,s,0),vg(n,s,r),s.set(e,i),new nA(t,n,e,s)};class nA{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const xg=({name:t,code:e,encode:n})=>new rA(t,e,n);class rA{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Wc(this.code,n):n.then(r=>Wc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const _g=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),iA=xg({name:"sha2-256",code:18,encode:_g("SHA-256")}),sA=xg({name:"sha2-512",code:19,encode:_g("SHA-512")});var oA=Object.freeze({__proto__:null,sha256:iA,sha512:sA});const Ig=0,aA="identity",Sg=dg;var cA=Object.freeze({__proto__:null,identity:{code:Ig,name:aA,encode:Sg,digest:t=>Wc(Ig,Sg(t))}});new TextEncoder,new TextDecoder;const Ag={...n4,...i4,...o4,...c4,...h4,...E4,...I4,...D4,...P4,...k4};({...oA,...cA});function Dg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function uA(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Dg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Og(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const $g=Og("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Gc=Og("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=uA(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),lA={utf8:$g,"utf-8":$g,hex:Ag.base16,latin1:Gc,ascii:Gc,binary:Gc,...Ag};function hA(t,e="utf8"){const n=lA[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Dg(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var fA=Object.defineProperty,dA=(t,e,n)=>e in t?fA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gt=(t,e,n)=>dA(t,typeof e!="symbol"?e+"":e,n);class pA{constructor(e,n){this.core=e,this.logger=n,Gt(this,"keychain",new Map),Gt(this,"name",p6),Gt(this,"version",g6),Gt(this,"initialized",!1),Gt(this,"storagePrefix",Ht),Gt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Gt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Gt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Gt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=z("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),Gt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,tc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?nc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gA=Object.defineProperty,yA=(t,e,n)=>e in t?gA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Re=(t,e,n)=>yA(t,typeof e!="symbol"?e+"":e,n);class wA{constructor(e,n,r){this.core=e,this.logger=n,Re(this,"name",f6),Re(this,"keychain"),Re(this,"randomSessionIdentifier",Rc()),Re(this,"initialized",!1),Re(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Re(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Re(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Gl(i);return Wl(s.publicKey)}),Re(this,"generateKeyPair",()=>{this.isInitialized();const i=cI();return this.setPrivateKey(i.publicKey,i.privateKey)}),Re(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Gl(s),a=this.randomSessionIdentifier;return await ub(a,i,d6,o)}),Re(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=uI(a,s);return this.setSymKey(c,o)}),Re(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ro(i);return await this.keychain.set(o,i),o}),Re(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Re(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Re(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Pp(o),c=Hn(s);if(Rp(a))return fI(c,o?.encoding);if(Cp(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(f,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return lI({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Re(this,"decode",async(i,s,o)=>{this.isInitialized();const a=pI(s,o);if(Rp(a)){const c=dI(s,o?.encoding);return gr(c)}if(Cp(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=hI({symKey:c,encoded:s,encoding:o?.encoding});return gr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Re(this,"getPayloadType",(i,s=it)=>{const o=Ni({encoded:i,encoding:s});return ur(o.type)}),Re(this,"getPayloadSenderPublicKey",(i,s=it)=>{const o=Ni({encoded:i,encoding:s});return o.senderPublicKey?et(o.senderPublicKey,Ye):void 0}),this.core=e,this.logger=Ke(n,this.name),this.keychain=r||new pA(this.core,this.logger)}get context(){return Je(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(cg)}catch{e=Rc(),await this.keychain.set(cg,e)}return hA(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mA=Object.defineProperty,bA=Object.defineProperties,vA=Object.getOwnPropertyDescriptors,Tg=Object.getOwnPropertySymbols,EA=Object.prototype.hasOwnProperty,xA=Object.prototype.propertyIsEnumerable,Yc=(t,e,n)=>e in t?mA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_A=(t,e)=>{for(var n in e||(e={}))EA.call(e,n)&&Yc(t,n,e[n]);if(Tg)for(var n of Tg(e))xA.call(e,n)&&Yc(t,n,e[n]);return t},IA=(t,e)=>bA(t,vA(e)),pt=(t,e,n)=>Yc(t,typeof e!="symbol"?e+"":e,n);class SA extends cw{constructor(e,n){super(e,n),this.logger=e,this.core=n,pt(this,"messages",new Map),pt(this,"messagesWithoutClientAck",new Map),pt(this,"name",y6),pt(this,"version",w6),pt(this,"initialized",!1),pt(this,"storagePrefix",Ht),pt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),pt(this,"set",async(r,i,s)=>{this.isInitialized();const o=_t(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===uo.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,IA(_A({},c),{[o]:i}))}return await this.persist(),o}),pt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),pt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),pt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=_t(i);return typeof s[o]<"u"}),pt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=_t(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),pt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ke(e,this.name),this.core=n}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,tc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,tc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?nc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?nc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AA=Object.defineProperty,DA=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,Bg=Object.getOwnPropertySymbols,$A=Object.prototype.hasOwnProperty,TA=Object.prototype.propertyIsEnumerable,Zc=(t,e,n)=>e in t?AA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fr=(t,e)=>{for(var n in e||(e={}))$A.call(e,n)&&Zc(t,n,e[n]);if(Bg)for(var n of Bg(e))TA.call(e,n)&&Zc(t,n,e[n]);return t},Pg=(t,e)=>DA(t,OA(e)),Dt=(t,e,n)=>Zc(t,typeof e!="symbol"?e+"":e,n);class BA extends uw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Dt(this,"events",new Ve.exports.EventEmitter),Dt(this,"name",b6),Dt(this,"queue",new Map),Dt(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),Dt(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),Dt(this,"needsTransportRestart",!1),Dt(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const h=s?.ttl||m6,f=s?.prompt||!1,p=s?.tag||0,d=s?.id||Ln().toString(),g=Rr(io().protocol),y={id:d,method:s?.publishMethod||g.publish,params:Fr({topic:r,message:i,ttl:h,prompt:f,tag:p,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},_=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{_e((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),_e((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const A=new Promise(async b=>{const v=({id:T})=>{var R;((R=y.id)==null?void 0:R.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(ge.publish,v),b())};this.relayer.events.on(ge.publish,v);const x=jt(new Promise((T,R)=>{this.rpcPublish(y,s).then(T).catch(C=>{this.logger.warn(C,C?.message),R(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await x,this.events.removeListener(ge.publish,v)}catch(T){this.queue.set(d,{request:y,opts:s,attempt:1}),this.logger.warn(T,T?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:i,opts:s}}),await jt(A,this.publishTimeout,_)}catch(A){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(A),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw A}finally{this.queue.delete(d)}}),Dt(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:l={}}=r,{attestation:h,tvf:f,publishMethod:p,prompt:d,tag:g,ttl:y=M.FIVE_MINUTES}=l,_=l.id||Ln().toString(),A=Rr(io().protocol),b=p||A.publish,v={id:_,method:b,params:Fr(Pg(Fr({},u),{ttl:y,prompt:d,tag:g,attestation:h}),f)},x=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{_e((i=v.params)==null?void 0:i.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const T=new Promise(async R=>{const C=({id:B})=>{var S;((S=v.id)==null?void 0:S.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(ge.publish,C),R())};this.relayer.events.on(ge.publish,C);const m=jt(new Promise((B,S)=>{this.rpcPublish(v,l).then(B).catch(O=>{this.logger.warn(O,O?.message),S(O)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${_} tag:${g}`);try{await m,this.events.removeListener(ge.publish,C)}catch(B){this.queue.set(_,{request:v,opts:l,attempt:1}),this.logger.warn(B,B?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:u,opts:l}}),await jt(T,this.publishTimeout,x)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw T}finally{this.queue.delete(_)}}),Dt(this,"on",(r,i)=>{this.events.on(r,i)}),Dt(this,"once",(r,i)=>{this.events.once(r,i)}),Dt(this,"off",(r,i)=>{this.events.off(r,i)}),Dt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ke(n,this.name),this.registerEventListeners()}get context(){return Je(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(ge.publish,Fr(Fr({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,Pg(Fr({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ge.connection_stalled);return}this.checkQueue()}),this.relayer.on(ge.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var PA=Object.defineProperty,CA=(t,e,n)=>e in t?PA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kr=(t,e,n)=>CA(t,typeof e!="symbol"?e+"":e,n);class RA{constructor(){kr(this,"map",new Map),kr(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),kr(this,"get",e=>this.map.get(e)||[]),kr(this,"exists",(e,n)=>this.get(e).includes(n)),kr(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),kr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var NA=Object.defineProperty,UA=Object.defineProperties,FA=Object.getOwnPropertyDescriptors,Cg=Object.getOwnPropertySymbols,kA=Object.prototype.hasOwnProperty,LA=Object.prototype.propertyIsEnumerable,Jc=(t,e,n)=>e in t?NA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hi=(t,e)=>{for(var n in e||(e={}))kA.call(e,n)&&Jc(t,n,e[n]);if(Cg)for(var n of Cg(e))LA.call(e,n)&&Jc(t,n,e[n]);return t},Xc=(t,e)=>UA(t,FA(e)),ce=(t,e,n)=>Jc(t,typeof e!="symbol"?e+"":e,n);class MA extends fw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,ce(this,"subscriptions",new Map),ce(this,"topicMap",new RA),ce(this,"events",new Ve.exports.EventEmitter),ce(this,"name",A6),ce(this,"version",D6),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Ht),ce(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=io(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),ce(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),ce(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ce(this,"on",(r,i)=>{this.events.on(r,i)}),ce(this,"once",(r,i)=>{this.events.once(r,i)}),ce(this,"off",(r,i)=>{this.events.off(r,i)}),ce(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Vn.pulse,async()=>{await this.checkPending()}),this.events.on(dt.created,async r=>{const i=dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(dt.deleted,async r=>{const i=dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ke(n,this.name),this.clientId=""}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=io(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Rr(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async h=>{const f=p=>{p.topic===e&&(this.events.removeListener(dt.created,f),h(p.id))};this.events.on(dt.created,f);try{const p=await jt(new Promise((d,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(dt.created,f),h(p)}catch{}}),l=await jt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ge.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Rr(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await jt(new Promise(i=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Rr(n.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await jt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Rr(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,Xc(Hi({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Hi({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,Hi({},n)),this.topicMap.set(n.topic,e),this.events.emit(dt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(dt.deleted,Xc(Hi({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(dt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(dt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async n=>Xc(Hi({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await Tx(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return _t(e+await this.getClientId())}}var zA=Object.defineProperty,Rg=Object.getOwnPropertySymbols,qA=Object.prototype.hasOwnProperty,jA=Object.prototype.propertyIsEnumerable,Qc=(t,e,n)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ng=(t,e)=>{for(var n in e||(e={}))qA.call(e,n)&&Qc(t,n,e[n]);if(Rg)for(var n of Rg(e))jA.call(e,n)&&Qc(t,n,e[n]);return t},ne=(t,e,n)=>Qc(t,typeof e!="symbol"?e+"":e,n);class VA extends lw{constructor(e){super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new Ve.exports.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",E6),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ne(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const s=n.id||Ln().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${s}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),ne(this,"resetPingTimeout",()=>{Ms()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(ge.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(ge.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(St.payload,this.onPayloadHandler),this.provider.on(St.connect,this.onConnectHandler),this.provider.on(St.disconnect,this.onDisconnectHandler),this.provider.on(St.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ke(e.logger,this.name):kt(Po({level:e.logger||v6})),this.messages=new SA(this.logger,e.core),this.subscriber=new MA(this,this.logger),this.publisher=new BA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg,px()?this.packageName=cd():gx()&&(this.bundleId=cd()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return Je(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:he.relay},uo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(dt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(dt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Ng({internal:{throwOnFailedPublish:o}},n)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await jt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Gp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const i=Ee(M.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(ge.message,e),await this.recordMessageEvent(e,uo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(St.disconnect,s),await jt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(St.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(St.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(St.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,M.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Ms())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new s6(new u6(vx({sdkVersion:Kc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Vc(e)){if(!e.method.endsWith(x6))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ng({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ao(e)&&this.events.emit(ge.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,uo.inbound),this.events.emit(ge.message,e))}async acknowledgePayload(e){const n=oo(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(St.payload,this.onPayloadHandler),this.provider.off(St.connect,this.onConnectHandler),this.provider.off(St.disconnect,this.onDisconnectHandler),this.provider.off(St.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Gp();cS(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ge.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},M.toMiliseconds(_6)))))}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function KA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ug(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Fg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const HA="[object RegExp]",WA="[object String]",GA="[object Number]",YA="[object Boolean]",kg="[object Arguments]",ZA="[object Symbol]",JA="[object Date]",XA="[object Map]",QA="[object Set]",eD="[object Array]",tD="[object Function]",nD="[object ArrayBuffer]",eu="[object Object]",rD="[object Error]",iD="[object DataView]",sD="[object Uint8Array]",oD="[object Uint8ClampedArray]",aD="[object Uint16Array]",cD="[object Uint32Array]",uD="[object BigUint64Array]",lD="[object Int8Array]",hD="[object Int16Array]",fD="[object Int32Array]",dD="[object BigInt64Array]",pD="[object Float32Array]",gD="[object Float64Array]";function yD(){}function Lg(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 wD(t,e,n){return Wi(t,e,void 0,void 0,void 0,void 0,n)}function Wi(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Gi(t,e,s,o)}return Gi(t,e,s,o)}function Gi(t,e,n,r){if(Object.is(t,e))return!0;let i=Fg(t),s=Fg(e);if(i===kg&&(i=eu),s===kg&&(s=eu),i!==s)return!1;switch(i){case WA:return t.toString()===e.toString();case GA:{const c=t.valueOf(),u=e.valueOf();return KA(c,u)}case YA:case JA:case ZA:return Object.is(t.valueOf(),e.valueOf());case HA:return t.source===e.source&&t.flags===e.flags;case tD:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case XA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Wi(u,e.get(c),c,t,e,n,r))return!1;return!0}case QA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>Wi(h,p,void 0,t,e,n,r));if(f===-1)return!1;u.splice(f,1)}return!0}case eD:case sD:case oD:case aD:case cD:case uD:case lD:case hD:case fD:case dD:case pD:case gD:{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(!Wi(t[c],e[c],c,t,e,n,r))return!1;return!0}case nD:return t.byteLength!==e.byteLength?!1:Gi(new Uint8Array(t),new Uint8Array(e),n,r);case iD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Gi(new Uint8Array(t),new Uint8Array(e),n,r);case rD:return t.name===e.name&&t.message===e.message;case eu:{if(!(Gi(t.constructor,e.constructor,n,r)||Lg(t)&&Lg(e)))return!1;const c=[...Object.keys(t),...Ug(t)],u=[...Object.keys(e),...Ug(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Wi(f,p,h,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function mD(t,e){return wD(t,e,yD)}var bD=Object.defineProperty,Mg=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,tu=(t,e,n)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zg=(t,e)=>{for(var n in e||(e={}))vD.call(e,n)&&tu(t,n,e[n]);if(Mg)for(var n of Mg(e))ED.call(e,n)&&tu(t,n,e[n]);return t},at=(t,e,n)=>tu(t,typeof e!="symbol"?e+"":e,n);class fr extends hw{constructor(e,n,r,i=Ht,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,at(this,"map",new Map),at(this,"version",I6),at(this,"cached",[]),at(this,"initialized",!1),at(this,"getKey"),at(this,"storagePrefix",Ht),at(this,"recentlyDeleted",[]),at(this,"recentlyDeletedLimit",200),at(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):LI(o)?this.map.set(o.id,o):MI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),at(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())}),at(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),at(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>mD(a[c],o[c]))):this.values)),at(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=zg(zg({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),at(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=Ke(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xD=Object.defineProperty,_D=(t,e,n)=>e in t?xD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,J=(t,e,n)=>_D(t,typeof e!="symbol"?e+"":e,n);class ID{constructor(e,n){this.core=e,this.logger=n,J(this,"name",O6),J(this,"version",$6),J(this,"events",new Ve.exports),J(this,"pairings"),J(this,"initialized",!1),J(this,"storagePrefix",Ht),J(this,"ignoredPayloadTypes",[cn]),J(this,"registeredMethods",[]),J(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),J(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),J(this,"create",async r=>{this.isInitialized();const i=Rc(),s=await this.core.crypto.setSymKey(i),o=Ee(M.FIVE_MINUTES),a={protocol:ug},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=Up({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(lr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:u}}),J(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Wt.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Np(r.uri);i.props.properties.topic=s,i.addTrace(Wt.pairing_uri_validation_success),i.addTrace(Wt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Wt.existing_pairing),l.active)throw i.setError(fn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Wt.pairing_not_expired)}const h=c||Ee(M.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),i.addTrace(Wt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(lr.create,f),i.addTrace(Wt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(fn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(fn.subscribe_pairing_topic_failure),p}return i.addTrace(Wt.subscribe_pairing_topic_success),f}),J(this,"activate",async({topic:r})=>{this.isInitialized();const i=Ee(M.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),J(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=rr();this.events.once(re("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),J(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),J(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),J(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),J(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),J(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return Up({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),J(this,"sendRequest",async(r,i,s)=>{const o=hn(i,s),a=await this.core.crypto.encode(r,o),c=zi[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),J(this,"sendResult",async(r,i,s)=>{const o=oo(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=zi[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"sendError",async(r,i,s)=>{const o=jc(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=zi[c]?zi[c].res:zi.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),J(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>An(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),J(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),J(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),J(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(lr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),J(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{Kt(i)?this.events.emit(re("pairing_ping",s),{}):It(i)&&this.events.emit(re("pairing_ping",s),{error:i.error})},500)}),J(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(lr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),J(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),J(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),J(this,"isValidPair",(r,i)=>{var s;if(!st(r)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(!kI(r.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(fn.malformed_pairing_uri),new Error(a)}const o=Np(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(fn.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),J(this,"isValidPing",async r=>{if(!st(r)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),J(this,"isValidDisconnect",async r=>{if(!st(r)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),J(this,"isValidPairingTopic",async r=>{if(!we(r,!1)){const{message:i}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(An(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=z("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ke(n,this.name),this.pairings=new fr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Je(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ge.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Vc(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(At.expired,async e=>{const{topic:n}=fd(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(lr.expire,{topic:n}))})}}var SD=Object.defineProperty,AD=(t,e,n)=>e in t?SD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ne=(t,e,n)=>AD(t,typeof e!="symbol"?e+"":e,n);class DD extends aw{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ne(this,"records",new Map),Ne(this,"events",new Ve.exports.EventEmitter),Ne(this,"name",T6),Ne(this,"version",B6),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Ht),Ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ne(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:Ee(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Nt.created,o)}),Ne(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=It(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Nt.updated,i))}),Ne(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Ne(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Nt.deleted,s)}}),this.persist()}),Ne(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ne(this,"on",(r,i)=>{this.events.on(r,i)}),Ne(this,"once",(r,i)=>{this.events.once(r,i)}),Ne(this,"off",(r,i)=>{this.events.off(r,i)}),Ne(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:hn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Nt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Nt.created,e=>{const n=Nt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Nt.updated,e=>{const n=Nt.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Nt.deleted,e=>{const n=Nt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Vn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{M.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(Nt.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var OD=Object.defineProperty,$D=(t,e,n)=>e in t?OD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qe=(t,e,n)=>$D(t,typeof e!="symbol"?e+"":e,n);class TD extends dw{constructor(e,n){super(e,n),this.core=e,this.logger=n,qe(this,"expirations",new Map),qe(this,"events",new Ve.exports.EventEmitter),qe(this,"name",P6),qe(this,"version",C6),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"storagePrefix",Ht),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),qe(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),qe(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(At.created,{target:s,expiration:o})}),qe(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),qe(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(At.deleted,{target:i,expiration:s})}}),qe(this,"on",(r,i)=>{this.events.on(r,i)}),qe(this,"once",(r,i)=>{this.events.once(r,i)}),qe(this,"off",(r,i)=>{this.events.off(r,i)}),qe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Ex(e);if(typeof e=="number")return xx(e);const{message:n}=z("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(At.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;M.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(At.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Vn.pulse,()=>this.checkExpirations()),this.events.on(At.created,e=>{const n=At.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(At.expired,e=>{const n=At.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(At.deleted,e=>{const n=At.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var BD=Object.defineProperty,PD=(t,e,n)=>e in t?BD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,me=(t,e,n)=>PD(t,typeof e!="symbol"?e+"":e,n);class CD extends pw{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,me(this,"name",R6),me(this,"abortController"),me(this,"isDevEnv"),me(this,"verifyUrlV3",U6),me(this,"storagePrefix",Ht),me(this,"version",ag),me(this,"publicKey"),me(this,"fetchPromise"),me(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),me(this,"register",async i=>{if(!Dr()||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=Yn(),l=this.startAbortTimer(M.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",y),u.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",d,{signal:this.abortController.signal});const y=_=>{if(_.data&&typeof _.data=="string")try{const A=JSON.parse(_.data);if(A.type==="verify_attestation"){if(Qo(A.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",y),f(A.attestation===null?"":A.attestation)}}catch(A){this.logger.warn(A)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),me(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(Qo(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)}),me(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),me(this,"getVerifyUrl",i=>{let s=i||qi;return F6.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${qi}`),s=qi),s}),me(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),me(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),me(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),me(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")}}),me(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),me(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}),me(this,"validateAttestation",(i,s)=>{const o=yI(i,s.publicKey),a={hasExpired:M.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ke(n,this.name),this.abortController=new AbortController,this.isDevEnv=rc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Je(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var RD=Object.defineProperty,ND=(t,e,n)=>e in t?RD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qg=(t,e,n)=>ND(t,typeof e!="symbol"?e+"":e,n);class UD extends gw{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,qg(this,"context",k6),qg(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${L6}/${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=Ke(n,this.context)}}var FD=Object.defineProperty,jg=Object.getOwnPropertySymbols,kD=Object.prototype.hasOwnProperty,LD=Object.prototype.propertyIsEnumerable,nu=(t,e,n)=>e in t?FD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yi=(t,e)=>{for(var n in e||(e={}))kD.call(e,n)&&nu(t,n,e[n]);if(jg)for(var n of jg(e))LD.call(e,n)&&nu(t,n,e[n]);return t},De=(t,e,n)=>nu(t,typeof e!="symbol"?e+"":e,n);class MD extends yw{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,De(this,"context",z6),De(this,"storagePrefix",Ht),De(this,"storageVersion",M6),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!rc())try{const i={eventId:pd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:ld(this.core.relayer.protocol,this.core.relayer.version,Kc)}}};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=pd(),l=this.core.projectId||"",h=Date.now(),f=Yi({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),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 Yi(Yi({},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(Vn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>q6&&(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,Yi(Yi({},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(`${j6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Kc}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>ud().url),this.logger=Ke(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var zD=Object.defineProperty,Vg=Object.getOwnPropertySymbols,qD=Object.prototype.hasOwnProperty,jD=Object.prototype.propertyIsEnumerable,ru=(t,e,n)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kg=(t,e)=>{for(var n in e||(e={}))qD.call(e,n)&&ru(t,n,e[n]);if(Vg)for(var n of Vg(e))jD.call(e,n)&&ru(t,n,e[n]);return t},le=(t,e,n)=>ru(t,typeof e!="symbol"?e+"":e,n);class iu extends rw{constructor(e){var n;super(e),le(this,"protocol",og),le(this,"version",ag),le(this,"name",co),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new Ve.exports.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Po({level:typeof e?.logger=="string"&&e.logger?e.logger:l6.logger,name:co}),{logger:s,chunkLoggerController:o}=ew({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ke(s,this.name),this.heartbeat=new So,this.crypto=new wA(this,this.logger,e?.keychain),this.history=new DD(this,this.logger),this.expirer=new TD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Ay(Kg(Kg({},h6),e?.storageOptions)),this.relayer=new VA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ID(this,this.logger),this.verify=new CD(this,this.logger,this.storage),this.echoClient=new UD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new MD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new iu(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(S6,r),n}get context(){return Je(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(hg,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(hg)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const VD=iu,Hg="wc",Wg=2,Gg="client",su=`${Hg}@${Wg}:${Gg}:`,ou={name:Gg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Yg="WALLETCONNECT_DEEPLINK_CHOICE",KD="proposal",Zg="Proposal expired",HD="session",Lr=M.SEVEN_DAYS,WD="engine",Ue={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},au={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Yt={idle:"IDLE",active:"ACTIVE"},GD={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},YD="request",ZD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],JD="wc",XD="auth",QD="authKeys",e5="pairingTopics",t5="requests",ho=`${JD}@${1.5}:${XD}:`,fo=`${ho}:PUB_KEY`;var n5=Object.defineProperty,r5=Object.defineProperties,i5=Object.getOwnPropertyDescriptors,Jg=Object.getOwnPropertySymbols,s5=Object.prototype.hasOwnProperty,o5=Object.prototype.propertyIsEnumerable,cu=(t,e,n)=>e in t?n5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ie=(t,e)=>{for(var n in e||(e={}))s5.call(e,n)&&cu(t,n,e[n]);if(Jg)for(var n of Jg(e))o5.call(e,n)&&cu(t,n,e[n]);return t},je=(t,e)=>r5(t,i5(e)),k=(t,e,n)=>cu(t,typeof e!="symbol"?e+"":e,n);class a5 extends vw{constructor(e){super(e),k(this,"name",WD),k(this,"events",new Ve.exports),k(this,"initialized",!1),k(this,"requestQueue",{state:Yt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:Yt.idle,queue:[]}),k(this,"emittedSessionRequests",new Bx({limit:500})),k(this,"requestQueueDelay",M.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Ue)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=je(ie({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=CI(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=r;let l=i,h,f=!1;try{if(l){const T=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),T}if(!l||!f){const{topic:T,uri:R}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=T,h=R}if(!l){const{message:T}=z("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(T)}const p=await this.client.core.crypto.generateKeyPair(),d=Ue.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=Ee(d),y=je(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:ug}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:ot()}),_=re("session_connect",y.id),{reject:A,resolve:b,done:v}=rr(d,Zg),x=({id:T})=>{T===y.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(y.id),this.events.emit(_,{error:{message:Zg,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(_,({error:T,session:R})=>{this.client.events.off("proposal_expire",x),T?A(T):R&&b(R)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:h,approval:v}}),k(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),k(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[Mn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(m){throw o.setError(ji.no_internet_connection),m}try{await this.isValidProposalId(n?.id)}catch(m){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(ji.proposal_not_found),m}try{await this.isValidApprove(n)}catch(m){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ji.session_approve_namespace_validation_failure),m}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:g,requiredNamespaces:y,optionalNamespaces:_}=p;let A=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});A||(A=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Mn.session_approve_started,properties:{topic:d,trace:[Mn.session_approve_started,Mn.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),v=g.publicKey,x=await this.client.core.crypto.generateSharedKey(b,v),T=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:Ee(Lr)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),R=he.relay;A.addTrace(Mn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:R,internal:{skipSubscribe:!0}})}catch(m){throw A.setError(ji.subscribe_session_topic_failure),m}A.addTrace(Mn.subscribe_session_topic_success);const C=je(ie({},T),{topic:x,requiredNamespaces:y,optionalNamespaces:_,pairingTopic:d,acknowledged:!1,self:T.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:b,transportType:he.relay});await this.client.session.set(x,C),A.addTrace(Mn.store_session);try{await this.sendApproveSession({sessionTopic:x,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:b},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),A.addTrace(Mn.session_approve_publish_success)}catch(m){throw this.client.logger.error(m),this.client.session.delete(x,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),m}return this.client.core.eventClient.deleteEvent({eventId:A.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(x,Ee(Lr)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),k(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Ue.wc_sessionPropose.reject}),await this.deleteProposal(r)}),k(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=rr(),c=ot(),u=Ln().toString(),l=this.client.session.get(r).namespaces;return this.events.once(re("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=ot(),{done:s,resolve:o,reject:a}=rr();return this.events.once(re("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Ee(Lr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Ue.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const c=ot(),u=Ln().toString(),{done:l,resolve:h,reject:f}=rr(o,"Request expired. Please try again.");this.events.once(re("session_request",c),({error:y,result:_})=>{y?f(y):h(_)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:je(ie({},i),{expiryTimestamp:Ee(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(y=>f(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:je(ie({},i),{expiryTimestamp:Ee(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const A=await Ax(this.client.core.storage,Yg);await _x({id:c,topic:s,wcDeepLink:A})}y()}),l()]).then(y=>y[2])}),k(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:s}=i,o=this.client.session.get(r);o.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Kt(i)?await this.sendResult({id:s,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):It(i)&&await this.sendError({id:s,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(n)}),k(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ot(),s=Ln().toString(),{done:o,resolve:a,reject:c}=rr();this.events.once(re("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),k(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=Ln().toString(),a=ot();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),k(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UI(r,n)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:g=[],expiry:y}=n,_=[...n.resources||[]],{topic:A,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),x=ro(v);if(await Promise.all([this.client.auth.authKeys.set(fo,{responseTopic:x,publicKey:v}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:A})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${A}`),g.length>0){const{namespace:D}=tr(a[0]);let N=z_(D,"request",g);Ks(_)&&(N=j_(N,_.pop())),_.push(N)}const T=y&&y>Ue.wc_sessionAuthenticate.req.ttl?y:Ue.wc_sessionAuthenticate.req.ttl,R={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ee(T)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},m={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:A,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ee(Ue.wc_sessionPropose.req.ttl),id:ot()},{done:B,resolve:S,reject:O}=rr(T,"Request expired"),P=ot(),F=re("session_connect",m.id),E=re("session_request",P),w=async({error:D,session:N})=>{this.events.off(E,I),D?O(D):N&&S({session:N})},I=async D=>{var N,U,L;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),D.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===W.code?void 0:(this.events.off(F,w),O(D.error.message))}await this.deleteProposal(m.id),this.events.off(F,w);const{cacaos:j,responder:V}=D.result,K=[],H=[];for(const W of j){await kd({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),O(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ae}=W,ye=Ks(ae.resources),gt=[gc(ae.iss)],Ot=Vs(ae.iss);if(ye){const $t=zd(ye),Zt=qd(ye);K.push(...$t),gt.push(...Zt)}for(const $t of gt)H.push(`${$t}:${Ot}`)}const Z=await this.client.core.crypto.generateSharedKey(v,V.publicKey);let Q;K.length>0&&(Q={topic:Z,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:Ee(Lr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:zp([...new Set(K)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(Z,{transportType:o}),await this.client.session.set(Z,Q),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:V.metadata}),Q=this.client.session.get(Z)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(L=V.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(Z,{transportType:he.link_mode})),S({auths:j,session:Q})};this.events.once(F,w),this.events.once(E,I);let $;try{if(s){const D=hn("wc_sessionAuthenticate",R,P);this.client.core.history.set(A,D);const N=await this.client.core.crypto.encode("",D,{type:Ci,encoding:kn});$=so(r,A,N)}else await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:R,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:m,expiry:Ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:m.id})])}catch(D){throw this.events.off(F,w),this.events.off(E,I),D}return await this.setProposal(m.id,m),await this.setAuthRequest(P,{request:je(ie({},R),{verifyContext:{}}),pairingTopic:A,transportType:o}),{uri:$??b,response:B}}),k(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[hr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Vi.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Vi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ro(c),h={type:cn,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const y of i){if(!await kd({cacao:y,projectId:this.client.core.projectId})){s.setError(Vi.invalid_cacao);const x=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:x,encodeOpts:h}),new Error(x.message)}s.addTrace(hr.cacaos_verified);const{p:_}=y,A=Ks(_.resources),b=[gc(_.iss)],v=Vs(_.iss);if(A){const x=zd(A),T=qd(A);f.push(...x),b.push(...T)}for(const x of b)p.push(`${x}:${v}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(hr.create_authenticated_session_topic);let g;if(f?.length>0){g={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Ee(Lr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:zp([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(hr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw s.setError(Vi.subscribe_authenticated_session_topic_failure),y}s.addTrace(hr.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),s.addTrace(hr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(hr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Vi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ro(o),u={type:cn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ue.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),k(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return Ld(r,i)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),k(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),k(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Yg).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),k(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(ji.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),k(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=Yt.idle,this.client.events.emit("session_request_expire",{id:n}))}),k(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),k(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),k(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Ee(Ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),k(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=he.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Ee(Ue.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),k(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=n,p=hn(i,s,c);let d;const g=!!l;try{const A=g?kn:it;d=await this.client.core.crypto.encode(r,p,{encoding:A})}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),A}let y;if(ZD.includes(i)){const A=_t(JSON.stringify(p)),b=_t(d);y=await this.client.core.verify.register({id:b,decryptedId:A})}const _=ie(ie({},Ue[i].req),f);if(_.attestation=y,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(r,p),g){const A=so(l,r,d);await global.Linking.openURL(A,this.client.name)}else _.tvf=je(ie({},h),{correlationId:p.id}),u?(_.internal=je(ie({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,_)):this.client.core.relayer.publish(r,d,_).catch(A=>this.client.logger.error(A));return p.id}),k(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=hn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:it}),a=_t(JSON.stringify(s)),c=_t(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:je(ie({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=oo(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:it}),l=hn("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(r,l,{encoding:it});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:je(ie({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=oo(r,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?kn:it;l=await this.client.core.crypto.encode(i,u,je(ie({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),d}let f,p;try{f=await this.client.core.history.get(i,r);const d=f.request;try{p=this.getTVFParams(r,d.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),d}if(h){const d=so(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=Ue[d].res;g.tvf=je(ie({},p),{correlationId:r}),o?(g.internal=je(ie({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),k(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=jc(r,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?kn:it;l=await this.client.core.crypto.encode(i,u,je(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let f;try{f=await this.client.core.history.get(i,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),p}if(h){const p=so(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Ue[p].res;this.client.core.relayer.publish(i,l,d)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;An(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{An(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),k(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),k(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Yt.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=Yt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Yt.idle}),k(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=z("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),k(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(fn.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||Ee(Ue.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:_t(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ue.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(Kt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const 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:n})}else if(It(r)){await this.deleteProposal(s);const o=re("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),k(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=r.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const d=this.client.proposal.get(p.proposalId),g=je(ie(ie(ie({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(re("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;Kt(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(re("session_approve",i),{})):It(r)&&(await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.events.emit(re("session_approve",i),{error:r.error}))}),k(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=ki.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:n},i));try{ki.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw ki.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=re("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_update",i),{}):It(r)&&this.events.emit(re("session_update",i),{error:r.error})}),k(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Ee(Lr)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=re("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_extend",i),{}):It(r)&&this.events.emit(re("session_extend",i),{error:r.error})}),k(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=re("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Kt(r)?this.events.emit(re("session_ping",i),{}):It(r)&&this.events.emit(re("session_ping",i),{error:r.error})},500)}),k(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(ge.publish,async()=>{s(await this.deleteSession({topic:n,id:i}))})}),this.sendResult({id:i,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:h,params:f}=a;try{await this.isValidRequest(ie({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:_t(JSON.stringify(hn("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(g),l===he.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),k(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=re("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_request",i),{result:r.result}):It(r)&&this.events.emit(re("session_request",i),{error:r.error})}),k(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=ki.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ie({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),ki.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),Kt(r)?this.events.emit(re("session_request",i),{result:r.result}):It(r)&&this.events.emit(re("session_request",i),{error:r.error})}),k(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:_t(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===he.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:cn,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Ue.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),k(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Yt.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=re("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(re("session_request",s.request.id),{error:r})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Yt.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),k(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=Yt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),k(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:hn("wc_sessionPropose",je(ie({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),k(this,"isValidConnect",async n=>{if(!st(n)){const{message:u}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(_e(r)||await this.isValidPairingTopic(r),!GI(c,!0)){const{message:u}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!_e(i)&&Ui(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!_e(s)&&Ui(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),k(this,"validateNamespaces",(n,r)=>{const i=WI(n,"connect()",r);if(i)throw new Error(i.message)}),k(this,"isValidApprove",async n=>{if(!st(n))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=Uc(i,"approve()");if(u)throw new Error(u.message);const l=Hp(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!we(s,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async n=>{if(!st(n)){const{message:s}=z("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!ZI(i)){const{message:s}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",n=>{if(!st(n)){const{message:u}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!Vp(r)){const{message:u}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=zI(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Uc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(An(o)){const{message:u}=z("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async n=>{if(!st(n)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=Uc(i,"update()");if(o)throw new Error(o.message);const a=Hp(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),k(this,"isValidRequest",async n=>{if(!st(n)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Kp(a,s)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!JI(i)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!eS(a,s,i.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!iS(o,au)){const{message:c}=z("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${au.min} and ${au.max}`);throw new Error(c)}}),k(this,"isValidRespond",async n=>{var r;if(!st(n)){const{message:o}=z("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!XI(s)){const{message:o}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),k(this,"isValidPing",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidEmit",async n=>{if(!st(n)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Kp(o,s)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!QI(i)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!tS(o,s,i.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!we(i,!1))throw new Error("uri is required parameter");if(!we(s,!1))throw new Error("domain is required parameter");if(!we(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>tr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=tr(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||qi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=z("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),k(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),k(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,h,f;return!n||r!==he.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((h=n?.redirect)==null?void 0:h.universal)!==""&&((f=n?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),k(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=dd(n,"topic")||"",i=decodeURIComponent(dd(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var n;if(rc()||Sn()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),k(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),k(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=GD[s];if(s==="sui_signTransaction")return[S_(r.transactionBytes)];if(s==="near_signTransaction")return[Rd(r)];if(s==="near_signTransactions")return r.map(c=>Rd(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[bS({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Ur(r)?r.map(c=>Nd(c)):[Nd(r)];if(s==="cosmos_signDirect")return[D_(r)];if(typeof r=="string")return[r];const a=r[o.key];if(Ur(a))return s==="solana_signAllTransactions"?a.map(c=>I_(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ge.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(fo)?this.client.auth.authKeys.get(fo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===he.link_mode?kn:it});Vc(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:_t(r)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(At.expired,async e=>{const{topic:n,id:r}=fd(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,z("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,z("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(lr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(lr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!we(e,!1)){const{message:n}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!we(e,!1)){const{message:n}=z("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=z("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=z("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(we(e,!1)){const{message:n}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!YI(e)){const{message:n}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=z("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class c5 extends fr{constructor(e,n){super(e,n,KD,su),this.core=e,this.logger=n}}class u5 extends fr{constructor(e,n){super(e,n,HD,su),this.core=e,this.logger=n}}class l5 extends fr{constructor(e,n){super(e,n,YD,su,r=>r.id),this.core=e,this.logger=n}}class h5 extends fr{constructor(e,n){super(e,n,QD,ho,()=>fo),this.core=e,this.logger=n}}class f5 extends fr{constructor(e,n){super(e,n,e5,ho),this.core=e,this.logger=n}}class d5 extends fr{constructor(e,n){super(e,n,t5,ho,r=>r.id),this.core=e,this.logger=n}}var p5=Object.defineProperty,g5=(t,e,n)=>e in t?p5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,uu=(t,e,n)=>g5(t,typeof e!="symbol"?e+"":e,n);class y5{constructor(e,n){this.core=e,this.logger=n,uu(this,"authKeys"),uu(this,"pairingTopics"),uu(this,"requests"),this.authKeys=new h5(this.core,this.logger),this.pairingTopics=new f5(this.core,this.logger),this.requests=new d5(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var w5=Object.defineProperty,m5=(t,e,n)=>e in t?w5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,X=(t,e,n)=>m5(t,typeof e!="symbol"?e+"":e,n);class lu extends bw{constructor(e){super(e),X(this,"protocol",Hg),X(this,"version",Wg),X(this,"name",ou.name),X(this,"metadata"),X(this,"core"),X(this,"logger"),X(this,"events",new Ve.exports.EventEmitter),X(this,"engine"),X(this,"session"),X(this,"proposal"),X(this,"pendingRequest"),X(this,"auth"),X(this,"signConfig"),X(this,"on",(r,i)=>this.events.on(r,i)),X(this,"once",(r,i)=>this.events.once(r,i)),X(this,"off",(r,i)=>this.events.off(r,i)),X(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),X(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),X(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),X(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),X(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||ou.name,this.metadata=wx(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:kt(Po({level:e?.logger||ou.logger}));this.core=e?.core||new VD(e),this.logger=Ke(n,this.name),this.session=new u5(this.core,this.logger),this.proposal=new c5(this.core,this.logger),this.pendingRequest=new l5(this.core,this.logger),this.engine=new a5(this),this.auth=new y5(this.core,this.logger)}static async init(e){const n=new lu(e);return await n.initialize(),n}get context(){return Je(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const b5=lu;class Xg{constructor(e){this.opts=e}}class Qg{constructor(e){this.client=e}}const e0=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Fi(r?.chainId))return!1;const{namespace:a}=tr(r.chainId),c=e.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(u=>u.toLowerCase()).includes(s?.toLowerCase()))throw new Error(`Unsupported token standard: ${s} for namespace: ${a}`);return!0},v5=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!e0({supportedNamespaces:e,token:r}))};var E5=Object.defineProperty,x5=(t,e,n)=>e in t?E5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,de=(t,e,n)=>x5(t,typeof e!="symbol"?e+"":e,n);class _5 extends Qg{constructor(e){var n;super(e),de(this,"signClient"),de(this,"tokens",[]),de(this,"paymentIntentsMap",new Map),de(this,"paymentIntentToTransactionsMap",new Map),de(this,"supportedNamespaces",Du),de(this,"logger"),de(this,"init",async()=>{var r,i;this.signClient=await b5.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((r=this.client.opts.storageOptions)==null?void 0:r.databaseName)||Iu.database},logger:(i=this.client.opts.loggerOptions)==null?void 0:i.signLevel});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest(JSON.stringify({id:ot(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}));this.logger.debug("Received supported namespaces/networks",{supportedNamespaces:s.result.namespaces}),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error("Failed to fetch supported namespaces/networks",s)}}),de(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug("Setting tokens",{tokens:i}),i.forEach(s=>{if(!e0({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=i,s()}),this.logger.debug("Tokens set",{tokens:i})}),de(this,"createPaymentIntent",async r=>{const{paymentIntents:i}=r;if(this.logger.debug("Creating payment intent",{paymentIntents:i}),i.length===0)throw new Error("No payment intents provided");i.forEach(u=>{if(!v5({paymentIntent:u,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(u)}`)}),this.logger.debug("Payment intent validation success",{paymentIntents:i});const s=this.composeNamespaces(i),{uri:o,approval:a}=await this.signClient.connect({optionalNamespaces:s});if(this.logger.debug("Connected to the WalletConnect network",{uri:o}),!o)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001}}),new Error("Failed to connect to the WalletConnect network");const c=ot();this.paymentIntentsMap.set(c,i),this.logger.debug("Payment intents map set",{intentId:c,paymentIntents:i}),this.emit("await_approval",{approval:a,intentId:c}),this.logger.debug("Emitted await_approval event",{intentId:c}),this.emit("qr_ready",{uri:o}),this.logger.debug("Emitted qr_ready event",{uri:o})}),de(this,"restart",async r=>{if(this.logger.debug("Restarting",{params:r}),r!=null&&r.reinit){this.tokens=[],this.paymentIntentsMap.clear(),this.paymentIntentToTransactionsMap.clear(),this.logger.debug("Restarted: Cleared payment intents map and payment intent to transactions map");return}const i=Array.from(this.paymentIntentsMap.values()).flat();await this.createPaymentIntent({paymentIntents:i}),this.logger.debug("Restarted: Created payment intent flow from the beginning",{paymentIntents:i})}),de(this,"emit",(r,i)=>(this.logger.debug("Emit",{event:r,args:i}),this.client.events.emit(r,i))),de(this,"on",(r,i)=>(this.logger.debug("On",{event:r,listener:i}),this.client.events.on(r,i))),de(this,"once",(r,i)=>(this.logger.debug("Once",{event:r,listener:i}),this.client.events.once(r,i))),de(this,"off",(r,i)=>(this.logger.debug("Off",{event:r,listener:i}),this.client.events.off(r,i))),de(this,"removeListener",(r,i)=>(this.logger.debug("Remove listener",{event:r,listener:i}),this.client.events.removeListener(r,i))),de(this,"prepareTransactionsFromPaymentIntents",async r=>{this.logger.debug("Preparing transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic});const{intentId:i,session:s}=r,o=this.paymentIntentsMap.get(i);if(!o)throw new Error(`Payment intents not found for id: ${i}`);const a=[];for(const h of o){const{token:f,amount:p,recipient:d}=h,{namespace:g}=tr(f.network.chainId),y=s.namespaces[g].accounts.find(_=>_.includes(`${f.network.chainId}:`));if(!y)throw new Error(`Address not found in session for chain id: ${f.network.chainId}, approved addresses: ${s.namespaces[g].accounts.join(", ")}`);a.push({asset:`${f.network.chainId}/${f.standard.toLowerCase()}:${f.address}`,recipient:d,amount:p,sender:y})}this.logger.debug("Prepared transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic,transactions:a});const c={id:ot(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:a}};this.logger.debug("Fetching wc_pos_buildTransactions",{payload:c});const u=await this.fetchRpcRequest(JSON.stringify(c));this.logger.debug("Received wc_pos_buildTransactions",{response:u});const l=u.result.transactions;return this.paymentIntentToTransactionsMap.set(i,l),this.logger.debug("Payment intent to transactions map set",{intentId:r.intentId,transactions:l}),l}),de(this,"onSessionConnected",async r=>{const{intentId:i,session:s}=r;this.logger.debug("On session connected",{intentId:i,sessionTopic:s.topic}),this.emit("connected",{session:s}),this.logger.debug("Emitted connected event");try{const o=await this.prepareTransactionsFromPaymentIntents({intentId:i,session:s});this.logger.debug("Transactions prepared",{transactions:o}),this.sendTransactionsToWallet({transactions:o,session:s,intentId:i})}catch(o){this.logger.error(o)}}),de(this,"sendTransactionsToWallet",async r=>{const{transactions:i,session:s,intentId:o}=r;this.logger.debug("Sending transactions to wallet",{transactions:i,sessionTopic:s.topic,intentId:o});const a=this.paymentIntentsMap.get(o);if(!a)throw new Error(`Payment intents not found for id: ${o}`);for(let c=0;c<i.length;c++){const u=i[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u}),this.logger.debug("Emitted payment_requested event",{transactionId:u.id});let h;try{h=await this.signClient.request({topic:s.topic,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug("Wallet responded to payment request",{transactionId:u.id,result:h})}catch(f){throw this.logger.error("error",f),this.emit("payment_rejected",{error:{message:f?.message,code:4001},paymentIntent:l}),f}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:h}),this.logger.debug("Emitted payment_broadcasted event",{transactionId:u.id}),this.awaitPaymentConfirmed({transaction:u,result:h}),await new Promise(f=>setTimeout(f,1e3))}catch(h){this.logger.error("error",h)}}}),de(this,"awaitPaymentConfirmed",async r=>{try{const{transaction:i,result:s}=r;this.logger.debug("Awaiting payment confirmed",{transactionId:i.id,result:s});const o={id:ot(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let a=0,c;for(;!c;){if(a>=Au)throw new Error(`Transaction status not found for id: ${i.id}`);a++;const u=await this.fetchRpcRequest(JSON.stringify(o));if(this.logger.debug("Received wc_pos_checkTransaction",{transactionId:i.id,response:u}),u.result.status==="CONFIRMED"){this.logger.debug("Transaction status confirmed",{response:u}),this.emit("payment_successful",{transaction:i,result:s}),c=u.result;break}else if(u.result.status==="FAILED"){this.logger.debug("Transaction failed",{response:u}),this.emit("payment_failed",{error:{message:u.result.error,code:4001},transaction:s}),c=u.result;break}else u.result.status==="PENDING"&&(this.logger.debug("Transaction pending",{response:u}),await new Promise(l=>setTimeout(l,u.result.checkIn||1e3)))}}catch(i){this.logger.error("Error while awaiting payment confirmations",i)}}),de(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,intentId:i})=>{try{this.logger.debug("On await_approval",{intentId:i});const s=await r();this.onSessionConnected({intentId:i,session:s})}catch(s){this.logger.error("Error while awaiting approval",s),this.emit("connection_rejected",{error:{message:s?.message,code:4001}})}})}),de(this,"fetchRpcRequest",async r=>{var i,s,o,a,c;this.logger.debug("Fetching RPC request",{url:this.getRpcUrl(),payload:r});const u=await fetch(this.getRpcUrl(),{method:"POST",body:r});let l;try{l=await u.json()}catch(h){this.logger.error("Error while getting json data from RPC response",h)}if(this.logger.debug("Received RPC request response",{data:l}),!u.ok||l.error){const h=((i=l.error)==null?void 0:i.code)||-18900,f=(s=wo)!=null&&s[h]?`${(o=wo)==null?void 0:o[h]}: ${(a=l.error)==null?void 0:a.message}`:(c=l.error)==null?void 0:c.message;throw this.emit("payment_failed",{error:{message:f,code:h},transaction:""}),new Error(f)}return l}),de(this,"getRpcUrl",()=>Ou({projectId:this.client.opts.projectId})),this.signClient={},this.logger=kt({name:this.client.name,level:(n=this.client.opts.loggerOptions)==null?void 0:n.posLevel}),this.setupEventHandlers()}composeNamespaces(e){this.logger.debug("Composing namespaces",{paymentIntents:e});const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=tr(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug("Composed namespaces",{namespaces:n}),n}}var I5=Object.defineProperty,S5=(t,e,n)=>e in t?I5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ut=(t,e,n)=>S5(t,typeof e!="symbol"?e+"":e,n);class po extends Xg{constructor(e){super(e),Ut(this,"name"),Ut(this,"events",new Ve.exports),Ut(this,"engine"),Ut(this,"metadata"),Ut(this,"on",(n,r)=>this.engine.on(n,r)),Ut(this,"once",(n,r)=>this.engine.once(n,r)),Ut(this,"off",(n,r)=>this.engine.off(n,r)),Ut(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),Ut(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ut(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ut(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=yo,this.engine=new _5(this)}static async init(e){const n=new po(e);return await n.initialize(),n}async initialize(){try{await this.engine.init(),this.engine.signClient.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.signClient.logger.info("POSClient Initialization Failure"),this.engine.signClient.logger.error(e.message),e}}}const A5=po;be.CLIENT_CONTEXT=yo,be.CLIENT_STORAGE_OPTIONS=Iu,be.CLIENT_STORAGE_PREFIX=g0,be.DEFAULT_NAMESPACES=Du,be.IPOSClient=Xg,be.IPOSClientEngine=Qg,be.MAX_TRANSACTION_STATUS_CHECKS=Au,be.POSClient=A5,be.POS_CLIENT_VERSION=Su,be.PROTOCOL=_u,be.PROTOCOL_VERSION=p0,be.RPC_ERROR_CODES=wo,be.RPC_URL=Ou,be.default=po,Object.defineProperty(be,"__esModule",{value:!0})});
42
42
  //# sourceMappingURL=index.umd.js.map