@walletconnect/pos-client 2.25.1-canary-0 → 2.25.1-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(ie,lt){typeof exports=="object"&&typeof module<"u"?lt(exports):typeof define=="function"&&define.amd?define(["exports"],lt):(ie=typeof globalThis<"u"?globalThis:ie||self,lt(ie["@walletconnect/pos-client"]={}))})(this,function(ie){"use strict";var lt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ma(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){var s=!1;try{s=this instanceof r}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var qr={exports:{}},ba;function Qf(){if(ba)return qr.exports;ba=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(x,_,T){return Function.prototype.apply.call(x,_,T)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:n=function(x){return Object.getOwnPropertyNames(x)};function r(m){console&&console.warn&&console.warn(m)}var s=Number.isNaN||function(x){return x!==x};function i(){i.init.call(this)}qr.exports=i,qr.exports.once=v,i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(m){if(typeof m!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof m)}Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(m){if(typeof m!="number"||m<0||s(m))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+m+".");o=m}}),i.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},i.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||s(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function c(m){return m._maxListeners===void 0?i.defaultMaxListeners:m._maxListeners}i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(x){for(var _=[],T=1;T<arguments.length;T++)_.push(arguments[T]);var $=x==="error",P=this._events;if(P!==void 0)$=$&&P.error===void 0;else if(!$)return!1;if($){var k;if(_.length>0&&(k=_[0]),k instanceof Error)throw k;var U=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw U.context=k,U}var N=P[x];if(N===void 0)return!1;if(typeof N=="function")e(N,this,_);else for(var S=N.length,R=d(N,S),T=0;T<S;++T)e(R[T],this,_);return!0};function l(m,x,_,T){var $,P,k;if(a(_),P=m._events,P===void 0?(P=m._events=Object.create(null),m._eventsCount=0):(P.newListener!==void 0&&(m.emit("newListener",x,_.listener?_.listener:_),P=m._events),k=P[x]),k===void 0)k=P[x]=_,++m._eventsCount;else if(typeof k=="function"?k=P[x]=T?[_,k]:[k,_]:T?k.unshift(_):k.push(_),$=c(m),$>0&&k.length>$&&!k.warned){k.warned=!0;var U=new Error("Possible EventEmitter memory leak detected. "+k.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");U.name="MaxListenersExceededWarning",U.emitter=m,U.type=x,U.count=k.length,r(U)}return m}i.prototype.addListener=function(x,_){return l(this,x,_,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(x,_){return l(this,x,_,!0)};function u(){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 h(m,x,_){var T={fired:!1,wrapFn:void 0,target:m,type:x,listener:_},$=u.bind(T);return $.listener=_,T.wrapFn=$,$}i.prototype.once=function(x,_){return a(_),this.on(x,h(this,x,_)),this},i.prototype.prependOnceListener=function(x,_){return a(_),this.prependListener(x,h(this,x,_)),this},i.prototype.removeListener=function(x,_){var T,$,P,k,U;if(a(_),$=this._events,$===void 0)return this;if(T=$[x],T===void 0)return this;if(T===_||T.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete $[x],$.removeListener&&this.emit("removeListener",x,T.listener||_));else if(typeof T!="function"){for(P=-1,k=T.length-1;k>=0;k--)if(T[k]===_||T[k].listener===_){U=T[k].listener,P=k;break}if(P<0)return this;P===0?T.shift():g(T,P),T.length===1&&($[x]=T[0]),$.removeListener!==void 0&&this.emit("removeListener",x,U||_)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(x){var _,T,$;if(T=this._events,T===void 0)return this;if(T.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):T[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete T[x]),this;if(arguments.length===0){var P=Object.keys(T),k;for($=0;$<P.length;++$)k=P[$],k!=="removeListener"&&this.removeAllListeners(k);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=T[x],typeof _=="function")this.removeListener(x,_);else if(_!==void 0)for($=_.length-1;$>=0;$--)this.removeListener(x,_[$]);return this};function f(m,x,_){var T=m._events;if(T===void 0)return[];var $=T[x];return $===void 0?[]:typeof $=="function"?_?[$.listener||$]:[$]:_?y($):d($,$.length)}i.prototype.listeners=function(x){return f(this,x,!0)},i.prototype.rawListeners=function(x){return f(this,x,!1)},i.listenerCount=function(m,x){return typeof m.listenerCount=="function"?m.listenerCount(x):p.call(m,x)},i.prototype.listenerCount=p;function p(m){var x=this._events;if(x!==void 0){var _=x[m];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}i.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function d(m,x){for(var _=new Array(x),T=0;T<x;++T)_[T]=m[T];return _}function g(m,x){for(;x+1<m.length;x++)m[x]=m[x+1];m.pop()}function y(m){for(var x=new Array(m.length),_=0;_<x.length;++_)x[_]=m[_].listener||m[_];return x}function v(m,x){return new Promise(function(_,T){function $(k){m.removeListener(x,P),T(k)}function P(){typeof m.removeListener=="function"&&m.removeListener("error",$),_([].slice.call(arguments))}w(m,x,P,{once:!0}),x!=="error"&&A(m,$,{once:!0})})}function A(m,x,_){typeof m.on=="function"&&w(m,"error",x,_)}function w(m,x,_,T){if(typeof m.on=="function")T.once?m.once(x,_):m.on(x,_);else if(typeof m.addEventListener=="function")m.addEventListener(x,function $(P){T.once&&m.removeEventListener(x,$),_(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof m)}return qr.exports}var Je=Qf(),Ys=Jf(Je);const va="wc",ed=2,Zs="POSClient",td=`${va}@2:${Zs}:`,Xs={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},Ea="1.0.0",xa=50,Js="error",_a=[{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"}],Ia=({projectId:t,deviceId:e})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${t}&st=node&sv=js-pos-${Ea}&deviceId=${e}`,Qs={"-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 ei={};/*! *****************************************************************************
1
+ (function(ie,lt){typeof exports=="object"&&typeof module<"u"?lt(exports):typeof define=="function"&&define.amd?define(["exports"],lt):(ie=typeof globalThis<"u"?globalThis:ie||self,lt(ie["@walletconnect/pos-client"]={}))})(this,function(ie){"use strict";var lt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jf(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function ba(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if(typeof e=="function"){var n=function r(){var s=!1;try{s=this instanceof r}catch{}return s?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var s=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:function(){return t[r]}})}),n}var qr={exports:{}},va;function Qf(){if(va)return qr.exports;va=1;var t=typeof Reflect=="object"?Reflect:null,e=t&&typeof t.apply=="function"?t.apply:function(x,_,T){return Function.prototype.apply.call(x,_,T)},n;t&&typeof t.ownKeys=="function"?n=t.ownKeys:Object.getOwnPropertySymbols?n=function(x){return Object.getOwnPropertyNames(x).concat(Object.getOwnPropertySymbols(x))}:n=function(x){return Object.getOwnPropertyNames(x)};function r(m){console&&console.warn&&console.warn(m)}var s=Number.isNaN||function(x){return x!==x};function i(){i.init.call(this)}qr.exports=i,qr.exports.once=b,i.EventEmitter=i,i.prototype._events=void 0,i.prototype._eventsCount=0,i.prototype._maxListeners=void 0;var o=10;function a(m){if(typeof m!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof m)}Object.defineProperty(i,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(m){if(typeof m!="number"||m<0||s(m))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+m+".");o=m}}),i.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},i.prototype.setMaxListeners=function(x){if(typeof x!="number"||x<0||s(x))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+x+".");return this._maxListeners=x,this};function c(m){return m._maxListeners===void 0?i.defaultMaxListeners:m._maxListeners}i.prototype.getMaxListeners=function(){return c(this)},i.prototype.emit=function(x){for(var _=[],T=1;T<arguments.length;T++)_.push(arguments[T]);var $=x==="error",P=this._events;if(P!==void 0)$=$&&P.error===void 0;else if(!$)return!1;if($){var k;if(_.length>0&&(k=_[0]),k instanceof Error)throw k;var U=new Error("Unhandled error."+(k?" ("+k.message+")":""));throw U.context=k,U}var N=P[x];if(N===void 0)return!1;if(typeof N=="function")e(N,this,_);else for(var S=N.length,R=d(N,S),T=0;T<S;++T)e(R[T],this,_);return!0};function l(m,x,_,T){var $,P,k;if(a(_),P=m._events,P===void 0?(P=m._events=Object.create(null),m._eventsCount=0):(P.newListener!==void 0&&(m.emit("newListener",x,_.listener?_.listener:_),P=m._events),k=P[x]),k===void 0)k=P[x]=_,++m._eventsCount;else if(typeof k=="function"?k=P[x]=T?[_,k]:[k,_]:T?k.unshift(_):k.push(_),$=c(m),$>0&&k.length>$&&!k.warned){k.warned=!0;var U=new Error("Possible EventEmitter memory leak detected. "+k.length+" "+String(x)+" listeners added. Use emitter.setMaxListeners() to increase limit");U.name="MaxListenersExceededWarning",U.emitter=m,U.type=x,U.count=k.length,r(U)}return m}i.prototype.addListener=function(x,_){return l(this,x,_,!1)},i.prototype.on=i.prototype.addListener,i.prototype.prependListener=function(x,_){return l(this,x,_,!0)};function u(){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 h(m,x,_){var T={fired:!1,wrapFn:void 0,target:m,type:x,listener:_},$=u.bind(T);return $.listener=_,T.wrapFn=$,$}i.prototype.once=function(x,_){return a(_),this.on(x,h(this,x,_)),this},i.prototype.prependOnceListener=function(x,_){return a(_),this.prependListener(x,h(this,x,_)),this},i.prototype.removeListener=function(x,_){var T,$,P,k,U;if(a(_),$=this._events,$===void 0)return this;if(T=$[x],T===void 0)return this;if(T===_||T.listener===_)--this._eventsCount===0?this._events=Object.create(null):(delete $[x],$.removeListener&&this.emit("removeListener",x,T.listener||_));else if(typeof T!="function"){for(P=-1,k=T.length-1;k>=0;k--)if(T[k]===_||T[k].listener===_){U=T[k].listener,P=k;break}if(P<0)return this;P===0?T.shift():g(T,P),T.length===1&&($[x]=T[0]),$.removeListener!==void 0&&this.emit("removeListener",x,U||_)}return this},i.prototype.off=i.prototype.removeListener,i.prototype.removeAllListeners=function(x){var _,T,$;if(T=this._events,T===void 0)return this;if(T.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):T[x]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete T[x]),this;if(arguments.length===0){var P=Object.keys(T),k;for($=0;$<P.length;++$)k=P[$],k!=="removeListener"&&this.removeAllListeners(k);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(_=T[x],typeof _=="function")this.removeListener(x,_);else if(_!==void 0)for($=_.length-1;$>=0;$--)this.removeListener(x,_[$]);return this};function f(m,x,_){var T=m._events;if(T===void 0)return[];var $=T[x];return $===void 0?[]:typeof $=="function"?_?[$.listener||$]:[$]:_?y($):d($,$.length)}i.prototype.listeners=function(x){return f(this,x,!0)},i.prototype.rawListeners=function(x){return f(this,x,!1)},i.listenerCount=function(m,x){return typeof m.listenerCount=="function"?m.listenerCount(x):p.call(m,x)},i.prototype.listenerCount=p;function p(m){var x=this._events;if(x!==void 0){var _=x[m];if(typeof _=="function")return 1;if(_!==void 0)return _.length}return 0}i.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function d(m,x){for(var _=new Array(x),T=0;T<x;++T)_[T]=m[T];return _}function g(m,x){for(;x+1<m.length;x++)m[x]=m[x+1];m.pop()}function y(m){for(var x=new Array(m.length),_=0;_<x.length;++_)x[_]=m[_].listener||m[_];return x}function b(m,x){return new Promise(function(_,T){function $(k){m.removeListener(x,P),T(k)}function P(){typeof m.removeListener=="function"&&m.removeListener("error",$),_([].slice.call(arguments))}w(m,x,P,{once:!0}),x!=="error"&&A(m,$,{once:!0})})}function A(m,x,_){typeof m.on=="function"&&w(m,"error",x,_)}function w(m,x,_,T){if(typeof m.on=="function")T.once?m.once(x,_):m.on(x,_);else if(typeof m.addEventListener=="function")m.addEventListener(x,function $(P){T.once&&m.removeEventListener(x,$),_(P)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof m)}return qr.exports}var Je=Qf(),Zs=Jf(Je);const Ea="wc",ed=2,Xs="POSClient",td=`${Ea}@2:${Xs}:`,Js={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},xa="1.0.0",_a=50,Qs="error",Ia=[{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"}],Sa=({projectId:t,deviceId:e})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${t}&st=node&sv=js-pos-${xa}&deviceId=${e}`,ei={"-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 ti={};/*! *****************************************************************************
2
2
  Copyright (c) Microsoft Corporation.
3
3
 
4
4
  Permission to use, copy, modify, and/or distribute this software for any
@@ -11,19 +11,19 @@
11
11
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
12
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
13
  PERFORMANCE OF THIS SOFTWARE.
14
- ***************************************************************************** */var ti=function(t,e){return ti=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},ti(t,e)};function nd(t,e){ti(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ni=function(){return ni=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ni.apply(this,arguments)};function rd(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 s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]]);return n}function sd(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function id(t,e){return function(n,r){e(n,r,t)}}function od(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ad(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function cd(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ld(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function ud(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function ri(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 Sa(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function hd(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Sa(arguments[e]));return t}function fd(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<n;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Qn(t){return this instanceof Qn?(this.v=t,this):new Qn(t)}function dd(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(d,g){i.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(i[0][3],d)}}function c(f){f.value instanceof Qn?Promise.resolve(f.value.v).then(l,u):h(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function pd(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:Qn(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function gd(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 ri=="function"?ri(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function yd(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function wd(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 md(t){return t&&t.__esModule?t:{default:t}}function bd(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function vd(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 Ed=Object.freeze({__proto__:null,get __assign(){return ni},__asyncDelegator:pd,__asyncGenerator:dd,__asyncValues:gd,__await:Qn,__awaiter:ad,__classPrivateFieldGet:bd,__classPrivateFieldSet:vd,__createBinding:ld,__decorate:sd,__exportStar:ud,__extends:nd,__generator:cd,__importDefault:md,__importStar:wd,__makeTemplateObject:yd,__metadata:od,__param:id,__read:Sa,__rest:rd,__spread:hd,__spreadArrays:fd,__values:ri}),zr=ma(Ed),si={},er={},Da;function xd(){if(Da)return er;Da=1,Object.defineProperty(er,"__esModule",{value:!0}),er.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return er.delay=t,er}var hn={},ii={},fn={},Aa;function _d(){return Aa||(Aa=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.ONE_THOUSAND=fn.ONE_HUNDRED=void 0,fn.ONE_HUNDRED=100,fn.ONE_THOUSAND=1e3),fn}var oi={},Ta;function Id(){return Ta||(Ta=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}(oi)),oi}var Oa;function $a(){return Oa||(Oa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zr;e.__exportStar(_d(),t),e.__exportStar(Id(),t)}(ii)),ii}var Ra;function Sd(){if(Ra)return hn;Ra=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.fromMiliseconds=hn.toMiliseconds=void 0;const t=$a();function e(r){return r*t.ONE_THOUSAND}hn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return hn.fromMiliseconds=n,hn}var Ba;function Dd(){return Ba||(Ba=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zr;e.__exportStar(xd(),t),e.__exportStar(Sd(),t)}(si)),si}var Nn={},Pa;function Ad(){if(Pa)return Nn;Pa=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.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 s=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:s})}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 Nn.Watch=t,Nn.default=t,Nn}var ai={},tr={},Ca;function Td(){if(Ca)return tr;Ca=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.IWatch=void 0;class t{}return tr.IWatch=t,tr}var Na;function Od(){return Na||(Na=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),zr.__exportStar(Td(),t)}(ai)),ai}var Ua;function $d(){return Ua||(Ua=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zr;e.__exportStar(Dd(),t),e.__exportStar(Ad(),t),e.__exportStar(Od(),t),e.__exportStar($a(),t)}(ei)),ei}var F=$d();class dn{}let Rd=class extends dn{constructor(e){super()}};const ka=F.FIVE_SECONDS,pn={pulse:"heartbeat_pulse"};class ci extends Rd{constructor(e){super(e),this.events=new Je.EventEmitter,this.interval=ka,this.interval=e?.interval||ka}static async init(e){const n=new ci(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(),F.toMiliseconds(this.interval))}pulse(){this.events.emit(pn.pulse)}}const Bd=/"(?:_|\\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*:/,Pd=/"(?: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*:/,Cd=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Nd(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Ud(t);return}return e}function Ud(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function jr(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(!Cd.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Bd.test(t)||Pd.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Nd)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function kd(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function pe(t,...e){try{return kd(t(...e))}catch(n){return Promise.reject(n)}}function Ld(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Fd(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Vr(t){if(Ld(t))return String(t);if(Fd(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Vr(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const li="base64:";function Md(t){return typeof t=="string"?t:li+jd(t)}function qd(t){return typeof t!="string"||!t.startsWith(li)?t:zd(t.slice(li.length))}function zd(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function jd(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Re(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Vd(...t){return Re(t.join(":"))}function Kr(t){return t=Re(t),t?t+":":""}function Kd(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 Hd(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function ES(t){return t}const Wd="memory",Gd=()=>{const t=new Map;return{name:Wd,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 Yd(t={}){const e={mounts:{"":t.driver||Gd()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(l,u)=>{if(e.watching){u=Re(u);for(const h of e.watchListeners)h(l,u)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await La(e.mounts[l],s,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,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 l){const g=typeof d=="string",y=Re(g?d:d.key),v=g?void 0:d.value,A=g||!d.options?u:{...u,...d.options},w=n(y);p(w).items.push({key:y,value:v,relativeKey:w.relativeKey,options:A})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return pe(f.hasItem,h,u)},getItem(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return pe(f.getItem,h,u).then(p=>jr(p))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?pe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(p=>({key:Vd(h.base,p.key),value:jr(p.value)}))):Promise.all(h.items.map(f=>pe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:jr(p)})))))},getItemRaw(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return f.getItemRaw?pe(f.getItemRaw,h,u):pe(f.getItem,h,u).then(p=>qd(p))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Re(l);const{relativeKey:f,driver:p}=n(l);p.setItem&&(await pe(p.setItem,f,Vr(u),h),p.watch||s("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return pe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Vr(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>pe(h.driver.setItem,f.relativeKey,Vr(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Re(l);const{relativeKey:f,driver:p}=n(l);if(p.setItemRaw)await pe(p.setItemRaw,f,u,h);else if(p.setItem)await pe(p.setItem,f,Md(u),h);else return;p.watch||s("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Re(l);const{relativeKey:h,driver:f}=n(l);f.removeItem&&(await pe(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await pe(f.removeItem,h+"$",u),f.watch||s("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Re(l);const{relativeKey:h,driver:f}=n(l),p=Object.create(null);if(f.getMeta&&Object.assign(p,await pe(f.getMeta,h,u)),!u.nativeOnly){const d=await pe(f.getItem,h+"$",u).then(g=>jr(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(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=Kr(l);const h=r(l,!0);let f=[];const p=[];let d=!0;for(const y of h){y.driver.flags?.maxDepth||(d=!1);const v=await pe(y.driver.getKeys,y.relativeBase,u);for(const A of v){const w=y.mountpoint+Re(A);f.some(m=>w.startsWith(m))||p.push(w)}f=[y.mountpoint,...f.filter(A=>!A.startsWith(y.mountpoint))]}const g=u.maxDepth!==void 0&&!d;return p.filter(y=>(!g||Kd(y,u.maxDepth))&&Hd(y,l))},async clear(l,u={}){l=Kr(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return pe(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(p=>h.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>Fa(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=Kr(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(La(u,s,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){l=Kr(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await Fa(e.mounts[l]),e.mountpoints=e.mountpoints.filter(h=>h!==l),delete e.mounts[l])},getMount(l=""){l=Re(l)+":";const u=n(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Re(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function La(t,e,n){return t.watch?t.watch((r,s)=>e(r,n+s)):()=>{}}async function Fa(t){typeof t.dispose=="function"&&await pe(t.dispose)}function gn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function Ma(t,e){let n;const r=()=>{if(n)return n;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),n=gn(s),n.then(i=>{i.onclose=()=>n=void 0},()=>{}),n};return(s,i)=>r().then(o=>i(o.transaction(e,s).objectStore(e)))}let ui;function nr(){return ui||(ui=Ma("keyval-store","keyval")),ui}function qa(t,e=nr()){return e("readonly",n=>gn(n.get(t)))}function Zd(t,e,n=nr()){return n("readwrite",r=>(r.put(e,t),gn(r.transaction)))}function Xd(t,e=nr()){return e("readwrite",n=>(n.delete(t),gn(n.transaction)))}function Jd(t=nr()){return t("readwrite",e=>(e.clear(),gn(e.transaction)))}function Qd(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},gn(t.transaction)}function ep(t=nr()){return t("readonly",e=>{if(e.getAllKeys)return gn(e.getAllKeys());const n=[];return Qd(e,r=>n.push(r.key)).then(()=>n)})}const tp=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),np=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,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Un(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return np(t)}catch{return t}}function rr(t){return typeof t=="string"?t:tp(t)||""}const rp="idb-keyval";var sp=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=s=>e+s;let r;return t.dbName&&t.storeName&&(r=Ma(t.dbName,t.storeName)),{name:rp,options:t,async hasItem(s){return!(typeof await qa(n(s),r)>"u")},async getItem(s){return await qa(n(s),r)??null},setItem(s,i){return Zd(n(s),i,r)},removeItem(s){return Xd(n(s),r)},getKeys(){return ep(r)},clear(){return Jd(r)}}};const ip="WALLET_CONNECT_V2_INDEXED_DB",op="keyvaluestorage";let ap=class{constructor(){this.indexedDb=Yd({driver:sp({dbName:ip,storeName:op})})}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,rr(n))}async removeItem(e){await this.indexedDb.removeItem(e)}};var hi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Hr={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 hi<"u"&&hi.localStorage?Hr.exports=hi.localStorage:typeof window<"u"&&window.localStorage?Hr.exports=window.localStorage:Hr.exports=new e})();function cp(t){var e;return[t[0],Un((e=t[1])!=null?e:"")]}let lp=class{constructor(){this.localStorage=Hr.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(cp)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return Un(n)}async setItem(e,n){this.localStorage.setItem(e,rr(n))}async removeItem(e){this.localStorage.removeItem(e)}};const up="wc_storage_version",za=1,hp=async(t,e,n)=>{const r=up,s=await e.getItem(r);if(s&&s>=za){n(e);return}const i=await t.getKeys();if(!i.length){n(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,za),n(e),fp(t,o)},fp=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};let dp=class{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new lp;this.storage=e;try{const n=new ap;hp(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)})}};var ut={exports:{}};function pp(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var gp=yp;function yp(t,e,n){var r=n&&n.stringify||pp,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=r(t);for(var a=1;a<i;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 l="",u=1-s,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(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Number(e[u]),h=p+2,p++;break;case 105:if(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Math.floor(Number(e[u])),h=p+2,p++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;h<p&&(l+=t.slice(h,p));var d=typeof e[u];if(d==="string"){l+="'"+e[u]+"'",h=p+2,p++;break}if(d==="function"){l+=e[u].name||"<anonymous>",h=p+2,p++;break}l+=r(e[u]),h=p+2,p++;break;case 115:if(u>=c)break;h<p&&(l+=t.slice(h,p)),l+=String(e[u]),h=p+2,p++;break;case 37:h<p&&(l+=t.slice(h,p)),l+="%",h=p+2,p++,u--;break}++u}++p}return h===-1?t:(h<f&&(l+=t.slice(h)),l)}const ja=gp;ut.exports=bt;const sr=Rp().console||{},wp={mapHttpRequest:Wr,mapHttpResponse:Wr,wrapRequestSerializer:yi,wrapResponseSerializer:yi,wrapErrorSerializer:yi,req:Wr,res:Wr,err:Ka,errWithCause:Ka};function Mt(t,e){return t==="silent"?1/0:e.levels.values[t]}const fi=Symbol("pino.logFuncs"),di=Symbol("pino.hierarchy"),mp={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Va(t,e){const n={logger:e,parent:t[di]};e[di]=n}function bp(t,e,n){const r={};e.forEach(s=>{r[s]=n[s]?n[s]:sr[s]||sr[mp[s]||"log"]||kn}),t[fi]=r}function vp(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function bt(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||sr;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},s=vp(t.browser.serialize,r);let i=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(n);l.log||(l.log=kn),bp(l,a,n),Va({},l),Object.defineProperty(l,"levelVal",{get:h}),Object.defineProperty(l,"level",{get:f,set:p});const u={transmit:e,serialize:s,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:Tp(t),messageKey:t.messageKey||"msg",onChild:t.onChild||kn};l.levels=Ep(t),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=kn,l.serializers=r,l._serialize=s,l._stdErrSerialize=i,l.child=function(...g){return d.call(this,u,...g)},e&&(l._logEvent=gi());function h(){return Mt(this.level,this)}function f(){return this._level}function p(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,yn(this,u,l,"error"),yn(this,u,l,"fatal"),yn(this,u,l,"warn"),yn(this,u,l,"info"),yn(this,u,l,"debug"),yn(this,u,l,"trace"),o.forEach(y=>{yn(this,u,l,y)})}function d(g,y,v){if(!y)throw new Error("missing bindings for child Pino");v=v||{},s&&y.serializers&&(v.serializers=y.serializers);const A=v.serializers;if(s&&A){var w=Object.assign({},r,A),m=t.browser.serialize===!0?Object.keys(w):s;delete y.serializers,pi([y],m,w,this._stdErrSerialize)}function x(T){this._childLevel=(T._childLevel|0)+1,this.bindings=y,w&&(this.serializers=w,this._serialize=m),e&&(this._logEvent=gi([].concat(T._logEvent.bindings,y)))}x.prototype=this;const _=new x(this);return Va(this,_),_.child=function(...T){return d.call(this,g,...T)},_.level=v.level||this.level,g.onChild(_),_}return l}function Ep(t){const e=t.customLevels||{},n=Object.assign({},bt.levels.values,e),r=Object.assign({},bt.levels.labels,xp(e));return{values:n,labels:r}}function xp(t){const e={};return Object.keys(t).forEach(function(n){e[t[n]]=n}),e}bt.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"}},bt.stdSerializers=wp,bt.stdTimeFunctions=Object.assign({},{nullTime:Ha,epochTime:Wa,unixTime:Op,isoTime:$p});function _p(t){const e=[];t.bindings&&e.push(t.bindings);let n=t[di];for(;n.parent;)n=n.parent,n.logger.bindings&&e.push(n.logger.bindings);return e.reverse()}function yn(t,e,n,r){if(Object.defineProperty(t,r,{value:Mt(t.level,n)>Mt(r,n)?kn:n[fi][r],writable:!0,enumerable:!0,configurable:!0}),t[r]===kn){if(!e.transmit)return;const i=e.transmit.level||t.level,o=Mt(i,n);if(Mt(r,n)<o)return}t[r]=Sp(t,e,n,r);const s=_p(t);s.length!==0&&(t[r]=Ip(s,t[r]))}function Ip(t,e){return function(){return e.apply(this,[...t,...arguments])}}function Sp(t,e,n,r){return function(s){return function(){const i=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===sr?sr:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(e.serialize&&(pi(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?s.call(a,...Dp(this,r,o,i,e)):s.apply(a,o),e.transmit){const u=e.transmit.level||t._level,h=Mt(u,n),f=Mt(r,n);if(f<h)return;Ap(this,{ts:i,methodLevel:r,methodValue:f,transmitValue:n.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Mt(t._level,n)},o,l)}}}(t[fi][r])}function Dp(t,e,n,r,s){const{level:i,log:o=h=>h}=s.formatters||{},a=n.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),i){const h=i(e,t.levels.values[e]);Object.assign(l,h)}else l.level=t.levels.values[e];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?ja(a.shift(),a):void 0}else typeof c=="string"&&(c=ja(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function pi(t,e,n,r){for(const s in t)if(r&&t[s]instanceof Error)t[s]=bt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s])&&e)for(const i in t[s])e.indexOf(i)>-1&&i in n&&(t[s][i]=n[i](t[s][i]))}function Ap(t,e,n,r=!1){const s=e.send,i=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;r||pi(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 l.indexOf(u)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,s(o,t._logEvent,c),t._logEvent=gi(l)}function gi(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Ka(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 Tp(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ha:Wa}function Wr(){return{}}function yi(t){return t}function kn(){}function Ha(){return!1}function Wa(){return Date.now()}function Op(){return Math.round(Date.now()/1e3)}function $p(){return new Date(Date.now()).toISOString()}function Rp(){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)||{}}}ut.exports.default=bt;var Bp=ut.exports.pino=bt;const Pp={level:"info"},Gr="custom_context",wi=1e3*1024;var Cp=Object.defineProperty,Np=(t,e,n)=>e in t?Cp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qt=(t,e,n)=>Np(t,typeof e!="symbol"?e+"":e,n);let Up=class{constructor(e){qt(this,"nodeValue"),qt(this,"sizeInBytes"),qt(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ga=class{constructor(e){qt(this,"lengthInNodes"),qt(this,"sizeInBytes"),qt(this,"head"),qt(this,"tail"),qt(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new Up(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}}}}};const kp=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n);function Ya(t){return typeof t=="string"?t:kp(t)||""}var Lp=Object.defineProperty,Fp=(t,e,n)=>e in t?Lp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yr=(t,e,n)=>Fp(t,typeof e!="symbol"?e+"":e,n);let Za=class{constructor(e,n=wi){Yr(this,"logs"),Yr(this,"level"),Yr(this,"levelValue"),Yr(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=ut.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Ga(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===ut.exports.levels.values.error?console.error(e):n===ut.exports.levels.values.warn?console.warn(e):n===ut.exports.levels.values.debug?console.debug(e):n===ut.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ya({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 Ga(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Ya({extraMetadata:e})),new Blob(n,{type:"application/json"})}};var Mp=Object.defineProperty,qp=(t,e,n)=>e in t?Mp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zp=(t,e,n)=>qp(t,e+"",n);let jp=class{constructor(e,n=wi){zp(this,"baseChunkLogger"),this.baseChunkLogger=new Za(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)}};var Vp=Object.defineProperty,Kp=(t,e,n)=>e in t?Vp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hp=(t,e,n)=>Kp(t,e+"",n);let Wp=class{constructor(e,n=wi){Hp(this,"baseChunkLogger"),this.baseChunkLogger=new Za(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 Gp=Object.defineProperty,Yp=Object.defineProperties,Zp=Object.getOwnPropertyDescriptors,Xa=Object.getOwnPropertySymbols,Xp=Object.prototype.hasOwnProperty,Jp=Object.prototype.propertyIsEnumerable,Ja=(t,e,n)=>e in t?Gp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zt=(t,e)=>{for(var n in e||(e={}))Xp.call(e,n)&&Ja(t,n,e[n]);if(Xa)for(var n of Xa(e))Jp.call(e,n)&&Ja(t,n,e[n]);return t},jt=(t,e)=>Yp(t,Zp(e));function Qp(t){return jt(zt({},t),{level:t?.level||Pp.level})}function eg(t,e,n=Gr){return t[n]=e,t}function Be(t,e=Gr){return t[e]||""}function tg(t,e,n=Gr){const r=Be(t,n);return r.trim()?`${r}/${e}`:e}function Fe(t,e,n=Gr){const r=tg(t,e,n),s=t.child({context:r});return eg(s,r,n)}function ng(t){var e,n;const r=new jp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ut.exports(jt(zt({},t.opts),{level:"trace",browser:jt(zt({},(n=t.opts)==null?void 0:n.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function rg(t){var e,n;const r=new Wp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ut.exports(jt(zt({},t.opts),{level:"trace",browser:jt(zt({},(n=t.opts)==null?void 0:n.browser),{write:s=>r.write(s)})}),r),chunkLoggerController:r}}function Qa(t){var e;if(typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string")return{logger:t.loggerOverride,chunkLoggerController:null};const n=jt(zt({},t.opts),{level:typeof t.loggerOverride=="string"?t.loggerOverride:(e=t.opts)==null?void 0:e.level});return typeof window<"u"?ng(jt(zt({},t),{opts:n})):rg(jt(zt({},t),{opts:n}))}class sg extends dn{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class ig extends dn{constructor(e,n){super(),this.core=e,this.logger=n,this.records=new Map}}let og=class{constructor(e,n){this.logger=e,this.core=n}},ag=class extends dn{constructor(e,n){super(),this.relayer=e,this.logger=n}};class cg extends dn{constructor(e){super()}}let lg=class{constructor(e,n,r,s){this.core=e,this.logger=n,this.name=r}},ug=class extends dn{constructor(e,n){super(),this.relayer=e,this.logger=n}},hg=class extends dn{constructor(e,n){super(),this.core=e,this.logger=n}},fg=class{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}},dg=class{constructor(e,n){this.projectId=e,this.logger=n}},pg=class{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}},gg=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},yg=class{constructor(e){this.client=e}};function wg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ec(t,...e){if(!wg(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 tc(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 mg(t,e){ec(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const Ln=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const mi=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function bg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function nc(t){return typeof t=="string"&&(t=bg(t)),ec(t),t}let vg=class{clone(){return this._cloneInto()}};function Eg(t){const e=r=>t().update(nc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function rc(t=32){if(Ln&&typeof Ln.getRandomValues=="function")return Ln.getRandomValues(new Uint8Array(t));if(Ln&&typeof Ln.randomBytes=="function")return Ln.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function xg(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}class _g extends vg{constructor(e,n,r,s){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=mi(this.buffer)}update(e){tc(this);const{view:n,buffer:r,blockLen:s}=this;e=nc(e);const i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=mi(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){tc(this),mg(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:i}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let h=o;h<s;h++)n[h]=0;xg(r,s-8,BigInt(this.length*8),i),this.process(r,0);const a=mi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}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:s,finished:i,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=i,e.destroyed=o,s%n&&e.buffer.set(r),e}}const Zr=BigInt(2**32-1),bi=BigInt(32);function sc(t,e=!1){return e?{h:Number(t&Zr),l:Number(t>>bi&Zr)}:{h:Number(t>>bi&Zr)|0,l:Number(t&Zr)|0}}function Ig(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:i,l:o}=sc(t[s],e);[n[s],r[s]]=[i,o]}return[n,r]}const Sg=(t,e)=>BigInt(t>>>0)<<bi|BigInt(e>>>0),Dg=(t,e,n)=>t>>>n,Ag=(t,e,n)=>t<<32-n|e>>>n,Tg=(t,e,n)=>t>>>n|e<<32-n,Og=(t,e,n)=>t<<32-n|e>>>n,$g=(t,e,n)=>t<<64-n|e>>>n-32,Rg=(t,e,n)=>t>>>n-32|e<<64-n,Bg=(t,e)=>e,Pg=(t,e)=>t,Cg=(t,e,n)=>t<<n|e>>>32-n,Ng=(t,e,n)=>e<<n|t>>>32-n,Ug=(t,e,n)=>e<<n-32|t>>>64-n,kg=(t,e,n)=>t<<n-32|e>>>64-n;function Lg(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const Fg=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Mg=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,qg=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),zg=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,jg=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Vg=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Y={fromBig:sc,split:Ig,toBig:Sg,shrSH:Dg,shrSL:Ag,rotrSH:Tg,rotrSL:Og,rotrBH:$g,rotrBL:Rg,rotr32H:Bg,rotr32L:Pg,rotlSH:Cg,rotlSL:Ng,rotlBH:Ug,rotlBL:kg,add:Lg,add3L:Fg,add3H:Mg,add4L:qg,add4H:zg,add5H:Vg,add5L:jg},[Kg,Hg]=Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Vt=new Uint32Array(80),Kt=new Uint32Array(80);let Wg=class extends _g{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:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|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 w=0;w<16;w++,n+=4)Vt[w]=e.getUint32(n),Kt[w]=e.getUint32(n+=4);for(let w=16;w<80;w++){const m=Vt[w-15]|0,x=Kt[w-15]|0,_=Y.rotrSH(m,x,1)^Y.rotrSH(m,x,8)^Y.shrSH(m,x,7),T=Y.rotrSL(m,x,1)^Y.rotrSL(m,x,8)^Y.shrSL(m,x,7),$=Vt[w-2]|0,P=Kt[w-2]|0,k=Y.rotrSH($,P,19)^Y.rotrBH($,P,61)^Y.shrSH($,P,6),U=Y.rotrSL($,P,19)^Y.rotrBL($,P,61)^Y.shrSL($,P,6),N=Y.add4L(T,U,Kt[w-7],Kt[w-16]),S=Y.add4H(N,_,k,Vt[w-7],Vt[w-16]);Vt[w]=S|0,Kt[w]=N|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:v,Hl:A}=this;for(let w=0;w<80;w++){const m=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),_=h&p^~h&g,T=f&d^~f&y,$=Y.add5L(A,x,T,Hg[w],Kt[w]),P=Y.add5H($,v,m,_,Kg[w],Vt[w]),k=$|0,U=Y.rotrSH(r,s,28)^Y.rotrBH(r,s,34)^Y.rotrBH(r,s,39),N=Y.rotrSL(r,s,28)^Y.rotrBL(r,s,34)^Y.rotrBL(r,s,39),S=r&i^r&a^i&a,R=s&o^s&c^o&c;v=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(l|0,u|0,P|0,k|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const b=Y.add3L(k,N,R);r=Y.add3H(b,P,U,S),s=b|0}({h:r,l:s}=Y.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=Y.add(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Y.add(this.Dh|0,this.Dl|0,l|0,u|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:v,l:A}=Y.add(this.Hh|0,this.Hl|0,v|0,A|0),this.set(r,s,i,o,a,c,l,u,h,f,p,d,g,y,v,A)}roundClean(){Vt.fill(0),Kt.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 Gg=Eg(()=>new Wg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const vi=BigInt(0),ic=BigInt(1),Yg=BigInt(2);function Ei(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xi(t){if(!Ei(t))throw new Error("Uint8Array expected")}function _i(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Zg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ii(t){xi(t);let e="";for(let n=0;n<t.length;n++)e+=Zg[t[n]];return e}function oc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?vi:BigInt("0x"+t)}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function ac(t){if(t>=vt._0&&t<=vt._9)return t-vt._0;if(t>=vt.A&&t<=vt.F)return t-(vt.A-10);if(t>=vt.a&&t<=vt.f)return t-(vt.a-10)}function cc(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 s=0,i=0;s<n;s++,i+=2){const o=ac(t.charCodeAt(i)),a=ac(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function Xg(t){return oc(Ii(t))}function Xr(t){return xi(t),oc(Ii(Uint8Array.from(t).reverse()))}function lc(t,e){return cc(t.toString(16).padStart(e*2,"0"))}function Si(t,e){return lc(t,e).reverse()}function Et(t,e,n){let r;if(typeof e=="string")try{r=cc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(Ei(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function uc(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];xi(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}const Di=t=>typeof t=="bigint"&&vi<=t;function Jg(t,e,n){return Di(t)&&Di(e)&&Di(n)&&e<=t&&t<n}function ir(t,e,n,r){if(!Jg(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Qg(t){let e;for(e=0;t>vi;t>>=ic,e+=1);return e}const ey=t=>(Yg<<BigInt(t-1))-ic,ty={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"||Ei(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 Ai(t,e,n={}){const r=(s,i,o)=>{const a=ty[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function hc(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}const ge=BigInt(0),re=BigInt(1),wn=BigInt(2),ny=BigInt(3),Ti=BigInt(4),fc=BigInt(5),dc=BigInt(8);function le(t,e){const n=t%e;return n>=ge?n:e+n}function ry(t,e,n){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(n<=ge)throw new Error("invalid modulus");if(n===re)return ge;let r=re;for(;e>ge;)e&re&&(r=r*t%n),t=t*t%n,e>>=re;return r}function ht(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function pc(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=le(t,e),r=e,s=ge,i=re;for(;n!==ge;){const o=r/n,a=r%n,c=s-i*o;r=n,n=a,s=i,i=c}if(r!==re)throw new Error("invert: does not exist");return le(s,e)}function sy(t){const e=(t-re)/wn;let n,r,s;for(n=t-re,r=0;n%wn===ge;n/=wn,r++);for(s=wn;s<t&&ry(s,e,t)!==t-re;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+re)/Ti;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const i=(n+re)/wn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,s),n),u=o.pow(a,i),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(l,re<<BigInt(c-f-1));l=o.sqr(p),u=o.mul(u,p),h=o.mul(h,l),c=f}return u}}function iy(t){if(t%Ti===ny){const e=(t+re)/Ti;return function(n,r){const s=n.pow(r,e);if(!n.eql(n.sqr(s),r))throw new Error("Cannot find square root");return s}}if(t%dc===fc){const e=(t-fc)/dc;return function(n,r){const s=n.mul(r,wn),i=n.pow(s,e),o=n.mul(r,i),a=n.mul(n.mul(o,wn),i),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 sy(t)}const oy=(t,e)=>(le(t,e)&re)===re,ay=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=ay.reduce((r,s)=>(r[s]="function",r),e);return Ai(t,n)}function ly(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===re)return e;let r=t.ONE,s=e;for(;n>ge;)n&re&&(r=t.mul(r,s)),s=t.sqr(s),n>>=re;return r}function uy(t,e){const n=new Array(e.length),r=e.reduce((i,o,a)=>t.is0(o)?i:(n[a]=i,t.mul(i,o)),t.ONE),s=t.inv(r);return e.reduceRight((i,o,a)=>t.is0(o)?i:(n[a]=t.mul(i,n[a]),t.mul(i,o)),s),n}function gc(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function yc(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=gc(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:ey(s),ZERO:ge,ONE:re,create:c=>le(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<t},is0:c=>c===ge,isOdd:c=>(c&re)===re,neg:c=>le(-c,t),eql:(c,l)=>c===l,sqr:c=>le(c*c,t),add:(c,l)=>le(c+l,t),sub:(c,l)=>le(c-l,t),mul:(c,l)=>le(c*l,t),pow:(c,l)=>ly(a,c,l),div:(c,l)=>le(c*pc(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>pc(c,t),sqrt:r.sqrt||(c=>(o||(o=iy(t)),o(a,c))),invertBatch:c=>uy(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>n?Si(c,i):lc(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?Xr(c):Xg(c)}});return Object.freeze(a)}const wc=BigInt(0),Jr=BigInt(1);function Oi(t,e){const n=e.negate();return t?n:e}function mc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $i(t,e){mc(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function hy(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 fy(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 Ri=new WeakMap,bc=new WeakMap;function Bi(t){return bc.get(t)||1}function dy(t,e){return{constTimeNegate:Oi,hasPrecomputes(n){return Bi(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>wc;)r&Jr&&(s=s.add(i)),i=i.double(),r>>=Jr;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=$i(r,e),o=[];let a=n,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<i;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,s){const{windows:i,windowSize:o}=$i(n,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<i;f++){const p=f*o;let d=Number(s&l);s>>=h,d>o&&(d-=u,s+=Jr);const g=p,y=p+Math.abs(d)-1,v=f%2!==0,A=d<0;d===0?c=c.add(Oi(v,r[g])):a=a.add(Oi(A,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,s,i=t.ZERO){const{windows:o,windowSize:a}=$i(n,e),c=BigInt(2**n-1),l=2**n,u=BigInt(n);for(let h=0;h<o;h++){const f=h*a;if(s===wc)break;let p=Number(s&c);if(s>>=u,p>a&&(p-=l,s+=Jr),p===0)continue;let d=r[f+Math.abs(p)-1];p<0&&(d=d.negate()),i=i.add(d)}return i},getPrecomputes(n,r,s){let i=Ri.get(r);return i||(i=this.precomputeWindow(r,n),n!==1&&Ri.set(r,s(i))),i},wNAFCached(n,r,s){const i=Bi(n);return this.wNAF(i,this.getPrecomputes(i,n,s),r)},wNAFCachedUnsafe(n,r,s,i){const o=Bi(n);return o===1?this.unsafeLadder(n,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,n,s),r,i)},setWindowSize(n,r){mc(r,e),bc.set(n,r),Ri.delete(n)}}}function py(t,e,n,r){if(hy(n,t),fy(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,i=Qg(BigInt(n.length)),o=i>12?i-3:i>4?i-2:i?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),l=Math.floor((e.BITS-1)/o)*o;let u=s;for(let h=l;h>=0;h-=o){c.fill(s);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=s;for(let p=c.length-1,d=s;p>0;p--)d=d.add(c[p]),f=f.add(d);if(u=u.add(f),h!==0)for(let p=0;p<o;p++)u=u.double()}return u}function gy(t){return cy(t.Fp),Ai(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...gc(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Qe=BigInt(0),Pe=BigInt(1),Qr=BigInt(2),yy=BigInt(8),wy={zip215:!0};function my(t){const e=gy(t);return Ai(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function by(t){const e=my(t),{Fp:n,n:r,prehash:s,hash:i,randomBytes:o,nByteLength:a,h:c}=e,l=Qr<<BigInt(a*8)-Pe,u=n.create,h=yc(e.n,e.nBitLength),f=e.uvRatio||((b,E)=>{try{return{isValid:!0,value:n.sqrt(b*n.inv(E))}}catch{return{isValid:!1,value:Qe}}}),p=e.adjustScalarBytes||(b=>b),d=e.domain||((b,E,D)=>{if(_i("phflag",D),E.length||D)throw new Error("Contexts/pre-hash are not supported");return b});function g(b,E){ir("coordinate "+b,E,Qe,l)}function y(b){if(!(b instanceof w))throw new Error("ExtendedPoint expected")}const v=hc((b,E)=>{const{ex:D,ey:B,ez:I}=b,O=b.is0();E==null&&(E=O?yy:n.inv(I));const C=u(D*E),L=u(B*E),V=u(I*E);if(O)return{x:Qe,y:Pe};if(V!==Pe)throw new Error("invZ was invalid");return{x:C,y:L}}),A=hc(b=>{const{a:E,d:D}=e;if(b.is0())throw new Error("bad point: ZERO");const{ex:B,ey:I,ez:O,et:C}=b,L=u(B*B),V=u(I*I),z=u(O*O),q=u(z*z),K=u(L*E),W=u(z*u(K+V)),G=u(q+u(D*u(L*V)));if(W!==G)throw new Error("bad point: equation left != right (1)");const H=u(B*I),Z=u(O*C);if(H!==Z)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,D,B,I){this.ex=E,this.ey=D,this.ez=B,this.et=I,g("x",E),g("y",D),g("z",B),g("t",I),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");const{x:D,y:B}=E||{};return g("x",D),g("y",B),new w(D,B,Pe,u(D*B))}static normalizeZ(E){const D=n.invertBatch(E.map(B=>B.ez));return E.map((B,I)=>B.toAffine(D[I])).map(w.fromAffine)}static msm(E,D){return py(w,h,E,D)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){A(this)}equals(E){y(E);const{ex:D,ey:B,ez:I}=this,{ex:O,ey:C,ez:L}=E,V=u(D*L),z=u(O*I),q=u(B*L),K=u(C*I);return V===z&&q===K}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:E}=e,{ex:D,ey:B,ez:I}=this,O=u(D*D),C=u(B*B),L=u(Qr*u(I*I)),V=u(E*O),z=D+B,q=u(u(z*z)-O-C),K=V+C,W=K-L,G=V-C,H=u(q*W),Z=u(K*G),ae=u(q*G),ce=u(W*K);return new w(H,Z,ce,ae)}add(E){y(E);const{a:D,d:B}=e,{ex:I,ey:O,ez:C,et:L}=this,{ex:V,ey:z,ez:q,et:K}=E;if(D===BigInt(-1)){const zf=u((O-I)*(z+V)),jf=u((O+I)*(z-V)),wa=u(jf-zf);if(wa===Qe)return this.double();const Vf=u(C*Qr*K),Kf=u(L*Qr*q),Hf=Kf+Vf,Wf=jf+zf,Gf=Kf-Vf,wS=u(Hf*wa),mS=u(Wf*Gf),bS=u(Hf*Gf),vS=u(wa*Wf);return new w(wS,mS,vS,bS)}const W=u(I*V),G=u(O*z),H=u(L*B*K),Z=u(C*q),ae=u((I+O)*(V+z)-W-G),ce=Z-H,we=Z+H,at=u(G-D*W),ct=u(ae*ce),Gs=u(we*at),gS=u(ae*at),yS=u(ce*we);return new w(ct,Gs,yS,gS)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){const D=E;ir("scalar",D,Pe,r);const{p:B,f:I}=this.wNAF(D);return w.normalizeZ([B,I])[0]}multiplyUnsafe(E,D=w.ZERO){const B=E;return ir("scalar",B,Qe,r),B===Qe?x:this.is0()||B===Pe?this:_.wNAFCachedUnsafe(this,B,w.normalizeZ,D)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,r).is0()}toAffine(E){return v(this,E)}clearCofactor(){const{h:E}=e;return E===Pe?this:this.multiplyUnsafe(E)}static fromHex(E,D=!1){const{d:B,a:I}=e,O=n.BYTES;E=Et("pointHex",E,O),_i("zip215",D);const C=E.slice(),L=E[O-1];C[O-1]=L&-129;const V=Xr(C),z=D?l:n.ORDER;ir("pointHex.y",V,Qe,z);const q=u(V*V),K=u(q-Pe),W=u(B*q-I);let{isValid:G,value:H}=f(K,W);if(!G)throw new Error("Point.fromHex: invalid y coordinate");const Z=(H&Pe)===Pe,ae=(L&128)!==0;if(!D&&H===Qe&&ae)throw new Error("Point.fromHex: x=0 and x_0=1");return ae!==Z&&(H=u(-H)),w.fromAffine({x:H,y:V})}static fromPrivateKey(E){return P(E).point}toRawBytes(){const{x:E,y:D}=this.toAffine(),B=Si(D,n.BYTES);return B[B.length-1]|=E&Pe?128:0,B}toHex(){return Ii(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Pe,u(e.Gx*e.Gy)),w.ZERO=new w(Qe,Pe,Pe,Qe);const{BASE:m,ZERO:x}=w,_=dy(w,a*8);function T(b){return le(b,r)}function $(b){return T(Xr(b))}function P(b){const E=n.BYTES;b=Et("private key",b,E);const D=Et("hashed private key",i(b),2*E),B=p(D.slice(0,E)),I=D.slice(E,2*E),O=$(B),C=m.multiply(O),L=C.toRawBytes();return{head:B,prefix:I,scalar:O,point:C,pointBytes:L}}function k(b){return P(b).pointBytes}function U(b=new Uint8Array,...E){const D=uc(...E);return $(i(d(D,Et("context",b),!!s)))}function N(b,E,D={}){b=Et("message",b),s&&(b=s(b));const{prefix:B,scalar:I,pointBytes:O}=P(E),C=U(D.context,B,b),L=m.multiply(C).toRawBytes(),V=U(D.context,L,O,b),z=T(C+V*I);ir("signature.s",z,Qe,r);const q=uc(L,Si(z,n.BYTES));return Et("result",q,n.BYTES*2)}const S=wy;function R(b,E,D,B=S){const{context:I,zip215:O}=B,C=n.BYTES;b=Et("signature",b,2*C),E=Et("message",E),D=Et("publicKey",D,C),O!==void 0&&_i("zip215",O),s&&(E=s(E));const L=Xr(b.slice(C,2*C));let V,z,q;try{V=w.fromHex(D,O),z=w.fromHex(b.slice(0,C),O),q=m.multiplyUnsafe(L)}catch{return!1}if(!O&&V.isSmallOrder())return!1;const K=U(I,z.toRawBytes(),V.toRawBytes(),E);return z.add(V.multiplyUnsafe(K)).subtract(q).clearCofactor().equals(w.ZERO)}return m._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:N,verify:R,ExtendedPoint:w,utils:{getExtendedPublicKey:P,randomPrivateKey:()=>o(n.BYTES),precompute(b=8,E=w.BASE){return E._setWindowSize(b),E.multiply(BigInt(3)),E}}}}BigInt(0),BigInt(1);const Pi=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),vc=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const vy=BigInt(1),Ec=BigInt(2);BigInt(3);const Ey=BigInt(5),xy=BigInt(8);function _y(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Pi,o=t*t%i*t%i,a=ht(o,Ec,i)*o%i,c=ht(a,vy,i)*t%i,l=ht(c,Ey,i)*c%i,u=ht(l,e,i)*l%i,h=ht(u,n,i)*u%i,f=ht(h,r,i)*h%i,p=ht(f,s,i)*f%i,d=ht(p,s,i)*f%i,g=ht(d,e,i)*l%i;return{pow_p_5_8:ht(g,Ec,i)*t%i,b2:o}}function Iy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Sy(t,e){const n=Pi,r=le(e*e*e,n),s=le(r*r*e,n),i=_y(t*s).pow_p_5_8;let o=le(t*r*i,n);const a=le(e*o*o,n),c=o,l=le(o*vc,n),u=a===t,h=a===le(-t,n),f=a===le(-t*vc,n);return u&&(o=c),(h||f)&&(o=l),oy(o,n)&&(o=le(-o,n)),{isValid:u||h,value:o}}const Dy=yc(Pi,void 0,!0),Ay={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dy,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:xy,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Gg,randomBytes:rc,adjustScalarBytes:Iy,uvRatio:Sy},xc=by(Ay),Ty="EdDSA",Oy="JWT",es=".",ts="base64url",_c="utf8",Ic="utf8",$y=":",Ry="did",By="key",Sc="base58btc",Py="z",Cy="K36",Ny=32;function Ci(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Dc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ci(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ac(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=Dc(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Ci(n)}function Uy(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 s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=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,v=0,A=d.length;v!==A&&d[v]===0;)v++,g++;for(var w=(A-v)*u+1>>>0,m=new Uint8Array(w);v!==A;){for(var x=d[v],_=0,T=w-1;(x!==0||_<y)&&T!==-1;T--,_++)x+=256*m[T]>>>0,m[T]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=_,v++}for(var $=w-y;$!==w&&m[$]===0;)$++;for(var P=c.repeat(g);$<w;++$)P+=t.charAt(m[$]);return P}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,v=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*l+1>>>0,w=new Uint8Array(A);d[g];){var m=n[d.charCodeAt(g)];if(m===255)return;for(var x=0,_=A-1;(m!==0||x<v)&&_!==-1;_--,x++)m+=a*w[_]>>>0,w[_]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");v=x,g++}if(d[g]!==" "){for(var T=A-v;T!==A&&w[T]===0;)T++;for(var $=new Uint8Array(y+(A-T)),P=y;T!==A;)$[P++]=w[T++];return $}}}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 ky=Uy,Ly=ky;const Tc=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")},Fy=t=>new TextEncoder().encode(t),My=t=>new TextDecoder().decode(t);let qy=class{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")}},zy=class{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 Oc(this,e)}},jy=class{constructor(e){this.decoders=e}or(e){return Oc(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 Oc=(t,e)=>new jy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Vy=class{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new qy(e,n,r),this.decoder=new zy(e,n,s)}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 Vy(t,e,n,r),or=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=Ly(n,e);return ns({prefix:t,name:e,encode:r,decode:i=>Tc(s(i))})},Ky=(t,e,n,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Hy=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},me=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ns({prefix:e,name:t,encode(s){return Hy(s,r,n)},decode(s){return Ky(s,r,n,t)}}),Wy=ns({prefix:"\0",name:"identity",encode:t=>My(t),decode:t=>Fy(t)});var Gy=Object.freeze({__proto__:null,identity:Wy});const Yy=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zy=Object.freeze({__proto__:null,base2:Yy});const Xy=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jy=Object.freeze({__proto__:null,base8:Xy});const Qy=or({prefix:"9",name:"base10",alphabet:"0123456789"});var e0=Object.freeze({__proto__:null,base10:Qy});const t0=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),n0=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var r0=Object.freeze({__proto__:null,base16:t0,base16upper:n0});const s0=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),i0=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o0=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a0=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c0=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),l0=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),u0=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),h0=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),f0=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var d0=Object.freeze({__proto__:null,base32:s0,base32upper:i0,base32pad:o0,base32padupper:a0,base32hex:c0,base32hexupper:l0,base32hexpad:u0,base32hexpadupper:h0,base32z:f0});const p0=or({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),g0=or({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y0=Object.freeze({__proto__:null,base36:p0,base36upper:g0});const w0=or({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),m0=or({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var b0=Object.freeze({__proto__:null,base58btc:w0,base58flickr:m0});const v0=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),E0=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),x0=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_0=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var I0=Object.freeze({__proto__:null,base64:v0,base64pad:E0,base64url:x0,base64urlpad:_0});const $c=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}"),S0=$c.reduce((t,e,n)=>(t[n]=e,t),[]),D0=$c.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function A0(t){return t.reduce((e,n)=>(e+=S0[n],e),"")}function T0(t){const e=[];for(const n of t){const r=D0[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const O0=ns({prefix:"\u{1F680}",name:"base256emoji",encode:A0,decode:T0});var $0=Object.freeze({__proto__:null,base256emoji:O0}),R0=Bc,Rc=128,B0=-128,P0=Math.pow(2,31);function Bc(t,e,n){e=e||[],n=n||0;for(var r=n;t>=P0;)e[n++]=t&255|Rc,t/=128;for(;t&B0;)e[n++]=t&255|Rc,t>>>=7;return e[n]=t|0,Bc.bytes=n-r+1,e}var C0=Ni,N0=128,Pc=127;function Ni(t,r){var n=0,r=r||0,s=0,i=r,o,a=t.length;do{if(i>=a)throw Ni.bytes=0,new RangeError("Could not decode varint");o=t[i++],n+=s<28?(o&Pc)<<s:(o&Pc)*Math.pow(2,s),s+=7}while(o>=N0);return Ni.bytes=i-r,n}var U0=Math.pow(2,7),k0=Math.pow(2,14),L0=Math.pow(2,21),F0=Math.pow(2,28),M0=Math.pow(2,35),q0=Math.pow(2,42),z0=Math.pow(2,49),j0=Math.pow(2,56),V0=Math.pow(2,63),K0=function(t){return t<U0?1:t<k0?2:t<L0?3:t<F0?4:t<M0?5:t<q0?6:t<z0?7:t<j0?8:t<V0?9:10},H0={encode:R0,decode:C0,encodingLength:K0},Cc=H0;const Nc=(t,e,n=0)=>(Cc.encode(t,e,n),e),Uc=t=>Cc.encodingLength(t),Ui=(t,e)=>{const n=e.byteLength,r=Uc(t),s=r+Uc(n),i=new Uint8Array(s+n);return Nc(t,i,0),Nc(n,i,r),i.set(e,s),new W0(t,n,e,i)};class W0{constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}}const kc=({name:t,code:e,encode:n})=>new G0(t,e,n);class G0{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?Ui(this.code,n):n.then(r=>Ui(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Lc=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Y0=kc({name:"sha2-256",code:18,encode:Lc("SHA-256")}),Z0=kc({name:"sha2-512",code:19,encode:Lc("SHA-512")});var X0=Object.freeze({__proto__:null,sha256:Y0,sha512:Z0});const Fc=0,J0="identity",Mc=Tc;var Q0=Object.freeze({__proto__:null,identity:{code:Fc,name:J0,encode:Mc,digest:t=>Ui(Fc,Mc(t))}});const qc={...Gy,...Zy,...Jy,...e0,...r0,...d0,...y0,...b0,...I0,...$0};({...X0,...Q0});function zc(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const jc=zc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ki=zc("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=Dc(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Vc={utf8:jc,"utf-8":jc,hex:qc.base16,latin1:ki,ascii:ki,binary:ki,...qc};function rs(t,e="utf8"){const n=Vc[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 Fn(t,e="utf8"){const n=Vc[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ci(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Kc(t){return Un(rs(Fn(t,ts),_c))}function ss(t){return rs(Fn(rr(t),_c),ts)}function Hc(t){const e=Fn(Cy,Sc),n=Py+rs(Ac([e,t]),Sc);return[Ry,By,n].join($y)}function ew(t){return rs(t,ts)}function tw(t){return Fn(t,ts)}function nw(t){return Fn([ss(t.header),ss(t.payload)].join(es),Ic)}function rw(t){return[ss(t.header),ss(t.payload),ew(t.signature)].join(es)}function Li(t){const e=t.split(es),n=Kc(e[0]),r=Kc(e[1]),s=tw(e[2]),i=Fn(e.slice(0,2).join(es),Ic);return{header:n,payload:r,signature:s,data:i}}function Wc(t=rc(Ny)){const e=xc.getPublicKey(t);return{secretKey:Ac([t,e]),publicKey:e}}async function sw(t,e,n,r,s=F.fromMiliseconds(Date.now())){const i={alg:Ty,typ:Oy},o=Hc(r.publicKey),a=s+n,c={iss:o,sub:t,aud:e,iat:s,exp:a},l=nw({header:i,payload:c}),u=xc.sign(l,r.secretKey.slice(0,32));return rw({header:i,payload:c,signature:u})}function iw(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 s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=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,v=0,A=d.length;v!==A&&d[v]===0;)v++,g++;for(var w=(A-v)*u+1>>>0,m=new Uint8Array(w);v!==A;){for(var x=d[v],_=0,T=w-1;(x!==0||_<y)&&T!==-1;T--,_++)x+=256*m[T]>>>0,m[T]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=_,v++}for(var $=w-y;$!==w&&m[$]===0;)$++;for(var P=c.repeat(g);$<w;++$)P+=t.charAt(m[$]);return P}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,v=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*l+1>>>0,w=new Uint8Array(A);d[g];){var m=n[d.charCodeAt(g)];if(m===255)return;for(var x=0,_=A-1;(m!==0||x<v)&&_!==-1;_--,x++)m+=a*w[_]>>>0,w[_]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");v=x,g++}if(d[g]!==" "){for(var T=A-v;T!==A&&w[T]===0;)T++;for(var $=new Uint8Array(y+(A-T)),P=y;T!==A;)$[P++]=w[T++];return $}}}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 ow=iw,aw=ow;const cw=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")},lw=t=>new TextEncoder().encode(t),uw=t=>new TextDecoder().decode(t);let hw=class{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")}},fw=class{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 Gc(this,e)}};class dw{constructor(e){this.decoders=e}or(e){return Gc(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 Gc=(t,e)=>new dw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class pw{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new hw(e,n,r),this.decoder=new fw(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const is=({name:t,prefix:e,encode:n,decode:r})=>new pw(t,e,n,r),ar=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=aw(n,e);return is({prefix:t,name:e,encode:r,decode:i=>cw(s(i))})},gw=(t,e,n,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},yw=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},be=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>is({prefix:e,name:t,encode(s){return yw(s,r,n)},decode(s){return gw(s,r,n,t)}}),ww=is({prefix:"\0",name:"identity",encode:t=>uw(t),decode:t=>lw(t)});var mw=Object.freeze({__proto__:null,identity:ww});const bw=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var vw=Object.freeze({__proto__:null,base2:bw});const Ew=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xw=Object.freeze({__proto__:null,base8:Ew});const _w=ar({prefix:"9",name:"base10",alphabet:"0123456789"});var Iw=Object.freeze({__proto__:null,base10:_w});const Sw=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Dw=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Aw=Object.freeze({__proto__:null,base16:Sw,base16upper:Dw});const Tw=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ow=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$w=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rw=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bw=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pw=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cw=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nw=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uw=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var kw=Object.freeze({__proto__:null,base32:Tw,base32hex:Bw,base32hexpad:Cw,base32hexpadupper:Nw,base32hexupper:Pw,base32pad:$w,base32padupper:Rw,base32upper:Ow,base32z:Uw});const Lw=ar({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fw=ar({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mw=Object.freeze({__proto__:null,base36:Lw,base36upper:Fw});const qw=ar({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),zw=ar({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var jw=Object.freeze({__proto__:null,base58btc:qw,base58flickr:zw});const Vw=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kw=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hw=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ww=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gw=Object.freeze({__proto__:null,base64:Vw,base64pad:Kw,base64url:Hw,base64urlpad:Ww});const Yc=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}"),Yw=Yc.reduce((t,e,n)=>(t[n]=e,t),[]),Zw=Yc.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Xw(t){return t.reduce((e,n)=>(e+=Yw[n],e),"")}function Jw(t){const e=[];for(const n of t){const r=Zw[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Qw=is({prefix:"\u{1F680}",name:"base256emoji",encode:Xw,decode:Jw});var em=Object.freeze({__proto__:null,base256emoji:Qw});const Zc={...mw,...vw,...xw,...Iw,...Aw,...kw,...Mw,...jw,...Gw,...em};function Fi(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Xc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Fi(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jc(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Qc=Jc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Mi=Jc("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=Xc(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),el={utf8:Qc,"utf-8":Qc,hex:Zc.base16,latin1:Mi,ascii:Mi,binary:Mi,...Zc};function _e(t,e="utf8"){const n=el[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Fi(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var tl=function(t,e,n){if(n||arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},tm=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),nm=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),rm=function(){function t(e,n,r,s){this.name=e,this.version=n,this.os=r,this.bot=s,this.type="bot-device"}return t}(),sm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),im=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),om=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,am=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,nl=3,cm=[["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",om]],rl=[["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 lm(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new im:typeof navigator<"u"?hm(navigator.userAgent):dm()}function um(t){return t!==""&&cm.reduce(function(e,n){var r=n[0],s=n[1];if(e)return e;var i=s.exec(t);return!!i&&[r,i]},!1)}function hm(t){var e=um(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new sm;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length<nl&&(s=tl(tl([],s,!0),pm(nl-s.length),!0)):s=[];var i=s.join("."),o=fm(t),a=am.exec(t);return a&&a[1]?new rm(n,i,o,a[1]):new tm(n,i,o)}function fm(t){for(var e=0,n=rl.length;e<n;e++){var r=rl[e],s=r[0],i=r[1],o=i.exec(t);if(o)return s}return null}function dm(){var t=typeof process<"u"&&process.version;return t?new nm(process.version.slice(1)):null}function pm(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var Q={},sl;function il(){if(sl)return Q;sl=1,Object.defineProperty(Q,"__esModule",{value:!0}),Q.getLocalStorage=Q.getLocalStorageOrThrow=Q.getCrypto=Q.getCryptoOrThrow=Q.getLocation=Q.getLocationOrThrow=Q.getNavigator=Q.getNavigatorOrThrow=Q.getDocument=Q.getDocumentOrThrow=Q.getFromWindowOrThrow=Q.getFromWindow=void 0;function t(f){let p;return typeof window<"u"&&typeof window[f]<"u"&&(p=window[f]),p}Q.getFromWindow=t;function e(f){const p=t(f);if(!p)throw new Error(`${f} is not defined in Window`);return p}Q.getFromWindowOrThrow=e;function n(){return e("document")}Q.getDocumentOrThrow=n;function r(){return t("document")}Q.getDocument=r;function s(){return e("navigator")}Q.getNavigatorOrThrow=s;function i(){return t("navigator")}Q.getNavigator=i;function o(){return e("location")}Q.getLocationOrThrow=o;function a(){return t("location")}Q.getLocation=a;function c(){return e("crypto")}Q.getCryptoOrThrow=c;function l(){return t("crypto")}Q.getCrypto=l;function u(){return e("localStorage")}Q.getLocalStorageOrThrow=u;function h(){return t("localStorage")}return Q.getLocalStorage=h,Q}var xt=il(),cr={},ol;function gm(){if(ol)return cr;ol=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.getWindowMetadata=void 0;const t=il();function e(){let n,r;try{n=t.getDocumentOrThrow(),r=t.getLocationOrThrow()}catch{return null}function s(){const p=n.getElementsByTagName("link"),d=[];for(let g=0;g<p.length;g++){const y=p[g],v=y.getAttribute("rel");if(v&&v.toLowerCase().indexOf("icon")>-1){const A=y.getAttribute("href");if(A)if(A.toLowerCase().indexOf("https:")===-1&&A.toLowerCase().indexOf("http:")===-1&&A.indexOf("//")!==0){let w=r.protocol+"//"+r.host;if(A.indexOf("/")===0)w+=A;else{const m=r.pathname.split("/");m.pop();const x=m.join("/");w+=x+"/"+A}d.push(w)}else if(A.indexOf("//")===0){const w=r.protocol+A;d.push(w)}else d.push(A)}}return d}function i(...p){const d=n.getElementsByTagName("meta");for(let g=0;g<d.length;g++){const y=d[g],v=["itemprop","property","name"].map(A=>y.getAttribute(A)).filter(A=>A?p.includes(A):!1);if(v.length&&v){const A=y.getAttribute("content");if(A)return A}}return""}function o(){let p=i("name","og:site_name","og:title","twitter:title");return p||(p=n.title),p}function a(){return i("description","og:description","twitter:description","keywords")}const c=o(),l=a(),u=r.origin,h=s();return{description:l,url:u,icons:h,name:c}}return cr.getWindowMetadata=e,cr}var ym=gm();const os=BigInt(2**32-1),al=BigInt(32);function cl(t,e=!1){return e?{h:Number(t&os),l:Number(t>>al&os)}:{h:Number(t>>al&os)|0,l:Number(t&os)|0}}function ll(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:o,l:a}=cl(t[i],e);[r[i],s[i]]=[o,a]}return[r,s]}const ul=(t,e,n)=>t>>>n,hl=(t,e,n)=>t<<32-n|e>>>n,Ht=(t,e,n)=>t>>>n|e<<32-n,Wt=(t,e,n)=>t<<32-n|e>>>n,lr=(t,e,n)=>t<<64-n|e>>>n-32,ur=(t,e,n)=>t>>>n-32|e<<64-n,wm=(t,e)=>e,mm=(t,e)=>t,bm=(t,e,n)=>t<<n|e>>>32-n,vm=(t,e,n)=>e<<n|t>>>32-n,Em=(t,e,n)=>e<<n-32|t>>>64-n,xm=(t,e,n)=>t<<n-32|e>>>64-n;function et(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const qi=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),zi=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,_m=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Im=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Sm=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Dm=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Mn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function as(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ft(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function tt(t,...e){if(!as(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 cs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ft(t.outputLen),ft(t.blockLen)}function Gt(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 ji(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 hr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ke(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Vi(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dt(t,e){return t<<32-e|t>>>e}const fl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function dl(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const _t=fl?t=>t:t=>dl(t);function Am(t){for(let e=0;e<t.length;e++)t[e]=dl(t[e]);return t}const Yt=fl?t=>t:Am,pl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Tm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function qn(t){if(tt(t),pl)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Tm[t[n]];return e}const It={_0:48,_9:57,A:65,F:70,a:97,f:102};function gl(t){if(t>=It._0&&t<=It._9)return t-It._0;if(t>=It.A&&t<=It.F)return t-(It.A-10);if(t>=It.a&&t<=It.f)return t-(It.a-10)}function ls(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(pl)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 s=0,i=0;s<n;s++,i+=2){const o=gl(t.charCodeAt(i)),a=gl(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function yl(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function nt(t){return typeof t=="string"&&(t=yl(t)),tt(t),t}function St(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];tt(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}class us{}function fr(t){const e=r=>t().update(nt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Om(t){const e=(r,s)=>t(s).update(nt(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Zt(t=32){if(Mn&&typeof Mn.getRandomValues=="function")return Mn.getRandomValues(new Uint8Array(t));if(Mn&&typeof Mn.randomBytes=="function")return Uint8Array.from(Mn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const $m=BigInt(0),dr=BigInt(1),Rm=BigInt(2),Bm=BigInt(7),Pm=BigInt(256),Cm=BigInt(113),wl=[],ml=[],bl=[];for(let t=0,e=dr,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],wl.push(2*(5*r+n)),ml.push((t+1)*(t+2)/2%64);let s=$m;for(let i=0;i<7;i++)e=(e<<dr^(e>>Bm)*Cm)%Pm,e&Rm&&(s^=dr<<(dr<<BigInt(i))-dr);bl.push(s)}const vl=ll(bl,!0),Nm=vl[0],Um=vl[1],El=(t,e,n)=>n>32?Em(t,e,n):bm(t,e,n),xl=(t,e,n)=>n>32?xm(t,e,n):vm(t,e,n);function km(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,l=n[c],u=n[c+1],h=El(l,u,1)^n[a],f=xl(l,u,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=ml[o],c=El(s,i,a),l=xl(s,i,a),u=wl[o];s=t[u],i=t[u+1],t[u]=c,t[u+1]=l}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]^=Nm[r],t[1]^=Um[r]}Ke(n)}class Ki extends us{constructor(e,n,r,s=!1,i=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=s,this.rounds=i,ft(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=hr(this.state)}clone(){return this._cloneInto()}keccak(){Yt(this.state32),km(this.state32,this.rounds),Yt(this.state32),this.posOut=0,this.pos=0}update(e){Gt(this),e=nt(e),tt(e);const{blockLen:n,state:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);for(let a=0;a<o;a++)r[this.pos++]^=e[i++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,(n&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gt(this,!1),tt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let s=0,i=e.length;s<i;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(n.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ft(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(ji(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,Ke(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Ki(n,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Lm=(t,e,n)=>fr(()=>new Ki(e,t,n)),_l=Lm(1,136,256/8),Fm="0.1.1";function Mm(){return Fm}class ne extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof ne){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})(),s=n.cause instanceof ne&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||s?["",r?`Details: ${r}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
15
- `);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Mm()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return Il(this,e)}}function Il(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Il(t.cause,e):e?null:t}function qm(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function zm(t,e,n){return t&e^~t&n}function jm(t,e,n){return t&e^t&n^e&n}class Sl extends us{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Vi(this.buffer)}update(e){Gt(this),e=nt(e),tt(e);const{view:n,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=Vi(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gt(this),ji(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:i}=this;let{pos:o}=this;n[o++]=128,Ke(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let h=o;h<s;h++)n[h]=0;qm(r,s-8,BigInt(this.length*8),i),this.process(r,0);const a=Vi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}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:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ie=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Vm=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]),Jt=new Uint32Array(64);class Km extends Sl{constructor(e=32){super(64,e,8,!1),this.A=Xt[0]|0,this.B=Xt[1]|0,this.C=Xt[2]|0,this.D=Xt[3]|0,this.E=Xt[4]|0,this.F=Xt[5]|0,this.G=Xt[6]|0,this.H=Xt[7]|0}get(){const{A:e,B:n,C:r,D:s,E:i,F:o,G:a,H:c}=this;return[e,n,r,s,i,o,a,c]}set(e,n,r,s,i,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=i|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)Jt[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=Jt[h-15],p=Jt[h-2],d=dt(f,7)^dt(f,18)^f>>>3,g=dt(p,17)^dt(p,19)^p>>>10;Jt[h]=g+Jt[h-7]+d+Jt[h-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=dt(a,6)^dt(a,11)^dt(a,25),p=u+f+zm(a,c,l)+Vm[h]+Jt[h]|0,g=(dt(r,2)^dt(r,13)^dt(r,22))+jm(r,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=r,r=p+g|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,c,l,u)}roundClean(){Ke(Jt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ke(this.buffer)}}const Dl=ll(["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))),Hm=Dl[0],Wm=Dl[1],Qt=new Uint32Array(80),en=new Uint32Array(80);class Hi extends Sl{constructor(e=64){super(128,e,16,!1),this.Ah=Se[0]|0,this.Al=Se[1]|0,this.Bh=Se[2]|0,this.Bl=Se[3]|0,this.Ch=Se[4]|0,this.Cl=Se[5]|0,this.Dh=Se[6]|0,this.Dl=Se[7]|0,this.Eh=Se[8]|0,this.El=Se[9]|0,this.Fh=Se[10]|0,this.Fl=Se[11]|0,this.Gh=Se[12]|0,this.Gl=Se[13]|0,this.Hh=Se[14]|0,this.Hl=Se[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|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 w=0;w<16;w++,n+=4)Qt[w]=e.getUint32(n),en[w]=e.getUint32(n+=4);for(let w=16;w<80;w++){const m=Qt[w-15]|0,x=en[w-15]|0,_=Ht(m,x,1)^Ht(m,x,8)^ul(m,x,7),T=Wt(m,x,1)^Wt(m,x,8)^hl(m,x,7),$=Qt[w-2]|0,P=en[w-2]|0,k=Ht($,P,19)^lr($,P,61)^ul($,P,6),U=Wt($,P,19)^ur($,P,61)^hl($,P,6),N=_m(T,U,en[w-7],en[w-16]),S=Im(N,_,k,Qt[w-7],Qt[w-16]);Qt[w]=S|0,en[w]=N|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:v,Hl:A}=this;for(let w=0;w<80;w++){const m=Ht(h,f,14)^Ht(h,f,18)^lr(h,f,41),x=Wt(h,f,14)^Wt(h,f,18)^ur(h,f,41),_=h&p^~h&g,T=f&d^~f&y,$=Sm(A,x,T,Wm[w],en[w]),P=Dm($,v,m,_,Hm[w],Qt[w]),k=$|0,U=Ht(r,s,28)^lr(r,s,34)^lr(r,s,39),N=Wt(r,s,28)^ur(r,s,34)^ur(r,s,39),S=r&i^r&a^i&a,R=s&o^s&c^o&c;v=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=et(l|0,u|0,P|0,k|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const b=qi(k,N,R);r=zi(b,P,U,S),s=b|0}({h:r,l:s}=et(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=et(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=et(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=et(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=et(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=et(this.Gh|0,this.Gl|0,g|0,y|0),{h:v,l:A}=et(this.Hh|0,this.Hl|0,v|0,A|0),this.set(r,s,i,o,a,c,l,u,h,f,p,d,g,y,v,A)}roundClean(){Ke(Qt,en)}destroy(){Ke(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Gm extends Hi{constructor(){super(48),this.Ah=Ie[0]|0,this.Al=Ie[1]|0,this.Bh=Ie[2]|0,this.Bl=Ie[3]|0,this.Ch=Ie[4]|0,this.Cl=Ie[5]|0,this.Dh=Ie[6]|0,this.Dl=Ie[7]|0,this.Eh=Ie[8]|0,this.El=Ie[9]|0,this.Fh=Ie[10]|0,this.Fl=Ie[11]|0,this.Gh=Ie[12]|0,this.Gl=Ie[13]|0,this.Hh=Ie[14]|0,this.Hl=Ie[15]|0}}const De=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Ym extends Hi{constructor(){super(32),this.Ah=De[0]|0,this.Al=De[1]|0,this.Bh=De[2]|0,this.Bl=De[3]|0,this.Ch=De[4]|0,this.Cl=De[5]|0,this.Dh=De[6]|0,this.Dl=De[7]|0,this.Eh=De[8]|0,this.El=De[9]|0,this.Fh=De[10]|0,this.Fl=De[11]|0,this.Gh=De[12]|0,this.Gl=De[13]|0,this.Hh=De[14]|0,this.Hl=De[15]|0}}const mn=fr(()=>new Km),Zm=fr(()=>new Hi),Xm=fr(()=>new Gm),Jm=fr(()=>new Ym),hs=mn;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Wi=BigInt(0),Gi=BigInt(1);function pr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Yi(t){if(!pr(t))throw new Error("Uint8Array expected")}function gr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function fs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Al(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Wi:BigInt("0x"+t)}const Tl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function yr(t){if(Yi(t),Tl)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Qm[t[n]];return e}const Dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ol(t){if(t>=Dt._0&&t<=Dt._9)return t-Dt._0;if(t>=Dt.A&&t<=Dt.F)return t-(Dt.A-10);if(t>=Dt.a&&t<=Dt.f)return t-(Dt.a-10)}function ds(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Tl)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 s=0,i=0;s<n;s++,i+=2){const o=Ol(t.charCodeAt(i)),a=Ol(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function bn(t){return Al(yr(t))}function $l(t){return Yi(t),Al(yr(Uint8Array.from(t).reverse()))}function wr(t,e){return ds(t.toString(16).padStart(e*2,"0"))}function Rl(t,e){return wr(t,e).reverse()}function He(t,e,n){let r;if(typeof e=="string")try{r=ds(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(pr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function ps(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Yi(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}const Zi=t=>typeof t=="bigint"&&Wi<=t;function Xi(t,e,n){return Zi(t)&&Zi(e)&&Zi(n)&&e<=t&&t<n}function zn(t,e,n,r){if(!Xi(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function eb(t){let e;for(e=0;t>Wi;t>>=Gi,e+=1);return e}const gs=t=>(Gi<<BigInt(t))-Gi,Ji=t=>new Uint8Array(t),Bl=t=>Uint8Array.from(t);function tb(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=Ji(t),s=Ji(t),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...h)=>n(s,r,...h),c=(h=Ji(0))=>{s=a(Bl([0]),h),r=a(),h.length!==0&&(s=a(Bl([1]),h),r=a())},l=()=>{if(i++>=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 ps(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(l()));)c();return o(),p}}const nb={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"||pr(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 ys(t,e,n={}){const r=(s,i,o)=>{const a=nb[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function Pl(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}function rb(t,e){if(ql(t)>e)throw new Ib({givenSize:ql(t),maxSize:e})}const At={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cl(t){if(t>=At.zero&&t<=At.nine)return t-At.zero;if(t>=At.A&&t<=At.F)return t-(At.A-10);if(t>=At.a&&t<=At.f)return t-(At.a-10)}function sb(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new Sb({size:t.length,targetSize:r,type:"Bytes"});const s=new Uint8Array(r);for(let i=0;i<r;i++){const o=n==="right";s[o?i:r-i-1]=t[o?i:t.length-i-1]}return s}function Nl(t,e){if(tn(t)>e)throw new pb({givenSize:tn(t),maxSize:e})}function ib(t,e){if(typeof e=="number"&&e>0&&e>tn(t)-1)throw new Ml({offset:e,position:"start",size:tn(t)})}function ob(t,e,n){if(typeof e=="number"&&typeof n=="number"&&tn(t)!==n-e)throw new Ml({offset:n,position:"end",size:tn(t)})}function Ul(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const s=t.replace("0x","");if(s.length>r*2)throw new gb({size:Math.ceil(s.length/2),targetSize:r,type:"Hex"});return`0x${s[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const ab="#__bigint";function Qi(t,e,n){return JSON.stringify(t,(r,s)=>typeof s=="bigint"?s.toString()+ab:s,n)}const cb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function lb(t,e={}){const{strict:n=!1}=e;if(!t)throw new Ll(t);if(typeof t!="string")throw new Ll(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Fl(t);if(!t.startsWith("0x"))throw new Fl(t)}function ub(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function eo(t){return t instanceof Uint8Array?ws(t):Array.isArray(t)?ws(new Uint8Array(t)):t}function ws(t,e={}){let n="";for(let s=0;s<t.length;s++)n+=cb[t[s]];const r=`0x${n}`;return typeof e.size=="number"?(Nl(r,e.size),kl(r,e.size)):r}function to(t,e={}){const{signed:n,size:r}=e,s=BigInt(t);let i;r?n?i=(1n<<BigInt(r)*8n-1n)-1n:i=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&n?-i-1n:0;if(i&&s>i||s<o){const l=typeof t=="bigint"?"n":"";throw new db({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:n,size:r,value:`${t}${l}`})}const c=`0x${(n&&s<0?(1n<<BigInt(r*8))+BigInt(s):s).toString(16)}`;return r?hb(c,r):c}function hb(t,e){return Ul(t,{dir:"left",size:e})}function kl(t,e){return Ul(t,{dir:"right",size:e})}function Tt(t,e,n,r={}){const{strict:s}=r;ib(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return s&&ob(i,e,n),i}function tn(t){return Math.ceil((t.length-2)/2)}function fb(t,e={}){const{strict:n=!1}=e;try{return lb(t,{strict:n}),!0}catch{return!1}}class db extends ne{constructor({max:e,min:n,signed:r,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*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 Ll extends ne{constructor(e){super(`Value \`${typeof e=="object"?Qi(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Fl extends ne{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let pb=class extends ne{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 Ml extends ne{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let gb=class extends ne{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const yb=new TextEncoder;function wb(t){if(!(t instanceof Uint8Array)){if(!t)throw new ms(t);if(typeof t!="object")throw new ms(t);if(!("BYTES_PER_ELEMENT"in t))throw new ms(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new ms(t)}}function mb(t){return t instanceof Uint8Array?t:typeof t=="string"?vb(t):bb(t)}function bb(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function vb(t,e={}){const{size:n}=e;let r=t;n&&(Nl(t,n),r=kl(t,n));let s=r.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=Cl(s.charCodeAt(c++)),u=Cl(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new ne(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function Eb(t,e={}){const{size:n}=e,r=yb.encode(t);return typeof n=="number"?(rb(r,n),xb(r,n)):r}function xb(t,e){return sb(t,{dir:"right",size:e})}function ql(t){return t.length}function _b(t){try{return wb(t),!0}catch{return!1}}class ms extends ne{constructor(e){super(`Value \`${typeof e=="object"?Qi(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class Ib extends ne{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 Sb extends ne{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function zl(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=_l(mb(t));return n==="Bytes"?r:ws(r)}class Db 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 no={checksum:new Db(8192)}.checksum;function jl(t,e={}){const{compressed:n}=e,{prefix:r,x:s,y:i}=t;if(n===!1||typeof s=="bigint"&&typeof i=="bigint"){if(r!==4)throw new Kl({prefix:r,cause:new Bb});return}if(n===!0||typeof s=="bigint"&&typeof i>"u"){if(r!==3&&r!==2)throw new Kl({prefix:r,cause:new Rb});return}throw new $b({publicKey:t})}function Ab(t){const e=(()=>{if(fb(t))return Vl(t);if(_b(t))return Tb(t);const{prefix:n,x:r,y:s}=t;return typeof r=="bigint"&&typeof s=="bigint"?{prefix:n??4,x:r,y:s}:{prefix:n,x:r}})();return jl(e),e}function Tb(t){return Vl(ws(t))}function Vl(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new Pb({publicKey:t});if(t.length===130){const r=BigInt(Tt(t,0,32)),s=BigInt(Tt(t,32,64));return{prefix:4,x:r,y:s}}if(t.length===132){const r=Number(Tt(t,0,1)),s=BigInt(Tt(t,1,33)),i=BigInt(Tt(t,33,65));return{prefix:r,x:s,y:i}}const e=Number(Tt(t,0,1)),n=BigInt(Tt(t,1,33));return{prefix:e,x:n}}function Ob(t,e={}){jl(t);const{prefix:n,x:r,y:s}=t,{includePrefix:i=!0}=e;return ub(i?to(n,{size:1}):"0x",to(r,{size:32}),typeof s=="bigint"?to(s,{size:32}):"0x")}class $b extends ne{constructor({publicKey:e}){super(`Value \`${Qi(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Kl extends ne{constructor({prefix:e,cause:n}){super(`Prefix "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Rb extends ne{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Bb extends ne{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Pb=class extends ne{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${tn(eo(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Cb=/^0x[a-fA-F0-9]{40}$/;function Hl(t,e={}){const{strict:n=!0}=e;if(!Cb.test(t))throw new Gl({address:t,cause:new kb});if(n){if(t.toLowerCase()===t)return;if(Wl(t)!==t)throw new Gl({address:t,cause:new Lb})}}function Wl(t){if(no.has(t))return no.get(t);Hl(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=zl(Eb(e),{as:"Bytes"}),r=e.split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&r[i]&&(r[i]=r[i].toUpperCase()),(n[i>>1]&15)>=8&&r[i+1]&&(r[i+1]=r[i+1].toUpperCase());const s=`0x${r.join("")}`;return no.set(t,s),s}function Nb(t,e={}){const{checksum:n=!1}=e;return Hl(t),n?Wl(t):t}function Ub(t,e={}){const n=zl(`0x${Ob(t).slice(4)}`).substring(26);return Nb(`0x${n}`,e)}class Gl extends ne{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 kb extends ne{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 Lb extends ne{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class Yl extends us{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,cs(e);const r=nt(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 s=this.blockLen,i=new Uint8Array(s);i.set(r.length>s?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ke(i)}update(e){return Gt(this),this.iHash.update(e),this}digestInto(e){Gt(this),tt(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:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,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 mr=(t,e,n)=>new Yl(t,e).update(n).digest();mr.create=(t,e)=>new Yl(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ce=BigInt(0),Te=BigInt(1),vn=BigInt(2),Fb=BigInt(3),Zl=BigInt(4),Xl=BigInt(5),Jl=BigInt(8);function Ne(t,e){const n=t%e;return n>=Ce?n:e+n}function We(t,e,n){let r=t;for(;e-- >Ce;)r*=r,r%=n;return r}function ro(t,e){if(t===Ce)throw new Error("invert: expected non-zero number");if(e<=Ce)throw new Error("invert: expected positive modulus, got "+e);let n=Ne(t,e),r=e,s=Ce,i=Te;for(;n!==Ce;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==Te)throw new Error("invert: does not exist");return Ne(s,e)}function Ql(t,e){const n=(t.ORDER+Te)/Zl,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function Mb(t,e){const n=(t.ORDER-Xl)/Jl,r=t.mul(e,vn),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,vn),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function qb(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Te,n=0;for(;e%vn===Ce;)e/=vn,n++;let r=vn;const s=so(t);for(;tu(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ql;let i=s.pow(r,e);const o=(e+Te)/vn;return function(c,l){if(c.is0(l))return l;if(tu(c,l)!==1)throw new Error("Cannot find square root");let u=n,h=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,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===u)throw new Error("Cannot find square root");const y=Te<<BigInt(u-d-1),v=c.pow(h,y);u=d,h=c.sqr(v),f=c.mul(f,h),p=c.mul(p,v)}return p}}function zb(t){return t%Zl===Fb?Ql:t%Jl===Xl?Mb:qb(t)}const jb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=jb.reduce((r,s)=>(r[s]="function",r),e);return ys(t,n)}function Kb(t,e,n){if(n<Ce)throw new Error("invalid exponent, negatives unsupported");if(n===Ce)return t.ONE;if(n===Te)return e;let r=t.ONE,s=e;for(;n>Ce;)n&Te&&(r=t.mul(r,s)),s=t.sqr(s),n>>=Te;return r}function eu(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function tu(t,e){const n=(t.ORDER-Te)/vn,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function nu(t,e){e!==void 0&&ft(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function so(t,e,n=!1,r={}){if(t<=Ce)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=nu(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:gs(s),ZERO:Ce,ONE:Te,create:c=>Ne(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ce<=c&&c<t},is0:c=>c===Ce,isOdd:c=>(c&Te)===Te,neg:c=>Ne(-c,t),eql:(c,l)=>c===l,sqr:c=>Ne(c*c,t),add:(c,l)=>Ne(c+l,t),sub:(c,l)=>Ne(c-l,t),mul:(c,l)=>Ne(c*l,t),pow:(c,l)=>Kb(a,c,l),div:(c,l)=>Ne(c*ro(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ro(c,t),sqrt:r.sqrt||(c=>(o||(o=zb(t)),o(a,c))),toBytes:c=>n?Rl(c,i):wr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?$l(c):bn(c)},invertBatch:c=>eu(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function ru(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 su(t){const e=ru(t);return e+Math.ceil(e/2)}function Hb(t,e,n=!1){const r=t.length,s=ru(e),i=su(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?$l(t):bn(t),a=Ne(o,e-Te)+Te;return n?Rl(a,s):wr(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const iu=BigInt(0),io=BigInt(1);function oo(t,e){const n=e.negate();return t?n:e}function ou(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ao(t,e){ou(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=gs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function au(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=io);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}function Wb(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 Gb(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 co=new WeakMap,cu=new WeakMap;function lo(t){return cu.get(t)||1}function Yb(t,e){return{constTimeNegate:oo,hasPrecomputes(n){return lo(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>iu;)r&io&&(s=s.add(i)),i=i.double(),r>>=io;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=ao(r,e),o=[];let a=n,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<i;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,s){let i=t.ZERO,o=t.BASE;const a=ao(n,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:d}=au(s,c,a);s=l,h?o=o.add(oo(p,r[d])):i=i.add(oo(f,r[u]))}return{p:i,f:o}},wNAFUnsafe(n,r,s,i=t.ZERO){const o=ao(n,e);for(let a=0;a<o.windows&&s!==iu;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=au(s,a,o);if(s=c,!u){const f=r[l];i=i.add(h?f.negate():f)}}return i},getPrecomputes(n,r,s){let i=co.get(r);return i||(i=this.precomputeWindow(r,n),n!==1&&co.set(r,s(i))),i},wNAFCached(n,r,s){const i=lo(n);return this.wNAF(i,this.getPrecomputes(i,n,s),r)},wNAFCachedUnsafe(n,r,s,i){const o=lo(n);return o===1?this.unsafeLadder(n,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,n,s),r,i)},setWindowSize(n,r){ou(r,e),cu.set(n,r),co.delete(n)}}}function Zb(t,e,n,r){Wb(n,t),Gb(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=eb(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=gs(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){u.fill(o);for(let g=0;g<i;g++){const y=r[g],v=Number(y>>BigInt(p)&l);u[v]=u[v].add(n[g])}let d=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[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 lu(t){return Vb(t.Fp),ys(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...nu(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function uu(t){t.lowS!==void 0&&gr("lowS",t.lowS),t.prehash!==void 0&&gr("prehash",t.prehash)}function Xb(t){const e=lu(t);ys(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:s}=e;if(n){if(!r.eql(s,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})}const Ot={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(t,e)=>{const{Err:n}=Ot;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,s=fs(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?fs(s.length/2|128):"";return fs(t)+i+s+e},decode(t,e){const{Err:n}=Ot;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 s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&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 l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;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}=Ot;if(t<$t)throw new e("integer: negative integers are not allowed");let n=fs(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}=Ot;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 bn(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Ot,s=He("signature",t),{v:i,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=Ot,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),i=r+s;return e.encode(48,i)}};function uo(t,e){return yr(wr(t,e))}const $t=BigInt(0),ye=BigInt(1);BigInt(2);const ho=BigInt(3),Jb=BigInt(4);function Qb(t){const e=Xb(t),{Fp:n}=e,r=so(e.n,e.nBitLength),s=e.toBytes||((w,m,x)=>{const _=m.toAffine();return ps(Uint8Array.from([4]),n.toBytes(_.x),n.toBytes(_.y))}),i=e.fromBytes||(w=>{const m=w.subarray(1),x=n.fromBytes(m.subarray(0,n.BYTES)),_=n.fromBytes(m.subarray(n.BYTES,2*n.BYTES));return{x,y:_}});function o(w){const{a:m,b:x}=e,_=n.sqr(w),T=n.mul(_,w);return n.add(n.add(T,n.mul(w,m)),x)}function a(w,m){const x=n.sqr(m),_=o(w);return n.eql(x,_)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,ho),Jb),l=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,l)))throw new Error("bad curve params: a or b");function u(w){return Xi(w,ye,e.n)}function h(w){const{allowedPrivateKeyLengths:m,nByteLength:x,wrapPrivateKey:_,n:T}=e;if(m&&typeof w!="bigint"){if(pr(w)&&(w=yr(w)),typeof w!="string"||!m.includes(w.length))throw new Error("invalid private key");w=w.padStart(x*2,"0")}let $;try{$=typeof w=="bigint"?w:bn(He("private key",w,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof w)}return _&&($=Ne($,T)),zn("private key",$,ye,T),$}function f(w){if(!(w instanceof g))throw new Error("ProjectivePoint expected")}const p=Pl((w,m)=>{const{px:x,py:_,pz:T}=w;if(n.eql(T,n.ONE))return{x,y:_};const $=w.is0();m==null&&(m=$?n.ONE:n.inv(T));const P=n.mul(x,m),k=n.mul(_,m),U=n.mul(T,m);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(U,n.ONE))throw new Error("invZ was invalid");return{x:P,y:k}}),d=Pl(w=>{if(w.is0()){if(e.allowInfinityPoint&&!n.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:m,y:x}=w.toAffine();if(!n.isValid(m)||!n.isValid(x))throw new Error("bad point: x or y not FE");if(!a(m,x))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(m,x,_){if(m==null||!n.isValid(m))throw new Error("x required");if(x==null||!n.isValid(x)||n.is0(x))throw new Error("y required");if(_==null||!n.isValid(_))throw new Error("z required");this.px=m,this.py=x,this.pz=_,Object.freeze(this)}static fromAffine(m){const{x,y:_}=m||{};if(!m||!n.isValid(x)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof g)throw new Error("projective point not allowed");const T=$=>n.eql($,n.ZERO);return T(x)&&T(_)?g.ZERO:new g(x,_,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const x=eu(n,m.map(_=>_.pz));return m.map((_,T)=>_.toAffine(x[T])).map(g.fromAffine)}static fromHex(m){const x=g.fromAffine(i(He("pointHex",m)));return x.assertValidity(),x}static fromPrivateKey(m){return g.BASE.multiply(h(m))}static msm(m,x){return Zb(g,r,m,x)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){d(this)}hasEvenY(){const{y:m}=this.toAffine();if(n.isOdd)return!n.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){f(m);const{px:x,py:_,pz:T}=this,{px:$,py:P,pz:k}=m,U=n.eql(n.mul(x,k),n.mul($,T)),N=n.eql(n.mul(_,k),n.mul(P,T));return U&&N}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:m,b:x}=e,_=n.mul(x,ho),{px:T,py:$,pz:P}=this;let k=n.ZERO,U=n.ZERO,N=n.ZERO,S=n.mul(T,T),R=n.mul($,$),b=n.mul(P,P),E=n.mul(T,$);return E=n.add(E,E),N=n.mul(T,P),N=n.add(N,N),k=n.mul(m,N),U=n.mul(_,b),U=n.add(k,U),k=n.sub(R,U),U=n.add(R,U),U=n.mul(k,U),k=n.mul(E,k),N=n.mul(_,N),b=n.mul(m,b),E=n.sub(S,b),E=n.mul(m,E),E=n.add(E,N),N=n.add(S,S),S=n.add(N,S),S=n.add(S,b),S=n.mul(S,E),U=n.add(U,S),b=n.mul($,P),b=n.add(b,b),S=n.mul(b,E),k=n.sub(k,S),N=n.mul(b,R),N=n.add(N,N),N=n.add(N,N),new g(k,U,N)}add(m){f(m);const{px:x,py:_,pz:T}=this,{px:$,py:P,pz:k}=m;let U=n.ZERO,N=n.ZERO,S=n.ZERO;const R=e.a,b=n.mul(e.b,ho);let E=n.mul(x,$),D=n.mul(_,P),B=n.mul(T,k),I=n.add(x,_),O=n.add($,P);I=n.mul(I,O),O=n.add(E,D),I=n.sub(I,O),O=n.add(x,T);let C=n.add($,k);return O=n.mul(O,C),C=n.add(E,B),O=n.sub(O,C),C=n.add(_,T),U=n.add(P,k),C=n.mul(C,U),U=n.add(D,B),C=n.sub(C,U),S=n.mul(R,O),U=n.mul(b,B),S=n.add(U,S),U=n.sub(D,S),S=n.add(D,S),N=n.mul(U,S),D=n.add(E,E),D=n.add(D,E),B=n.mul(R,B),O=n.mul(b,O),D=n.add(D,B),B=n.sub(E,B),B=n.mul(R,B),O=n.add(O,B),E=n.mul(D,O),N=n.add(N,E),E=n.mul(C,O),U=n.mul(I,U),U=n.sub(U,E),E=n.mul(I,D),S=n.mul(C,S),S=n.add(S,E),new g(U,N,S)}subtract(m){return this.add(m.negate())}is0(){return this.equals(g.ZERO)}wNAF(m){return A.wNAFCached(this,m,g.normalizeZ)}multiplyUnsafe(m){const{endo:x,n:_}=e;zn("scalar",m,$t,_);const T=g.ZERO;if(m===$t)return T;if(this.is0()||m===ye)return this;if(!x||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,m,g.normalizeZ);let{k1neg:$,k1:P,k2neg:k,k2:U}=x.splitScalar(m),N=T,S=T,R=this;for(;P>$t||U>$t;)P&ye&&(N=N.add(R)),U&ye&&(S=S.add(R)),R=R.double(),P>>=ye,U>>=ye;return $&&(N=N.negate()),k&&(S=S.negate()),S=new g(n.mul(S.px,x.beta),S.py,S.pz),N.add(S)}multiply(m){const{endo:x,n:_}=e;zn("scalar",m,ye,_);let T,$;if(x){const{k1neg:P,k1:k,k2neg:U,k2:N}=x.splitScalar(m);let{p:S,f:R}=this.wNAF(k),{p:b,f:E}=this.wNAF(N);S=A.constTimeNegate(P,S),b=A.constTimeNegate(U,b),b=new g(n.mul(b.px,x.beta),b.py,b.pz),T=S.add(b),$=R.add(E)}else{const{p:P,f:k}=this.wNAF(m);T=P,$=k}return g.normalizeZ([T,$])[0]}multiplyAndAddUnsafe(m,x,_){const T=g.BASE,$=(k,U)=>U===$t||U===ye||!k.equals(T)?k.multiplyUnsafe(U):k.multiply(U),P=$(this,x).add($(m,_));return P.is0()?void 0:P}toAffine(m){return p(this,m)}isTorsionFree(){const{h:m,isTorsionFree:x}=e;if(m===ye)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:x}=e;return m===ye?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return gr("isCompressed",m),this.assertValidity(),s(g,this,m)}toHex(m=!0){return gr("isCompressed",m),yr(this.toRawBytes(m))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:y,nBitLength:v}=e,A=Yb(g,y?Math.ceil(v/2):v);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function e1(t){const e=lu(t);return ys(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function t1(t){const e=e1(t),{Fp:n,n:r,nByteLength:s,nBitLength:i}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(b){return Ne(b,r)}function l(b){return ro(b,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=Qb({...e,toBytes(b,E,D){const B=E.toAffine(),I=n.toBytes(B.x),O=ps;return gr("isCompressed",D),D?O(Uint8Array.from([E.hasEvenY()?2:3]),I):O(Uint8Array.from([4]),I,n.toBytes(B.y))},fromBytes(b){const E=b.length,D=b[0],B=b.subarray(1);if(E===o&&(D===2||D===3)){const I=bn(B);if(!Xi(I,ye,n.ORDER))throw new Error("Point is not on curve");const O=f(I);let C;try{C=n.sqrt(O)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const L=(C&ye)===ye;return(D&1)===1!==L&&(C=n.neg(C)),{x:I,y:C}}else if(E===a&&D===4){const I=n.fromBytes(B.subarray(0,n.BYTES)),O=n.fromBytes(B.subarray(n.BYTES,2*n.BYTES));return{x:I,y:O}}else{const I=o,O=a;throw new Error("invalid Point, expected length of "+I+", or uncompressed "+O+", got "+E)}}});function d(b){const E=r>>ye;return b>E}function g(b){return d(b)?c(-b):b}const y=(b,E,D)=>bn(b.slice(E,D));class v{constructor(E,D,B){zn("r",E,ye,r),zn("s",D,ye,r),this.r=E,this.s=D,B!=null&&(this.recovery=B),Object.freeze(this)}static fromCompact(E){const D=s;return E=He("compactSignature",E,D*2),new v(y(E,0,D),y(E,D,2*D))}static fromDER(E){const{r:D,s:B}=Ot.toSig(He("DER",E));return new v(D,B)}assertValidity(){}addRecoveryBit(E){return new v(this.r,this.s,E)}recoverPublicKey(E){const{r:D,s:B,recovery:I}=this,O=T(He("msgHash",E));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const C=I===2||I===3?D+e.n:D;if(C>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(I&1)===0?"02":"03",V=u.fromHex(L+uo(C,n.BYTES)),z=l(C),q=c(-O*z),K=c(B*z),W=u.BASE.multiplyAndAddUnsafe(V,q,K);if(!W)throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new v(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ds(this.toDERHex())}toDERHex(){return Ot.hexFromSig(this)}toCompactRawBytes(){return ds(this.toCompactHex())}toCompactHex(){const E=s;return uo(this.r,E)+uo(this.s,E)}}const A={isValidPrivateKey(b){try{return h(b),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const b=su(e.n);return Hb(e.randomBytes(b),e.n)},precompute(b=8,E=u.BASE){return E._setWindowSize(b),E.multiply(BigInt(3)),E}};function w(b,E=!0){return u.fromPrivateKey(b).toRawBytes(E)}function m(b){if(typeof b=="bigint")return!1;if(b instanceof u)return!0;const D=He("key",b).length,B=n.BYTES,I=B+1,O=2*B+1;if(!(e.allowedPrivateKeyLengths||s===I))return D===I||D===O}function x(b,E,D=!0){if(m(b)===!0)throw new Error("first arg must be private key");if(m(E)===!1)throw new Error("second arg must be public key");return u.fromHex(E).multiply(h(b)).toRawBytes(D)}const _=e.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const E=bn(b),D=b.length*8-i;return D>0?E>>BigInt(D):E},T=e.bits2int_modN||function(b){return c(_(b))},$=gs(i);function P(b){return zn("num < 2^"+i,b,$t,$),wr(b,s)}function k(b,E,D=U){if(["recovered","canonical"].some(H=>H in D))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:I}=e;let{lowS:O,prehash:C,extraEntropy:L}=D;O==null&&(O=!0),b=He("msgHash",b),uu(D),C&&(b=He("prehashed msgHash",B(b)));const V=T(b),z=h(E),q=[P(z),P(V)];if(L!=null&&L!==!1){const H=L===!0?I(n.BYTES):L;q.push(He("extraEntropy",H))}const K=ps(...q),W=V;function G(H){const Z=_(H);if(!p(Z))return;const ae=l(Z),ce=u.BASE.multiply(Z).toAffine(),we=c(ce.x);if(we===$t)return;const at=c(ae*c(W+we*z));if(at===$t)return;let ct=(ce.x===we?0:2)|Number(ce.y&ye),Gs=at;return O&&d(at)&&(Gs=g(at),ct^=1),new v(we,Gs,ct)}return{seed:K,k2sig:G}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function S(b,E,D=U){const{seed:B,k2sig:I}=k(b,E,D),O=e;return tb(O.hash.outputLen,O.nByteLength,O.hmac)(B,I)}u.BASE._setWindowSize(8);function R(b,E,D,B=N){const I=b;E=He("msgHash",E),D=He("publicKey",D);const{lowS:O,prehash:C,format:L}=B;if(uu(B),"strict"in B)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 V=typeof I=="string"||pr(I),z=!V&&!L&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!V&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,K;try{if(z&&(q=new v(I.r,I.s)),V){try{L!=="compact"&&(q=v.fromDER(I))}catch(ct){if(!(ct instanceof Ot.Err))throw ct}!q&&L!=="der"&&(q=v.fromCompact(I))}K=u.fromHex(D)}catch{return!1}if(!q||O&&q.hasHighS())return!1;C&&(E=e.hash(E));const{r:W,s:G}=q,H=T(E),Z=l(G),ae=c(H*Z),ce=c(W*Z),we=u.BASE.multiplyAndAddUnsafe(K,ae,ce)?.toAffine();return we?c(we.x)===W:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:x,sign:S,verify:R,ProjectivePoint:u,Signature:v,utils:A}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function n1(t){return{hash:t,hmac:(e,...n)=>mr(t,e,St(...n)),randomBytes:Zt}}function r1(t,e){const n=r=>t1({...t,...n1(r)});return{...n(e),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const hu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),fu=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),s1=BigInt(0),i1=BigInt(1),fo=BigInt(2),du=(t,e)=>(t+e/fo)/e;function o1(t){const e=hu,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=We(u,n,e)*u%e,f=We(h,n,e)*u%e,p=We(f,fo,e)*l%e,d=We(p,s,e)*p%e,g=We(d,i,e)*d%e,y=We(g,a,e)*g%e,v=We(y,c,e)*y%e,A=We(v,a,e)*g%e,w=We(A,n,e)*u%e,m=We(w,o,e)*d%e,x=We(m,r,e)*l%e,_=We(x,fo,e);if(!po.eql(po.sqr(_),t))throw new Error("Cannot find square root");return _}const po=so(hu,void 0,void 0,{sqrt:o1}),a1=r1({a:s1,b:BigInt(7),Fp:po,n:fu,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=fu,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-i1*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=du(i*t,e),c=du(-r*t,e);let l=Ne(t-a*n-c*s,e),u=Ne(-a*r-c*i,e);const h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}}},mn);function c1(t){if(t.length!==130&&t.length!==132)throw new u1({signature:t});const e=BigInt(Tt(t,0,32)),n=BigInt(Tt(t,32,64)),r=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return l1(s)}catch{throw new h1({value:s})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function l1(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new f1({value:t})}class u1 extends ne{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${tn(eo(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class h1 extends ne{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class f1 extends ne{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}const d1=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]),ue=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),j=new Uint32Array(32);function nn(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=j[2*t],l=j[2*t+1],u=j[2*e],h=j[2*e+1],f=j[2*n],p=j[2*n+1],d=j[2*r],g=j[2*r+1],y=qi(c,u,o);l=zi(y,l,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^l,Dl:d^c},{Dh:g,Dl:d}={Dh:wm(g,d),Dl:mm(g)},{h:p,l:f}=et(p,f,g,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:Ht(h,u,24),Bl:Wt(h,u,24)},j[2*t]=c,j[2*t+1]=l,j[2*e]=u,j[2*e+1]=h,j[2*n]=f,j[2*n+1]=p,j[2*r]=d,j[2*r+1]=g}function rn(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=j[2*t],l=j[2*t+1],u=j[2*e],h=j[2*e+1],f=j[2*n],p=j[2*n+1],d=j[2*r],g=j[2*r+1],y=qi(c,u,o);l=zi(y,l,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^l,Dl:d^c},{Dh:g,Dl:d}={Dh:Ht(g,d,16),Dl:Wt(g,d,16)},{h:p,l:f}=et(p,f,g,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:lr(h,u,63),Bl:ur(h,u,63)},j[2*t]=c,j[2*t+1]=l,j[2*e]=u,j[2*e+1]=h,j[2*n]=f,j[2*n+1]=p,j[2*r]=d,j[2*r+1]=g}function p1(t,e={},n,r,s){if(ft(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.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!==s)throw new Error("personalization must be undefined or "+s)}class g1 extends us{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ft(e),ft(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=hr(this.buffer)}update(e){Gt(this),e=nt(e),tt(e);const{blockLen:n,buffer:r,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===n&&(Yt(s),this.compress(s,0,!1),Yt(s),this.pos=0);const l=Math.min(n-this.pos,i-c),u=o+c;if(l===n&&!(u%4)&&c+l<i){const h=new Uint32Array(a,u,Math.floor((i-c)/4));Yt(h);for(let f=0;c+n<i;f+=s.length,c+=n)this.length+=n,this.compress(h,f,!1);Yt(h);continue}r.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Gt(this),ji(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,Ke(this.buffer.subarray(n)),Yt(r),this.compress(r,0,!0),Yt(r);const s=hr(e);this.get().forEach((i,o)=>s[o]=_t(i))}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:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=i,e.finished=s,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class y1 extends g1{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=ue[0]|0,this.v0h=ue[1]|0,this.v1l=ue[2]|0,this.v1h=ue[3]|0,this.v2l=ue[4]|0,this.v2h=ue[5]|0,this.v3l=ue[6]|0,this.v3h=ue[7]|0,this.v4l=ue[8]|0,this.v4h=ue[9]|0,this.v5l=ue[10]|0,this.v5h=ue[11]|0,this.v6l=ue[12]|0,this.v6h=ue[13]|0,this.v7l=ue[14]|0,this.v7h=ue[15]|0,p1(n,e,64,16,16);let{key:r,personalization:s,salt:i}=e,o=0;if(r!==void 0&&(r=nt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=nt(i);const a=hr(i);this.v4l^=_t(a[0]),this.v4h^=_t(a[1]),this.v5l^=_t(a[2]),this.v5h^=_t(a[3])}if(s!==void 0){s=nt(s);const a=hr(s);this.v6l^=_t(a[0]),this.v6h^=_t(a[1]),this.v7l^=_t(a[2]),this.v7h^=_t(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:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:h,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|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,l)=>j[l]=c),j.set(ue,16);let{h:s,l:i}=cl(BigInt(this.length));j[24]=ue[8]^i,j[25]=ue[9]^s,r&&(j[28]=~j[28],j[29]=~j[29]);let o=0;const a=d1;for(let c=0;c<12;c++)nn(0,4,8,12,e,n+2*a[o++]),rn(0,4,8,12,e,n+2*a[o++]),nn(1,5,9,13,e,n+2*a[o++]),rn(1,5,9,13,e,n+2*a[o++]),nn(2,6,10,14,e,n+2*a[o++]),rn(2,6,10,14,e,n+2*a[o++]),nn(3,7,11,15,e,n+2*a[o++]),rn(3,7,11,15,e,n+2*a[o++]),nn(0,5,10,15,e,n+2*a[o++]),rn(0,5,10,15,e,n+2*a[o++]),nn(1,6,11,12,e,n+2*a[o++]),rn(1,6,11,12,e,n+2*a[o++]),nn(2,7,8,13,e,n+2*a[o++]),rn(2,7,8,13,e,n+2*a[o++]),nn(3,4,9,14,e,n+2*a[o++]),rn(3,4,9,14,e,n+2*a[o++]);this.v0l^=j[0]^j[16],this.v0h^=j[1]^j[17],this.v1l^=j[2]^j[18],this.v1h^=j[3]^j[19],this.v2l^=j[4]^j[20],this.v2h^=j[5]^j[21],this.v3l^=j[6]^j[22],this.v3h^=j[7]^j[23],this.v4l^=j[8]^j[24],this.v4h^=j[9]^j[25],this.v5l^=j[10]^j[26],this.v5h^=j[11]^j[27],this.v6l^=j[12]^j[28],this.v6h^=j[13]^j[29],this.v7l^=j[14]^j[30],this.v7h^=j[15]^j[31],Ke(j)}destroy(){this.destroyed=!0,Ke(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const w1=Om(t=>new y1(t));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function pu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function gu(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 bs(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function br(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function vs(t){if(!Array.isArray(t))throw new Error("array expected")}function Es(t,e){if(!gu(!0,e))throw new Error(`${t}: array of strings expected`)}function yu(t,e){if(!gu(!1,e))throw new Error(`${t}: array of numbers expected`)}function wu(...t){const e=i=>i,n=(i,o)=>a=>i(o(a)),r=t.map(i=>i.encode).reduceRight(n,e),s=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:s}}function mu(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Es("alphabet",e);const r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(vs(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(vs(s),s.map(i=>{bs("alphabet.decode",i);const o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function bu(t=""){return bs("join",t),{encode:e=>(Es("join.decode",e),e.join(t)),decode:e=>(bs("join.decode",e),e.split(t))}}function m1(t,e="="){return br(t),bs("padding",e),{encode(n){for(Es("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Es("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 vu(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(vs(t),!t.length)return[];let r=0;const s=[],i=Array.from(t,a=>{if(br(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let l=r;l<o;l++){const u=i[l],h=e*a,f=h+u;if(!Number.isSafeInteger(f)||h/e!==a||f-u!==h)throw new Error("convertRadix: carry overflow");const p=f/n;a=f%n;const d=Math.floor(p);if(i[l]=d,!Number.isSafeInteger(d)||d*n+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:r=l;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}const Eu=(t,e)=>e===0?t:Eu(e,t%e),xs=(t,e)=>t+(e-Eu(t,e)),go=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function xu(t,e,n,r){if(vs(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(xs(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${xs(e,n)}`);let s=0,i=0;const o=go[e],a=go[n]-1,c=[];for(const l of t){if(br(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((s>>i-n&a)>>>0);const u=go[i];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&c.push(s>>>0),c}function b1(t){br(t);const e=2**8;return{encode:n=>{if(!pu(n))throw new Error("radix.encode input should be Uint8Array");return vu(Array.from(n),e,t)},decode:n=>(yu("radix.decode",n),Uint8Array.from(vu(n,t,e)))}}function v1(t,e=!1){if(br(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(xs(8,t)>32||xs(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!pu(n))throw new Error("radix2.encode input should be Uint8Array");return xu(Array.from(n),8,t,!e)},decode:n=>(yu("radix2.decode",n),Uint8Array.from(xu(n,t,8,e)))}}const E1=wu(v1(5),mu("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),m1(5),bu("")),vr=(t=>wu(b1(58),mu(t),bu("")))("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function x1(t){return Ub(_1(t))}function _1(t){const{payload:e,signature:n}=t,{r,s,yParity:i}=n,a=new a1.Signature(BigInt(r),BigInt(s)).addRecoveryBit(i).recoverPublicKey(eo(e).substring(2));return Ab(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function _u(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function wo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ue(t,...e){if(!_u(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 Iu(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 I1(t,e){Ue(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function sn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function jn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function S1(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const D1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function A1(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function mo(t){if(typeof t=="string")t=A1(t);else if(_u(t))t=bo(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function T1(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function O1(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 $1=(t,e)=>{function n(r,...s){if(Ue(r),!D1)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?Ue(u):Ue(u,t.nonceLength)}const i=t.tagLength;i&&s[1]!==void 0&&Ue(s[1]);const o=e(r,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");Ue(h)}};let c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ue(u),a(o.encrypt.length,h),o.encrypt(u,h)},decrypt(u,h){if(Ue(u),i&&u.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,h),o.decrypt(u,h)}}}return Object.assign(n,t),n};function Su(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&&!B1(e))throw new Error("invalid output, must be aligned");return e}function Du(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=4,l=0;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function R1(t,e,n){yo(n);const r=new Uint8Array(16),s=S1(r);return Du(s,0,BigInt(e),n),Du(s,8,BigInt(t),n),r}function B1(t){return t.byteOffset%4===0}function bo(t){return Uint8Array.from(t)}function P1(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const i=t.charCodeAt(r);(i&64512)===56320&&(++r,s=((s&1023)<<10)+(i&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function C1(t,e,n){const r=t.length;let s=n,i=0;for(;i<r;){let o=t.charCodeAt(i++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&i<r){const a=t.charCodeAt(i);(a&64512)===56320&&(++i,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const N1=new TextEncoder,U1=50;function k1(t,e,n){N1.encodeInto(t,e.subarray(n))}function L1(t,e,n){t.length>U1?k1(t,e,n):C1(t,e,n)}const F1=4096;function Au(t,e,n){let r=e;const s=r+n,i=[];let o="";for(;r<s;){const a=t[r++];if((a&128)===0)i.push(a);else if((a&224)===192){const c=t[r++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,l=t[r++]&63;i.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[r++]&63,l=t[r++]&63,u=t[r++]&63;let h=(a&7)<<18|c<<12|l<<6|u;h>65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|h&1023),i.push(h)}else i.push(a);i.length>=F1&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}const M1=new TextDecoder,q1=200;function z1(t,e,n){const r=t.subarray(e,e+n);return M1.decode(r)}function j1(t,e,n){return n>q1?z1(t,e,n):Au(t,e,n)}class _s{type;data;constructor(e,n){this.type=e,this.data=n}}class Me extends Error{constructor(e){super(e);const n=Object.create(Me.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Me.name})}}const Er=4294967295;function V1(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Tu(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Ou(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function K1(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const H1=-1,W1=4294967296-1,G1=17179869184-1;function Y1({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=G1)if(e===0&&t<=W1){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Tu(r,4,t),n}}function Z1(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function X1(t){if(t instanceof Date){const e=Z1(t);return Y1(e)}else return null}function J1(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),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{const n=Ou(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Me(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Q1(t){const e=J1(t);return new Date(e.sec*1e3+e.nsec/1e6)}const ev={type:H1,encode:X1,decode:Q1};class Is{static defaultCodec=new Is;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(ev)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const i=s(e,n);if(i!=null){const o=-1-r;return new _s(o,i)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const i=s(e,n);if(i!=null){const o=r;return new _s(o,i)}}}return e instanceof _s?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new _s(n,e)}}function tv(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function vo(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):tv(t)?new Uint8Array(t):Uint8Array.from(t)}const nv=100,rv=2048;class Eo{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Is.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??nv,this.initialBufferSize=e?.initialBufferSize??rv,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 Eo({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),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=P1(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),L1(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=vo(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 s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const i of r){const o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const 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),V1(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Tu(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 sv(t,e){return new Eo(e).encodeSharedRef(t)}function xo(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const iv=16,ov=16;class av{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=iv,n=ov){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 s=this.caches[r-1];e:for(const i of s){const o=i.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return i.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const i=Au(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}}const _o="array",xr="map_key",$u="map_value",cv=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Me("The type of key must be string or number but "+typeof t)};class lv{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=_o,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=xr,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===_o){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===xr||e.type===$u){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 _r=-1,Io=new DataView(new ArrayBuffer(0)),uv=new Uint8Array(Io.buffer);try{Io.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 Ru=new RangeError("Insufficient data"),hv=new av;class So{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Io;bytes=uv;headByte=_r;stack=new lv;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Is.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Er,this.maxBinLength=e?.maxBinLength??Er,this.maxArrayLength=e?.maxArrayLength??Er,this.maxMapLength=e?.maxMapLength??Er,this.maxExtLength=e?.maxExtLength??Er,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:hv,this.mapKeyConverter=e?.mapKeyConverter??cv}clone(){return new So({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=_r,this.stack.reset()}setBuffer(e){const n=vo(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===_r&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=vo(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}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:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${xo(s)} at ${o} (${i} 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,s=-1;for await(const i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,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 s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,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 s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Me(`Unrecognized type byte: ${xo(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===_o)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===xr){if(n==="__proto__")throw new Me("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=$u;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=xr;continue e}}return n}}readHeadByte(){return this.headByte===_r&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=_r}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 Me(`Unrecognized array type byte: ${xo(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Me(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Me(`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 Me(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Ru;const r=this.pos+n;let s;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?s=this.keyDecoder.decode(this.bytes,r,e):s=j1(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===xr:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Me(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Ru;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Me(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=K1(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Ou(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 fv(t,e){return new So(e).decode(t)}function Rt(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=Xc(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Fi(n)}function he(t,e="utf8"){const n=el[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 Bu=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),dv=Bu("expand 16-byte k"),pv=Bu("expand 32-byte k"),gv=sn(dv),yv=sn(pv);function X(t,e){return t<<e|t>>>32-e}function Do(t){return t.byteOffset%4===0}const Ss=64,wv=16,Pu=2**32-1,Cu=new Uint32Array;function mv(t,e,n,r,s,i,o,a){const c=s.length,l=new Uint8Array(Ss),u=sn(l),h=Do(s)&&Do(i),f=h?sn(s):Cu,p=h?sn(i):Cu;for(let d=0;d<c;o++){if(t(e,n,r,u,o,a),o>=Pu)throw new Error("arx: counter overflow");const g=Math.min(Ss,c-d);if(h&&g===Ss){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let v=0,A;v<wv;v++)A=y+v,p[A]=f[A]^u[v];d+=Ss;continue}for(let y=0,v;y<g;y++)v=d+y,i[v]=s[v]^l[y];d+=g}}function bv(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:s,counterRight:i,rounds:o}=T1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return wo(s),wo(o),yo(i),yo(n),(a,c,l,u,h=0)=>{Ue(a),Ue(c),Ue(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),Ue(u),wo(h),h<0||h>=Pu)throw new Error("arx: counter overflow");if(u.length<f)throw new Error(`arx: output (${u.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=bo(a)),y=yv;else if(d===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=gv,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);Do(c)||p.push(c=bo(c));const v=sn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,v,sn(c.subarray(0,16)),v),c=c.subarray(16)}const A=16-s;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){const m=new Uint8Array(12);m.set(c,i?0:12-c.length),c=m,p.push(c)}const w=sn(c);return mv(t,y,v,w,l,u,h,o),jn(...p),u}}const ve=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class vv{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=mo(e),Ue(e,32);const n=ve(e,0),r=ve(e,2),s=ve(e,4),i=ve(e,6),o=ve(e,8),a=ve(e,10),c=ve(e,12),l=ve(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ve(e,16+2*u)}process(e,n,r=!1){const s=r?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],h=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],v=ve(e,n+0),A=ve(e,n+2),w=ve(e,n+4),m=ve(e,n+6),x=ve(e,n+8),_=ve(e,n+10),T=ve(e,n+12),$=ve(e,n+14);let P=i[0]+(v&8191),k=i[1]+((v>>>13|A<<3)&8191),U=i[2]+((A>>>10|w<<6)&8191),N=i[3]+((w>>>7|m<<9)&8191),S=i[4]+((m>>>4|x<<12)&8191),R=i[5]+(x>>>1&8191),b=i[6]+((x>>>14|_<<2)&8191),E=i[7]+((_>>>11|T<<5)&8191),D=i[8]+((T>>>8|$<<8)&8191),B=i[9]+($>>>5|s),I=0,O=I+P*a+k*(5*y)+U*(5*g)+N*(5*d)+S*(5*p);I=O>>>13,O&=8191,O+=R*(5*f)+b*(5*h)+E*(5*u)+D*(5*l)+B*(5*c),I+=O>>>13,O&=8191;let C=I+P*c+k*a+U*(5*y)+N*(5*g)+S*(5*d);I=C>>>13,C&=8191,C+=R*(5*p)+b*(5*f)+E*(5*h)+D*(5*u)+B*(5*l),I+=C>>>13,C&=8191;let L=I+P*l+k*c+U*a+N*(5*y)+S*(5*g);I=L>>>13,L&=8191,L+=R*(5*d)+b*(5*p)+E*(5*f)+D*(5*h)+B*(5*u),I+=L>>>13,L&=8191;let V=I+P*u+k*l+U*c+N*a+S*(5*y);I=V>>>13,V&=8191,V+=R*(5*g)+b*(5*d)+E*(5*p)+D*(5*f)+B*(5*h),I+=V>>>13,V&=8191;let z=I+P*h+k*u+U*l+N*c+S*a;I=z>>>13,z&=8191,z+=R*(5*y)+b*(5*g)+E*(5*d)+D*(5*p)+B*(5*f),I+=z>>>13,z&=8191;let q=I+P*f+k*h+U*u+N*l+S*c;I=q>>>13,q&=8191,q+=R*a+b*(5*y)+E*(5*g)+D*(5*d)+B*(5*p),I+=q>>>13,q&=8191;let K=I+P*p+k*f+U*h+N*u+S*l;I=K>>>13,K&=8191,K+=R*c+b*a+E*(5*y)+D*(5*g)+B*(5*d),I+=K>>>13,K&=8191;let W=I+P*d+k*p+U*f+N*h+S*u;I=W>>>13,W&=8191,W+=R*l+b*c+E*a+D*(5*y)+B*(5*g),I+=W>>>13,W&=8191;let G=I+P*g+k*d+U*p+N*f+S*h;I=G>>>13,G&=8191,G+=R*u+b*l+E*c+D*a+B*(5*y),I+=G>>>13,G&=8191;let H=I+P*y+k*g+U*d+N*p+S*f;I=H>>>13,H&=8191,H+=R*h+b*u+E*l+D*c+B*a,I+=H>>>13,H&=8191,I=(I<<2)+I|0,I=I+O|0,O=I&8191,I=I>>>13,C+=I,i[0]=O,i[1]=C,i[2]=L,i[3]=V,i[4]=z,i[5]=q,i[6]=K,i[7]=W,i[8]=G,i[9]=H}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|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;jn(r)}update(e){Iu(this),e=mo(e),Ue(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o===r){for(;r<=s-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){jn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Iu(this),I1(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:s}=this;if(s){for(n[s++]=1;s<16;s++)n[s]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=r[o]>>>0,e[i++]=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 Ev(t){const e=(r,s)=>t(s).update(mo(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const xv=Ev(t=>new vv(t));function _v(t,e,n,r,s,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],v=e[7],A=s,w=n[0],m=n[1],x=n[2],_=o,T=a,$=c,P=l,k=u,U=h,N=f,S=p,R=d,b=g,E=y,D=v,B=A,I=w,O=m,C=x;for(let V=0;V<i;V+=2)_=_+k|0,B=X(B^_,16),R=R+B|0,k=X(k^R,12),_=_+k|0,B=X(B^_,8),R=R+B|0,k=X(k^R,7),T=T+U|0,I=X(I^T,16),b=b+I|0,U=X(U^b,12),T=T+U|0,I=X(I^T,8),b=b+I|0,U=X(U^b,7),$=$+N|0,O=X(O^$,16),E=E+O|0,N=X(N^E,12),$=$+N|0,O=X(O^$,8),E=E+O|0,N=X(N^E,7),P=P+S|0,C=X(C^P,16),D=D+C|0,S=X(S^D,12),P=P+S|0,C=X(C^P,8),D=D+C|0,S=X(S^D,7),_=_+U|0,C=X(C^_,16),E=E+C|0,U=X(U^E,12),_=_+U|0,C=X(C^_,8),E=E+C|0,U=X(U^E,7),T=T+N|0,B=X(B^T,16),D=D+B|0,N=X(N^D,12),T=T+N|0,B=X(B^T,8),D=D+B|0,N=X(N^D,7),$=$+S|0,I=X(I^$,16),R=R+I|0,S=X(S^R,12),$=$+S|0,I=X(I^$,8),R=R+I|0,S=X(S^R,7),P=P+k|0,O=X(O^P,16),b=b+O|0,k=X(k^b,12),P=P+k|0,O=X(O^P,8),b=b+O|0,k=X(k^b,7);let L=0;r[L++]=o+_|0,r[L++]=a+T|0,r[L++]=c+$|0,r[L++]=l+P|0,r[L++]=u+k|0,r[L++]=h+U|0,r[L++]=f+N|0,r[L++]=p+S|0,r[L++]=d+R|0,r[L++]=g+b|0,r[L++]=y+E|0,r[L++]=v+D|0,r[L++]=A+B|0,r[L++]=w+I|0,r[L++]=m+O|0,r[L++]=x+C|0}const Iv=bv(_v,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Sv=new Uint8Array(16),Nu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(Sv.subarray(n))},Dv=new Uint8Array(32);function Uu(t,e,n,r,s){const i=t(e,n,Dv),o=xv.create(i);s&&Nu(o,s),Nu(o,r);const a=R1(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return jn(i,a),c}const ku=$1({blockSize:64,nonceLength:12,tagLength:16},(t=>(e,n,r)=>({encrypt(i,o){const a=i.length;o=Su(a+16,o,!1),o.set(i);const c=o.subarray(0,-16);t(e,n,c,c,1);const l=Uu(t,e,n,c,r);return o.set(l,a),jn(l),o},decrypt(i,o){o=Su(i.length-16,o,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=Uu(t,e,n,a,r);if(!O1(c,l))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),t(e,n,o,o,1),jn(l),o}}))(Iv));function Av(t,e,n){return cs(t),n===void 0&&(n=new Uint8Array(t.outputLen)),mr(t,nt(n),nt(e))}const Ao=Uint8Array.from([0]),Lu=Uint8Array.of();function Tv(t,e,n,r=32){cs(t),ft(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/s);n===void 0&&(n=Lu);const o=new Uint8Array(i*s),a=mr.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<i;u++)Ao[0]=u+1,c.update(u===0?Lu:l).update(n).update(Ao).digestInto(l),o.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ke(l,Ao),o.slice(0,r)}const Ov=(t,e,n,r,s)=>Tv(t,Av(t,e,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const To=BigInt(0),Oo=BigInt(1);function Ds(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function En(t,e,n=""){const r=as(t),s=t?.length,i=e!==void 0;if(!r||i&&s!==e){const o=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function As(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Fu(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?To:BigInt("0x"+t)}function Ts(t){return Fu(qn(t))}function Os(t){return tt(t),Fu(qn(Uint8Array.from(t).reverse()))}function $o(t,e){return ls(t.toString(16).padStart(e*2,"0"))}function Ro(t,e){return $o(t,e).reverse()}function Ae(t,e,n){let r;if(typeof e=="string")try{r=ls(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(as(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}const Bo=t=>typeof t=="bigint"&&To<=t;function $v(t,e,n){return Bo(t)&&Bo(e)&&Bo(n)&&e<=t&&t<n}function Po(t,e,n,r){if(!$v(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Mu(t){let e;for(e=0;t>To;t>>=Oo,e+=1);return e}const Ir=t=>(Oo<<BigInt(t))-Oo;function Rv(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=p=>new Uint8Array(p),s=p=>Uint8Array.of(p);let i=r(t),o=r(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...p)=>n(o,i,...p),u=(p=r(0))=>{o=l(s(0),p),i=l(),p.length!==0&&(o=l(s(1),p),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const d=[];for(;p<e;){i=l();const g=i.slice();d.push(g),p+=i.length}return St(...d)};return(p,d)=>{c(),u(p);let g;for(;!(g=d(h()));)u();return c(),g}}function $s(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,i,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>r(s,i,!1)),Object.entries(n).forEach(([s,i])=>r(s,i,!0))}function qu(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ke=BigInt(0),Oe=BigInt(1),xn=BigInt(2),zu=BigInt(3),ju=BigInt(4),Vu=BigInt(5),Bv=BigInt(7),Ku=BigInt(8),Pv=BigInt(9),Hu=BigInt(16);function qe(t,e){const n=t%e;return n>=ke?n:e+n}function rt(t,e,n){let r=t;for(;e-- >ke;)r*=r,r%=n;return r}function Wu(t,e){if(t===ke)throw new Error("invert: expected non-zero number");if(e<=ke)throw new Error("invert: expected positive modulus, got "+e);let n=qe(t,e),r=e,s=ke,i=Oe;for(;n!==ke;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==Oe)throw new Error("invert: does not exist");return qe(s,e)}function Co(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Gu(t,e){const n=(t.ORDER+Oe)/ju,r=t.pow(e,n);return Co(t,r,e),r}function Cv(t,e){const n=(t.ORDER-Vu)/Ku,r=t.mul(e,xn),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,xn),s),a=t.mul(i,t.sub(o,t.ONE));return Co(t,a,e),a}function Nv(t){const e=on(t),n=Yu(t),r=n(e,e.neg(e.ONE)),s=n(e,r),i=n(e,e.neg(r)),o=(t+Bv)/Hu;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const h=a.mul(l,s),f=a.mul(l,i),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(f,h,d);const g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return Co(a,y,c),y}}function Yu(t){if(t<zu)throw new Error("sqrt is not defined for small field");let e=t-Oe,n=0;for(;e%xn===ke;)e/=xn,n++;let r=xn;const s=on(t);for(;Xu(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Gu;let i=s.pow(r,e);const o=(e+Oe)/xn;return function(c,l){if(c.is0(l))return l;if(Xu(c,l)!==1)throw new Error("Cannot find square root");let u=n,h=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,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===u)throw new Error("Cannot find square root");const y=Oe<<BigInt(u-d-1),v=c.pow(h,y);u=d,h=c.sqr(v),f=c.mul(f,h),p=c.mul(p,v)}return p}}function Uv(t){return t%ju===zu?Gu:t%Ku===Vu?Cv:t%Hu===Pv?Nv(t):Yu(t)}const kv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lv(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=kv.reduce((r,s)=>(r[s]="function",r),e);return $s(t,n),t}function Fv(t,e,n){if(n<ke)throw new Error("invalid exponent, negatives unsupported");if(n===ke)return t.ONE;if(n===Oe)return e;let r=t.ONE,s=e;for(;n>ke;)n&Oe&&(r=t.mul(r,s)),s=t.sqr(s),n>>=Oe;return r}function Zu(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function Xu(t,e){const n=(t.ORDER-Oe)/xn,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Ju(t,e){e!==void 0&&ft(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function on(t,e,n=!1,r={}){if(t<=ke)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(s=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=Ju(t,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Ir(c),ZERO:ke,ONE:Oe,allowedLengths:a,create:f=>qe(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ke<=f&&f<t},is0:f=>f===ke,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&Oe)===Oe,neg:f=>qe(-f,t),eql:(f,p)=>f===p,sqr:f=>qe(f*f,t),add:(f,p)=>qe(f+p,t),sub:(f,p)=>qe(f-p,t),mul:(f,p)=>qe(f*p,t),pow:(f,p)=>Fv(h,f,p),div:(f,p)=>qe(f*Wu(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>Wu(f,t),sqrt:i||(f=>(u||(u=Uv(t)),u(h,f))),toBytes:f=>n?Ro(f,l):$o(f,l),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const g=new Uint8Array(l);g.set(f,n?0:g.length-f.length),f=g}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let d=n?Os(f):Ts(f);if(o&&(d=qe(d,t)),!p&&!h.isValid(d))throw new Error("invalid field element: outside of range 0..ORDER");return d},invertBatch:f=>Zu(h,f),cmov:(f,p,d)=>d?p:f});return Object.freeze(h)}function Qu(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 eh(t){const e=Qu(t);return e+Math.ceil(e/2)}function Mv(t,e,n=!1){const r=t.length,s=Qu(e),i=eh(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?Os(t):Ts(t),a=qe(o,e-Oe)+Oe;return n?Ro(a,s):$o(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vn=BigInt(0),_n=BigInt(1);function Rs(t,e){const n=e.negate();return t?n:e}function No(t,e){const n=Zu(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function th(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Uo(t,e){th(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=Ir(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function nh(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=_n);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}function qv(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 zv(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 ko=new WeakMap,rh=new WeakMap;function Lo(t){return rh.get(t)||1}function sh(t){if(t!==Vn)throw new Error("invalid wNAF")}class jv{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 s=e;for(;n>Vn;)n&_n&&(r=r.add(s)),s=s.double(),n>>=_n;return r}precomputeWindow(e,n){const{windows:r,windowSize:s}=Uo(n,this.bits),i=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,i.push(a);for(let l=1;l<s;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE;const o=Uo(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=nh(r,a,o);r=c,u?i=i.add(Rs(f,n[p])):s=s.add(Rs(h,n[l]))}return sh(r),{p:s,f:i}}wNAFUnsafe(e,n,r,s=this.ZERO){const i=Uo(e,this.bits);for(let o=0;o<i.windows&&r!==Vn;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=nh(r,o,i);if(r=a,!l){const h=n[c];s=s.add(u?h.negate():h)}}return sh(r),s}getPrecomputes(e,n,r){let s=ko.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(s=r(s)),ko.set(n,s))),s}cached(e,n,r){const s=Lo(e);return this.wNAF(s,this.getPrecomputes(s,e,r),n)}unsafe(e,n,r,s){const i=Lo(e);return i===1?this._unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,s)}createCache(e,n){th(n,this.bits),rh.set(e,n),ko.delete(e)}hasCache(e){return Lo(e)!==1}}function Vv(t,e,n,r){let s=e,i=t.ZERO,o=t.ZERO;for(;n>Vn||r>Vn;)n&_n&&(i=i.add(s)),r&_n&&(o=o.add(s)),s=s.double(),n>>=_n,r>>=_n;return{p1:i,p2:o}}function Kv(t,e,n,r){qv(n,t),zv(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Mu(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ir(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){u.fill(o);for(let g=0;g<i;g++){const y=r[g],v=Number(y>>BigInt(p)&l);u[v]=u[v].add(n[g])}let d=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[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 ih(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lv(e),e}else return on(t,{isLE:n})}function Hv(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 l=e[c];if(!(typeof l=="bigint"&&l>Vn))throw new Error(`CURVE.${c} must be positive bigint`)}const s=ih(e.p,n.Fp,r),i=ih(e.n,n.Fn,r),a=["Gx","Gy","a","b"];for(const c of a)if(!s.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:s,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(0),BigInt(1),BigInt(2),BigInt(8),yl("HashToScalar-");/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sr=BigInt(0),Kn=BigInt(1),Bs=BigInt(2);function Wv(t){return $s(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function Gv(t){const e=Wv(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:i,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||Zt,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?Bs**BigInt(254):Bs**BigInt(447),d=a?BigInt(8)*Bs**BigInt(251)-Kn:BigInt(4)*Bs**BigInt(445)-Kn,g=p+d+Kn,y=S=>qe(S,n),v=A(h);function A(S){return Ro(y(S),u)}function w(S){const R=Ae("u coordinate",S,u);return a&&(R[31]&=127),y(Os(R))}function m(S){return Os(s(Ae("scalar",S,u)))}function x(S,R){const b=$(w(R),m(S));if(b===Sr)throw new Error("invalid private or public key received");return A(b)}function _(S){return x(S,v)}function T(S,R,b){const E=y(S*(R-b));return R=y(R-E),b=y(b+E),{x_2:R,x_3:b}}function $(S,R){Po("u",S,Sr,n),Po("scalar",R,p,g);const b=R,E=S;let D=Kn,B=Sr,I=S,O=Kn,C=Sr;for(let V=BigInt(l-1);V>=Sr;V--){const z=b>>V&Kn;C^=z,{x_2:D,x_3:I}=T(C,D,I),{x_2:B,x_3:O}=T(C,B,O),C=z;const q=D+B,K=y(q*q),W=D-B,G=y(W*W),H=K-G,Z=I+O,ae=I-O,ce=y(ae*q),we=y(Z*W),at=ce+we,ct=ce-we;I=y(at*at),O=y(E*y(ct*ct)),D=y(K*G),B=y(H*(K+y(f*H)))}({x_2:D,x_3:I}=T(C,D,I)),{x_2:B,x_3:O}=T(C,B,O);const L=i(B);return y(D*L)}const P={secretKey:u,publicKey:u,seed:u},k=(S=c(u))=>(tt(S,P.seed),S);function U(S){const R=k(S);return{secretKey:R,publicKey:_(R)}}return{keygen:U,getSharedSecret:(S,R)=>x(S,R),getPublicKey:S=>_(S),scalarMult:x,scalarMultBase:_,utils:{randomSecretKey:k,randomPrivateKey:k},GuBytes:v.slice(),lengths:P}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yv=BigInt(1),oh=BigInt(2),Zv=BigInt(3),Xv=BigInt(5),Jv=BigInt(8),ah=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qv={p:ah,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jv,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eE(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=ah,a=t*t%i*t%i,c=rt(a,oh,i)*a%i,l=rt(c,Yv,i)*t%i,u=rt(l,Xv,i)*l%i,h=rt(u,e,i)*u%i,f=rt(h,n,i)*h%i,p=rt(f,r,i)*f%i,d=rt(p,s,i)*p%i,g=rt(d,s,i)*p%i,y=rt(g,e,i)*u%i;return{pow_p_5_8:rt(y,oh,i)*t%i,b2:a}}function tE(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const nE=on(Qv.p,{isLE:!0}),Fo=(()=>{const t=nE.ORDER;return Gv({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=eE(e);return qe(rt(n,Zv,t)*r,t)},adjustScalarBytes:tE})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ch=(t,e)=>(t+(t>=0?e:-e)/lh)/e;function rE(t,e,n){const[[r,s],[i,o]]=e,a=ch(o*t,n),c=ch(-s*t,n);let l=t-a*r-c*i,u=-a*s-c*o;const h=l<Pt,f=u<Pt;h&&(l=-l),f&&(u=-u);const p=Ir(Math.ceil(Mu(n)/2))+Hn;if(l<Pt||l>=p||u<Pt||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}function Mo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function qo(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Ds(n.lowS,"lowS"),Ds(n.prehash,"prehash"),n.format!==void 0&&Mo(n.format),n}class sE extends Error{constructor(e=""){super(e)}}const Bt={Err:sE,_tlv:{encode:(t,e)=>{const{Err:n}=Bt;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,s=As(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?As(s.length/2|128):"";return As(t)+i+s+e},decode(t,e){const{Err:n}=Bt;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 s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&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 l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;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}=Bt;if(t<Pt)throw new e("integer: negative integers are not allowed");let n=As(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}=Bt;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 Ts(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Bt,s=Ae("signature",t),{v:i,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=Bt,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),i=r+s;return e.encode(48,i)}},Pt=BigInt(0),Hn=BigInt(1),lh=BigInt(2),Ps=BigInt(3),iE=BigInt(4);function Wn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let s=Ae("private key",e);try{r=t.fromBytes(s)}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 oE(t,e={}){const n=Hv("weierstrass",t,e),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o,n:a}=i;$s(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=hh(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(N,S,R){const{x:b,y:E}=S.toAffine(),D=r.toBytes(b);if(Ds(R,"isCompressed"),R){u();const B=!r.isOdd(E);return St(uh(B),D)}else return St(Uint8Array.of(4),D,r.toBytes(E))}function f(N){En(N,void 0,"Point");const{publicKey:S,publicKeyUncompressed:R}=l,b=N.length,E=N[0],D=N.subarray(1);if(b===S&&(E===2||E===3)){const B=r.fromBytes(D);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");const I=g(B);let O;try{O=r.sqrt(I)}catch(V){const z=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+z)}u();const C=r.isOdd(O);return(E&1)===1!==C&&(O=r.neg(O)),{x:B,y:O}}else if(b===R&&E===4){const B=r.BYTES,I=r.fromBytes(D.subarray(0,B)),O=r.fromBytes(D.subarray(B,B*2));if(!y(I,O))throw new Error("bad point: is not on curve");return{x:I,y:O}}else throw new Error(`bad point: got length ${b}, expected compressed=${S} or uncompressed=${R}`)}const p=e.toBytes||h,d=e.fromBytes||f;function g(N){const S=r.sqr(N),R=r.mul(S,N);return r.add(r.add(R,r.mul(N,i.a)),i.b)}function y(N,S){const R=r.sqr(S),b=g(N);return r.eql(R,b)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const v=r.mul(r.pow(i.a,Ps),iE),A=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(v,A)))throw new Error("bad curve params: a or b");function w(N,S,R=!1){if(!r.isValid(S)||R&&r.is0(S))throw new Error(`bad point coordinate ${N}`);return S}function m(N){if(!(N instanceof P))throw new Error("ProjectivePoint expected")}function x(N){if(!c||!c.basises)throw new Error("no endo");return rE(N,c.basises,s.ORDER)}const _=qu((N,S)=>{const{X:R,Y:b,Z:E}=N;if(r.eql(E,r.ONE))return{x:R,y:b};const D=N.is0();S==null&&(S=D?r.ONE:r.inv(E));const B=r.mul(R,S),I=r.mul(b,S),O=r.mul(E,S);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:B,y:I}}),T=qu(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}const{x:S,y:R}=N.toAffine();if(!r.isValid(S)||!r.isValid(R))throw new Error("bad point: x or y not field elements");if(!y(S,R))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function $(N,S,R,b,E){return R=new P(r.mul(R.X,N),R.Y,R.Z),S=Rs(b,S),R=Rs(E,R),S.add(R)}class P{constructor(S,R,b){this.X=w("x",S),this.Y=w("y",R,!0),this.Z=w("z",b),Object.freeze(this)}static CURVE(){return i}static fromAffine(S){const{x:R,y:b}=S||{};if(!S||!r.isValid(R)||!r.isValid(b))throw new Error("invalid affine point");if(S instanceof P)throw new Error("projective point not allowed");return r.is0(R)&&r.is0(b)?P.ZERO:new P(R,b,r.ONE)}static fromBytes(S){const R=P.fromAffine(d(En(S,void 0,"point")));return R.assertValidity(),R}static fromHex(S){return P.fromBytes(Ae("pointHex",S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,R=!0){return U.createCache(this,S),R||this.multiply(Ps),this}assertValidity(){T(this)}hasEvenY(){const{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){m(S);const{X:R,Y:b,Z:E}=this,{X:D,Y:B,Z:I}=S,O=r.eql(r.mul(R,I),r.mul(D,E)),C=r.eql(r.mul(b,I),r.mul(B,E));return O&&C}negate(){return new P(this.X,r.neg(this.Y),this.Z)}double(){const{a:S,b:R}=i,b=r.mul(R,Ps),{X:E,Y:D,Z:B}=this;let I=r.ZERO,O=r.ZERO,C=r.ZERO,L=r.mul(E,E),V=r.mul(D,D),z=r.mul(B,B),q=r.mul(E,D);return q=r.add(q,q),C=r.mul(E,B),C=r.add(C,C),I=r.mul(S,C),O=r.mul(b,z),O=r.add(I,O),I=r.sub(V,O),O=r.add(V,O),O=r.mul(I,O),I=r.mul(q,I),C=r.mul(b,C),z=r.mul(S,z),q=r.sub(L,z),q=r.mul(S,q),q=r.add(q,C),C=r.add(L,L),L=r.add(C,L),L=r.add(L,z),L=r.mul(L,q),O=r.add(O,L),z=r.mul(D,B),z=r.add(z,z),L=r.mul(z,q),I=r.sub(I,L),C=r.mul(z,V),C=r.add(C,C),C=r.add(C,C),new P(I,O,C)}add(S){m(S);const{X:R,Y:b,Z:E}=this,{X:D,Y:B,Z:I}=S;let O=r.ZERO,C=r.ZERO,L=r.ZERO;const V=i.a,z=r.mul(i.b,Ps);let q=r.mul(R,D),K=r.mul(b,B),W=r.mul(E,I),G=r.add(R,b),H=r.add(D,B);G=r.mul(G,H),H=r.add(q,K),G=r.sub(G,H),H=r.add(R,E);let Z=r.add(D,I);return H=r.mul(H,Z),Z=r.add(q,W),H=r.sub(H,Z),Z=r.add(b,E),O=r.add(B,I),Z=r.mul(Z,O),O=r.add(K,W),Z=r.sub(Z,O),L=r.mul(V,H),O=r.mul(z,W),L=r.add(O,L),O=r.sub(K,L),L=r.add(K,L),C=r.mul(O,L),K=r.add(q,q),K=r.add(K,q),W=r.mul(V,W),H=r.mul(z,H),K=r.add(K,W),W=r.sub(q,W),W=r.mul(V,W),H=r.add(H,W),q=r.mul(K,H),C=r.add(C,q),q=r.mul(Z,H),O=r.mul(G,O),O=r.sub(O,q),q=r.mul(G,K),L=r.mul(Z,L),L=r.add(L,q),new P(O,C,L)}subtract(S){return this.add(S.negate())}is0(){return this.equals(P.ZERO)}multiply(S){const{endo:R}=e;if(!s.isValidNot0(S))throw new Error("invalid scalar: out of range");let b,E;const D=B=>U.cached(this,B,I=>No(P,I));if(R){const{k1neg:B,k1:I,k2neg:O,k2:C}=x(S),{p:L,f:V}=D(I),{p:z,f:q}=D(C);E=V.add(q),b=$(R.beta,L,z,B,O)}else{const{p:B,f:I}=D(S);b=B,E=I}return No(P,[b,E])[0]}multiplyUnsafe(S){const{endo:R}=e,b=this;if(!s.isValid(S))throw new Error("invalid scalar: out of range");if(S===Pt||b.is0())return P.ZERO;if(S===Hn)return b;if(U.hasCache(this))return this.multiply(S);if(R){const{k1neg:E,k1:D,k2neg:B,k2:I}=x(S),{p1:O,p2:C}=Vv(P,b,D,I);return $(R.beta,O,C,E,B)}else return U.unsafe(b,S)}multiplyAndAddUnsafe(S,R,b){const E=this.multiplyUnsafe(R).add(S.multiplyUnsafe(b));return E.is0()?void 0:E}toAffine(S){return _(this,S)}isTorsionFree(){const{isTorsionFree:S}=e;return o===Hn?!0:S?S(P,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:S}=e;return o===Hn?this:S?S(P,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(S=!0){return Ds(S,"isCompressed"),this.assertValidity(),p(P,this,S)}toHex(S=!0){return qn(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(S=!0){return this.toBytes(S)}_setWindowSize(S){this.precompute(S)}static normalizeZ(S){return No(P,S)}static msm(S,R){return Kv(P,s,S,R)}static fromPrivateKey(S){return P.BASE.multiply(Wn(s,S))}}P.BASE=new P(i.Gx,i.Gy,r.ONE),P.ZERO=new P(r.ZERO,r.ONE,r.ZERO),P.Fp=r,P.Fn=s;const k=s.BITS,U=new jv(P,e.endo?Math.ceil(k/2):k);return P.BASE.precompute(8),P}function uh(t){return Uint8Array.of(t?2:3)}function hh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function aE(t,e={}){const{Fn:n}=t,r=e.randomBytes||Zt,s=Object.assign(hh(t.Fp,n),{seed:eh(n.ORDER)});function i(p){try{return!!Wn(n,p)}catch{return!1}}function o(p,d){const{publicKey:g,publicKeyUncompressed:y}=s;try{const v=p.length;return d===!0&&v!==g||d===!1&&v!==y?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return Mv(En(p,s.seed,"seed"),n.ORDER)}function c(p,d=!0){return t.BASE.multiply(Wn(n,p)).toBytes(d)}function l(p){const d=a(p);return{secretKey:d,publicKey:c(d)}}function u(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;const{secretKey:d,publicKey:g,publicKeyUncompressed:y}=s;if(n.allowedLengths||d===g)return;const v=Ae("key",p).length;return v===g||v===y}function h(p,d,g=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");const y=Wn(n,p);return t.fromHex(d).multiply(y).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:p=>Wn(n,p),precompute(p=8,d=t.BASE){return d.precompute(p,!1)}},lengths:s})}function cE(t,e,n={}){cs(e),$s(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Zt,s=n.hmac||((R,...b)=>mr(e,R,St(...b))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=aE(t,n),d={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(R){const b=a>>Hn;return R>b}function v(R,b){if(!o.isValidNot0(b))throw new Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return b}function A(R,b){Mo(b);const E=p.signature,D=b==="compact"?E:b==="recovered"?E+1:void 0;return En(R,D,`${b} signature`)}class w{constructor(b,E,D){this.r=v("r",b),this.s=v("s",E),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(b,E=g){A(b,E);let D;if(E==="der"){const{r:C,s:L}=Bt.toSig(En(b));return new w(C,L)}E==="recovered"&&(D=b[0],E="compact",b=b.subarray(1));const B=o.BYTES,I=b.subarray(0,B),O=b.subarray(B,B*2);return new w(o.fromBytes(I),o.fromBytes(O),D)}static fromHex(b,E){return this.fromBytes(ls(b),E)}addRecoveryBit(b){return new w(this.r,this.s,b)}recoverPublicKey(b){const E=i.ORDER,{r:D,s:B,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*lh<E&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const C=I===2||I===3?D+a:D;if(!i.isValid(C))throw new Error("recovery id 2 or 3 invalid");const L=i.toBytes(C),V=t.fromBytes(St(uh((I&1)===0),L)),z=o.inv(C),q=x(Ae("msgHash",b)),K=o.create(-q*z),W=o.create(B*z),G=t.BASE.multiplyUnsafe(K).add(V.multiplyUnsafe(W));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return y(this.s)}toBytes(b=g){if(Mo(b),b==="der")return ls(Bt.hexFromSig(this));const E=o.toBytes(this.r),D=o.toBytes(this.s);if(b==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return St(Uint8Array.of(this.recovery),E,D)}return St(E,D)}toHex(b){return qn(this.toBytes(b))}assertValidity(){}static fromCompact(b){return w.fromBytes(Ae("sig",b),"compact")}static fromDER(b){return w.fromBytes(Ae("sig",b),"der")}normalizeS(){return this.hasHighS()?new w(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return qn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return qn(this.toBytes("compact"))}}const m=n.bits2int||function(b){if(b.length>8192)throw new Error("input is too large");const E=Ts(b),D=b.length*8-c;return D>0?E>>BigInt(D):E},x=n.bits2int_modN||function(b){return o.create(m(b))},_=Ir(c);function T(R){return Po("num < 2^"+c,R,Pt,_),o.toBytes(R)}function $(R,b){return En(R,void 0,"message"),b?En(e(R),void 0,"prehashed message"):R}function P(R,b,E){if(["recovered","canonical"].some(K=>K in E))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:B,extraEntropy:I}=qo(E,d);R=$(R,B);const O=x(R),C=Wn(o,b),L=[T(C),T(O)];if(I!=null&&I!==!1){const K=I===!0?r(p.secretKey):I;L.push(Ae("extraEntropy",K))}const V=St(...L),z=O;function q(K){const W=m(K);if(!o.isValidNot0(W))return;const G=o.inv(W),H=t.BASE.multiply(W).toAffine(),Z=o.create(H.x);if(Z===Pt)return;const ae=o.create(G*o.create(z+Z*C));if(ae===Pt)return;let ce=(H.x===Z?0:2)|Number(H.y&Hn),we=ae;return D&&y(ae)&&(we=o.neg(ae),ce^=1),new w(Z,we,ce)}return{seed:V,k2sig:q}}function k(R,b,E={}){R=Ae("message",R);const{seed:D,k2sig:B}=P(R,b,E);return Rv(e.outputLen,o.BYTES,s)(D,B)}function U(R){let b;const E=typeof R=="string"||as(R),D=!E&&R!==null&&typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint";if(!E&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)b=new w(R.r,R.s);else if(E){try{b=w.fromBytes(Ae("sig",R),"der")}catch(B){if(!(B instanceof Bt.Err))throw B}if(!b)try{b=w.fromBytes(Ae("sig",R),"compact")}catch{return!1}}return b||!1}function N(R,b,E,D={}){const{lowS:B,prehash:I,format:O}=qo(D,d);if(E=Ae("publicKey",E),b=$(Ae("message",b),I),"strict"in D)throw new Error("options.strict was renamed to lowS");const C=O===void 0?U(R):w.fromBytes(Ae("sig",R),O);if(C===!1)return!1;try{const L=t.fromBytes(E);if(B&&C.hasHighS())return!1;const{r:V,s:z}=C,q=x(b),K=o.inv(z),W=o.create(q*K),G=o.create(V*K),H=t.BASE.multiplyUnsafe(W).add(L.multiplyUnsafe(G));return H.is0()?!1:o.create(H.x)===V}catch{return!1}}function S(R,b,E={}){const{prehash:D}=qo(E,d);return b=$(b,D),w.fromBytes(R,"recovered").recoverPublicKey(b).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p,Point:t,sign:k,verify:N,recoverPublicKey:S,Signature:w,hash:e})}function lE(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 s=on(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function uE(t){const{CURVE:e,curveOpts:n}=lE(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 hE(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Ju(n.Fn.ORDER,n.Fn.BITS))})}function fE(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:s}=uE(t),i=oE(e,n),o=cE(i,r,s);return hE(t,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function zo(t,e){const n=r=>fE({...t,hash:r});return{...n(e),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},dh={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},ph={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},dE=on(fh.p),pE=on(dh.p),gE=on(ph.p),yE=zo({...fh,Fp:dE,lowS:!1},mn);zo({...dh,Fp:pE,lowS:!1},Xm),zo({...ph,Fp:gE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Zm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wE=yE,mE={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"}};var jo,gh;function yh(){if(gh)return jo;gh=1;const t="Input must be an string, Buffer or Uint8Array";function e(o){let a;if(o instanceof Uint8Array)a=o;else if(typeof o=="string")a=new TextEncoder().encode(o);else throw new Error(t);return a}function n(o){return Array.prototype.map.call(o,function(a){return(a<16?"0":"")+a.toString(16)}).join("")}function r(o){return(4294967296+o).toString(16).substring(1)}function s(o,a,c){let l=`
14
+ ***************************************************************************** */var ni=function(t,e){return ni=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},ni(t,e)};function nd(t,e){ni(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ri=function(){return ri=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ri.apply(this,arguments)};function rd(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 s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]]);return n}function sd(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function id(t,e){return function(n,r){e(n,r,t)}}function od(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ad(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function cd(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ld(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function ud(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function si(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 Da(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function hd(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Da(arguments[e]));return t}function fd(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<n;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Qn(t){return this instanceof Qn?(this.v=t,this):new Qn(t)}function dd(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(d,g){i.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(i[0][3],d)}}function c(f){f.value instanceof Qn?Promise.resolve(f.value.v).then(l,u):h(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function pd(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:Qn(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function gd(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 si=="function"?si(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function yd(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function wd(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 md(t){return t&&t.__esModule?t:{default:t}}function bd(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function vd(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 Ed=Object.freeze({__proto__:null,get __assign(){return ri},__asyncDelegator:pd,__asyncGenerator:dd,__asyncValues:gd,__await:Qn,__awaiter:ad,__classPrivateFieldGet:bd,__classPrivateFieldSet:vd,__createBinding:ld,__decorate:sd,__exportStar:ud,__extends:nd,__generator:cd,__importDefault:md,__importStar:wd,__makeTemplateObject:yd,__metadata:od,__param:id,__read:Da,__rest:rd,__spread:hd,__spreadArrays:fd,__values:si}),jr=ba(Ed),ii={},er={},Aa;function xd(){if(Aa)return er;Aa=1,Object.defineProperty(er,"__esModule",{value:!0}),er.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return er.delay=t,er}var hn={},oi={},fn={},Ta;function _d(){return Ta||(Ta=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.ONE_THOUSAND=fn.ONE_HUNDRED=void 0,fn.ONE_HUNDRED=100,fn.ONE_THOUSAND=1e3),fn}var ai={},Oa;function Id(){return Oa||(Oa=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}(ai)),ai}var $a;function Ra(){return $a||($a=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=jr;e.__exportStar(_d(),t),e.__exportStar(Id(),t)}(oi)),oi}var Ba;function Sd(){if(Ba)return hn;Ba=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.fromMiliseconds=hn.toMiliseconds=void 0;const t=Ra();function e(r){return r*t.ONE_THOUSAND}hn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return hn.fromMiliseconds=n,hn}var Pa;function Dd(){return Pa||(Pa=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=jr;e.__exportStar(xd(),t),e.__exportStar(Sd(),t)}(ii)),ii}var Nn={},Ca;function Ad(){if(Ca)return Nn;Ca=1,Object.defineProperty(Nn,"__esModule",{value:!0}),Nn.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 s=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:s})}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 Nn.Watch=t,Nn.default=t,Nn}var ci={},tr={},Na;function Td(){if(Na)return tr;Na=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.IWatch=void 0;class t{}return tr.IWatch=t,tr}var Ua;function Od(){return Ua||(Ua=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),jr.__exportStar(Td(),t)}(ci)),ci}var ka;function $d(){return ka||(ka=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=jr;e.__exportStar(Dd(),t),e.__exportStar(Ad(),t),e.__exportStar(Od(),t),e.__exportStar(Ra(),t)}(ti)),ti}var F=$d();class dn{}let Rd=class extends dn{constructor(e){super()}};const La=F.FIVE_SECONDS,pn={pulse:"heartbeat_pulse"};class li extends Rd{constructor(e){super(e),this.events=new Je.EventEmitter,this.interval=La,this.interval=e?.interval||La}static async init(e){const n=new li(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(),F.toMiliseconds(this.interval))}pulse(){this.events.emit(pn.pulse)}}const Bd=/"(?:_|\\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*:/,Pd=/"(?: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*:/,Cd=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Nd(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Ud(t);return}return e}function Ud(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function zr(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(!Cd.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Bd.test(t)||Pd.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Nd)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function kd(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function pe(t,...e){try{return kd(t(...e))}catch(n){return Promise.reject(n)}}function Ld(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Fd(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Vr(t){if(Ld(t))return String(t);if(Fd(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Vr(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const ui="base64:";function Md(t){return typeof t=="string"?t:ui+zd(t)}function qd(t){return typeof t!="string"||!t.startsWith(ui)?t:jd(t.slice(ui.length))}function jd(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function zd(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Re(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Vd(...t){return Re(t.join(":"))}function Kr(t){return t=Re(t),t?t+":":""}function Kd(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 Hd(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function ES(t){return t}const Wd="memory",Gd=()=>{const t=new Map;return{name:Wd,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 Yd(t={}){const e={mounts:{"":t.driver||Gd()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(l,u)=>{if(e.watching){u=Re(u);for(const h of e.watchListeners)h(l,u)}},i=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await Fa(e.mounts[l],s,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,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 l){const g=typeof d=="string",y=Re(g?d:d.key),b=g?void 0:d.value,A=g||!d.options?u:{...u,...d.options},w=n(y);p(w).items.push({key:y,value:b,relativeKey:w.relativeKey,options:A})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return pe(f.hasItem,h,u)},getItem(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return pe(f.getItem,h,u).then(p=>zr(p))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?pe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(p=>({key:Vd(h.base,p.key),value:zr(p.value)}))):Promise.all(h.items.map(f=>pe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:zr(p)})))))},getItemRaw(l,u={}){l=Re(l);const{relativeKey:h,driver:f}=n(l);return f.getItemRaw?pe(f.getItemRaw,h,u):pe(f.getItem,h,u).then(p=>qd(p))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Re(l);const{relativeKey:f,driver:p}=n(l);p.setItem&&(await pe(p.setItem,f,Vr(u),h),p.watch||s("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return pe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:Vr(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>pe(h.driver.setItem,f.relativeKey,Vr(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Re(l);const{relativeKey:f,driver:p}=n(l);if(p.setItemRaw)await pe(p.setItemRaw,f,u,h);else if(p.setItem)await pe(p.setItem,f,Md(u),h);else return;p.watch||s("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Re(l);const{relativeKey:h,driver:f}=n(l);f.removeItem&&(await pe(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await pe(f.removeItem,h+"$",u),f.watch||s("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Re(l);const{relativeKey:h,driver:f}=n(l),p=Object.create(null);if(f.getMeta&&Object.assign(p,await pe(f.getMeta,h,u)),!u.nativeOnly){const d=await pe(f.getItem,h+"$",u).then(g=>zr(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(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){l=Kr(l);const h=r(l,!0);let f=[];const p=[];let d=!0;for(const y of h){y.driver.flags?.maxDepth||(d=!1);const b=await pe(y.driver.getKeys,y.relativeBase,u);for(const A of b){const w=y.mountpoint+Re(A);f.some(m=>w.startsWith(m))||p.push(w)}f=[y.mountpoint,...f.filter(A=>!A.startsWith(y.mountpoint))]}const g=u.maxDepth!==void 0&&!d;return p.filter(y=>(!g||Kd(y,u.maxDepth))&&Hd(y,l))},async clear(l,u={}){l=Kr(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return pe(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(p=>h.driver.removeItem(p,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>Ma(l)))},async watch(l){return await i(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=Kr(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(Fa(u,s,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){l=Kr(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&(e.unwatch[l]?.(),delete e.unwatch[l]),u&&await Ma(e.mounts[l]),e.mountpoints=e.mountpoints.filter(h=>h!==l),delete e.mounts[l])},getMount(l=""){l=Re(l)+":";const u=n(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Re(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function Fa(t,e,n){return t.watch?t.watch((r,s)=>e(r,n+s)):()=>{}}async function Ma(t){typeof t.dispose=="function"&&await pe(t.dispose)}function gn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function qa(t,e){let n;const r=()=>{if(n)return n;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),n=gn(s),n.then(i=>{i.onclose=()=>n=void 0},()=>{}),n};return(s,i)=>r().then(o=>i(o.transaction(e,s).objectStore(e)))}let hi;function nr(){return hi||(hi=qa("keyval-store","keyval")),hi}function ja(t,e=nr()){return e("readonly",n=>gn(n.get(t)))}function Zd(t,e,n=nr()){return n("readwrite",r=>(r.put(e,t),gn(r.transaction)))}function Xd(t,e=nr()){return e("readwrite",n=>(n.delete(t),gn(n.transaction)))}function Jd(t=nr()){return t("readwrite",e=>(e.clear(),gn(e.transaction)))}function Qd(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},gn(t.transaction)}function ep(t=nr()){return t("readonly",e=>{if(e.getAllKeys)return gn(e.getAllKeys());const n=[];return Qd(e,r=>n.push(r.key)).then(()=>n)})}const tp=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),np=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,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Un(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return np(t)}catch{return t}}function rr(t){return typeof t=="string"?t:tp(t)||""}const rp="idb-keyval";var sp=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=s=>e+s;let r;return t.dbName&&t.storeName&&(r=qa(t.dbName,t.storeName)),{name:rp,options:t,async hasItem(s){return!(typeof await ja(n(s),r)>"u")},async getItem(s){return await ja(n(s),r)??null},setItem(s,i){return Zd(n(s),i,r)},removeItem(s){return Xd(n(s),r)},getKeys(){return ep(r)},clear(){return Jd(r)}}};const ip="WALLET_CONNECT_V2_INDEXED_DB",op="keyvaluestorage";let ap=class{constructor(){this.indexedDb=Yd({driver:sp({dbName:ip,storeName:op})})}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,rr(n))}async removeItem(e){await this.indexedDb.removeItem(e)}};var fi=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Hr={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 fi<"u"&&fi.localStorage?Hr.exports=fi.localStorage:typeof window<"u"&&window.localStorage?Hr.exports=window.localStorage:Hr.exports=new e})();function cp(t){var e;return[t[0],Un((e=t[1])!=null?e:"")]}let lp=class{constructor(){this.localStorage=Hr.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(cp)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return Un(n)}async setItem(e,n){this.localStorage.setItem(e,rr(n))}async removeItem(e){this.localStorage.removeItem(e)}};const up="wc_storage_version",za=1,hp=async(t,e,n)=>{const r=up,s=await e.getItem(r);if(s&&s>=za){n(e);return}const i=await t.getKeys();if(!i.length){n(e);return}const o=[];for(;i.length;){const a=i.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,za),n(e),fp(t,o)},fp=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};let dp=class{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new lp;this.storage=e;try{const n=new ap;hp(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)})}};var ut={exports:{}};function pp(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var gp=yp;function yp(t,e,n){var r=n&&n.stringify||pp,s=1;if(typeof t=="object"&&t!==null){var i=e.length+s;if(i===1)return t;var o=new Array(i);o[0]=r(t);for(var a=1;a<i;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 l="",u=1-s,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(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Number(e[u]),h=p+2,p++;break;case 105:if(u>=c||e[u]==null)break;h<p&&(l+=t.slice(h,p)),l+=Math.floor(Number(e[u])),h=p+2,p++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;h<p&&(l+=t.slice(h,p));var d=typeof e[u];if(d==="string"){l+="'"+e[u]+"'",h=p+2,p++;break}if(d==="function"){l+=e[u].name||"<anonymous>",h=p+2,p++;break}l+=r(e[u]),h=p+2,p++;break;case 115:if(u>=c)break;h<p&&(l+=t.slice(h,p)),l+=String(e[u]),h=p+2,p++;break;case 37:h<p&&(l+=t.slice(h,p)),l+="%",h=p+2,p++,u--;break}++u}++p}return h===-1?t:(h<f&&(l+=t.slice(h)),l)}const Va=gp;ut.exports=bt;const sr=Rp().console||{},wp={mapHttpRequest:Wr,mapHttpResponse:Wr,wrapRequestSerializer:wi,wrapResponseSerializer:wi,wrapErrorSerializer:wi,req:Wr,res:Wr,err:Ha,errWithCause:Ha};function Mt(t,e){return t==="silent"?1/0:e.levels.values[t]}const di=Symbol("pino.logFuncs"),pi=Symbol("pino.hierarchy"),mp={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Ka(t,e){const n={logger:e,parent:t[pi]};e[pi]=n}function bp(t,e,n){const r={};e.forEach(s=>{r[s]=n[s]?n[s]:sr[s]||sr[mp[s]||"log"]||kn}),t[di]=r}function vp(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function bt(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||sr;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},s=vp(t.browser.serialize,r);let i=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(i=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(n);l.log||(l.log=kn),bp(l,a,n),Ka({},l),Object.defineProperty(l,"levelVal",{get:h}),Object.defineProperty(l,"level",{get:f,set:p});const u={transmit:e,serialize:s,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:Tp(t),messageKey:t.messageKey||"msg",onChild:t.onChild||kn};l.levels=Ep(t),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=kn,l.serializers=r,l._serialize=s,l._stdErrSerialize=i,l.child=function(...g){return d.call(this,u,...g)},e&&(l._logEvent=yi());function h(){return Mt(this.level,this)}function f(){return this._level}function p(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,yn(this,u,l,"error"),yn(this,u,l,"fatal"),yn(this,u,l,"warn"),yn(this,u,l,"info"),yn(this,u,l,"debug"),yn(this,u,l,"trace"),o.forEach(y=>{yn(this,u,l,y)})}function d(g,y,b){if(!y)throw new Error("missing bindings for child Pino");b=b||{},s&&y.serializers&&(b.serializers=y.serializers);const A=b.serializers;if(s&&A){var w=Object.assign({},r,A),m=t.browser.serialize===!0?Object.keys(w):s;delete y.serializers,gi([y],m,w,this._stdErrSerialize)}function x(T){this._childLevel=(T._childLevel|0)+1,this.bindings=y,w&&(this.serializers=w,this._serialize=m),e&&(this._logEvent=yi([].concat(T._logEvent.bindings,y)))}x.prototype=this;const _=new x(this);return Ka(this,_),_.child=function(...T){return d.call(this,g,...T)},_.level=b.level||this.level,g.onChild(_),_}return l}function Ep(t){const e=t.customLevels||{},n=Object.assign({},bt.levels.values,e),r=Object.assign({},bt.levels.labels,xp(e));return{values:n,labels:r}}function xp(t){const e={};return Object.keys(t).forEach(function(n){e[t[n]]=n}),e}bt.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"}},bt.stdSerializers=wp,bt.stdTimeFunctions=Object.assign({},{nullTime:Wa,epochTime:Ga,unixTime:Op,isoTime:$p});function _p(t){const e=[];t.bindings&&e.push(t.bindings);let n=t[pi];for(;n.parent;)n=n.parent,n.logger.bindings&&e.push(n.logger.bindings);return e.reverse()}function yn(t,e,n,r){if(Object.defineProperty(t,r,{value:Mt(t.level,n)>Mt(r,n)?kn:n[di][r],writable:!0,enumerable:!0,configurable:!0}),t[r]===kn){if(!e.transmit)return;const i=e.transmit.level||t.level,o=Mt(i,n);if(Mt(r,n)<o)return}t[r]=Sp(t,e,n,r);const s=_p(t);s.length!==0&&(t[r]=Ip(s,t[r]))}function Ip(t,e){return function(){return e.apply(this,[...t,...arguments])}}function Sp(t,e,n,r){return function(s){return function(){const i=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===sr?sr:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(e.serialize&&(gi(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?s.call(a,...Dp(this,r,o,i,e)):s.apply(a,o),e.transmit){const u=e.transmit.level||t._level,h=Mt(u,n),f=Mt(r,n);if(f<h)return;Ap(this,{ts:i,methodLevel:r,methodValue:f,transmitValue:n.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Mt(t._level,n)},o,l)}}}(t[di][r])}function Dp(t,e,n,r,s){const{level:i,log:o=h=>h}=s.formatters||{},a=n.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),i){const h=i(e,t.levels.values[e]);Object.assign(l,h)}else l.level=t.levels.values[e];if(s.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?Va(a.shift(),a):void 0}else typeof c=="string"&&(c=Va(a.shift(),a));return c!==void 0&&(l[s.messageKey]=c),[o(l)]}}function gi(t,e,n,r){for(const s in t)if(r&&t[s]instanceof Error)t[s]=bt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s])&&e)for(const i in t[s])e.indexOf(i)>-1&&i in n&&(t[s][i]=n[i](t[s][i]))}function Ap(t,e,n,r=!1){const s=e.send,i=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;r||gi(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 l.indexOf(u)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,s(o,t._logEvent,c),t._logEvent=yi(l)}function yi(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Ha(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 Tp(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Wa:Ga}function Wr(){return{}}function wi(t){return t}function kn(){}function Wa(){return!1}function Ga(){return Date.now()}function Op(){return Math.round(Date.now()/1e3)}function $p(){return new Date(Date.now()).toISOString()}function Rp(){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)||{}}}ut.exports.default=bt;var Bp=ut.exports.pino=bt;const Pp={level:"info"},Gr="custom_context",mi=1e3*1024;var Cp=Object.defineProperty,Np=(t,e,n)=>e in t?Cp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qt=(t,e,n)=>Np(t,typeof e!="symbol"?e+"":e,n);let Up=class{constructor(e){qt(this,"nodeValue"),qt(this,"sizeInBytes"),qt(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}},Ya=class{constructor(e){qt(this,"lengthInNodes"),qt(this,"sizeInBytes"),qt(this,"head"),qt(this,"tail"),qt(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new Up(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}}}}};const kp=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n);function Za(t){return typeof t=="string"?t:kp(t)||""}var Lp=Object.defineProperty,Fp=(t,e,n)=>e in t?Lp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yr=(t,e,n)=>Fp(t,typeof e!="symbol"?e+"":e,n);let Xa=class{constructor(e,n=mi){Yr(this,"logs"),Yr(this,"level"),Yr(this,"levelValue"),Yr(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=ut.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Ya(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===ut.exports.levels.values.error?console.error(e):n===ut.exports.levels.values.warn?console.warn(e):n===ut.exports.levels.values.debug?console.debug(e):n===ut.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Za({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 Ya(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Za({extraMetadata:e})),new Blob(n,{type:"application/json"})}};var Mp=Object.defineProperty,qp=(t,e,n)=>e in t?Mp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jp=(t,e,n)=>qp(t,e+"",n);let zp=class{constructor(e,n=mi){jp(this,"baseChunkLogger"),this.baseChunkLogger=new Xa(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)}};var Vp=Object.defineProperty,Kp=(t,e,n)=>e in t?Vp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hp=(t,e,n)=>Kp(t,e+"",n);let Wp=class{constructor(e,n=mi){Hp(this,"baseChunkLogger"),this.baseChunkLogger=new Xa(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 Gp=Object.defineProperty,Yp=Object.defineProperties,Zp=Object.getOwnPropertyDescriptors,Ja=Object.getOwnPropertySymbols,Xp=Object.prototype.hasOwnProperty,Jp=Object.prototype.propertyIsEnumerable,Qa=(t,e,n)=>e in t?Gp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jt=(t,e)=>{for(var n in e||(e={}))Xp.call(e,n)&&Qa(t,n,e[n]);if(Ja)for(var n of Ja(e))Jp.call(e,n)&&Qa(t,n,e[n]);return t},zt=(t,e)=>Yp(t,Zp(e));function Qp(t){return zt(jt({},t),{level:t?.level||Pp.level})}function eg(t,e,n=Gr){return t[n]=e,t}function Be(t,e=Gr){return t[e]||""}function tg(t,e,n=Gr){const r=Be(t,n);return r.trim()?`${r}/${e}`:e}function Fe(t,e,n=Gr){const r=tg(t,e,n),s=t.child({context:r});return eg(s,r,n)}function ng(t){var e,n;const r=new zp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ut.exports(zt(jt({},t.opts),{level:"trace",browser:zt(jt({},(n=t.opts)==null?void 0:n.browser),{write:s=>r.write(s)})})),chunkLoggerController:r}}function rg(t){var e,n;const r=new Wp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:ut.exports(zt(jt({},t.opts),{level:"trace",browser:zt(jt({},(n=t.opts)==null?void 0:n.browser),{write:s=>r.write(s)})}),r),chunkLoggerController:r}}function ec(t){var e;if(typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string")return{logger:t.loggerOverride,chunkLoggerController:null};const n=zt(jt({},t.opts),{level:typeof t.loggerOverride=="string"?t.loggerOverride:(e=t.opts)==null?void 0:e.level});return typeof window<"u"?ng(zt(jt({},t),{opts:n})):rg(zt(jt({},t),{opts:n}))}class sg extends dn{constructor(e){super(),this.opts=e,this.protocol="wc",this.version=2}}class ig extends dn{constructor(e,n){super(),this.core=e,this.logger=n,this.records=new Map}}let og=class{constructor(e,n){this.logger=e,this.core=n}},ag=class extends dn{constructor(e,n){super(),this.relayer=e,this.logger=n}};class cg extends dn{constructor(e){super()}}let lg=class{constructor(e,n,r,s){this.core=e,this.logger=n,this.name=r}},ug=class extends dn{constructor(e,n){super(),this.relayer=e,this.logger=n}},hg=class extends dn{constructor(e,n){super(),this.core=e,this.logger=n}},fg=class{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}},dg=class{constructor(e,n){this.projectId=e,this.logger=n}},pg=class{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}},gg=class{constructor(e){this.opts=e,this.protocol="wc",this.version=2}},yg=class{constructor(e){this.client=e}};function wg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tc(t,...e){if(!wg(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function nc(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function mg(t,e){tc(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const Ln=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const bi=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function bg(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function rc(t){return typeof t=="string"&&(t=bg(t)),tc(t),t}let vg=class{clone(){return this._cloneInto()}};function Eg(t){const e=r=>t().update(rc(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function sc(t=32){if(Ln&&typeof Ln.getRandomValues=="function")return Ln.getRandomValues(new Uint8Array(t));if(Ln&&typeof Ln.randomBytes=="function")return Ln.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function xg(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}class _g extends vg{constructor(e,n,r,s){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=bi(this.buffer)}update(e){nc(this);const{view:n,buffer:r,blockLen:s}=this;e=rc(e);const i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=bi(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nc(this),mg(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:i}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(r,0),o=0);for(let h=o;h<s;h++)n[h]=0;xg(r,s-8,BigInt(this.length*8),i),this.process(r,0);const a=bi(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}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:s,finished:i,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=i,e.destroyed=o,s%n&&e.buffer.set(r),e}}const Zr=BigInt(2**32-1),vi=BigInt(32);function ic(t,e=!1){return e?{h:Number(t&Zr),l:Number(t>>vi&Zr)}:{h:Number(t>>vi&Zr)|0,l:Number(t&Zr)|0}}function Ig(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:i,l:o}=ic(t[s],e);[n[s],r[s]]=[i,o]}return[n,r]}const Sg=(t,e)=>BigInt(t>>>0)<<vi|BigInt(e>>>0),Dg=(t,e,n)=>t>>>n,Ag=(t,e,n)=>t<<32-n|e>>>n,Tg=(t,e,n)=>t>>>n|e<<32-n,Og=(t,e,n)=>t<<32-n|e>>>n,$g=(t,e,n)=>t<<64-n|e>>>n-32,Rg=(t,e,n)=>t>>>n-32|e<<64-n,Bg=(t,e)=>e,Pg=(t,e)=>t,Cg=(t,e,n)=>t<<n|e>>>32-n,Ng=(t,e,n)=>e<<n|t>>>32-n,Ug=(t,e,n)=>e<<n-32|t>>>64-n,kg=(t,e,n)=>t<<n-32|e>>>64-n;function Lg(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const Fg=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Mg=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,qg=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),jg=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,zg=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Vg=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Y={fromBig:ic,split:Ig,toBig:Sg,shrSH:Dg,shrSL:Ag,rotrSH:Tg,rotrSL:Og,rotrBH:$g,rotrBL:Rg,rotr32H:Bg,rotr32L:Pg,rotlSH:Cg,rotlSL:Ng,rotlBH:Ug,rotlBL:kg,add:Lg,add3L:Fg,add3H:Mg,add4L:qg,add4H:jg,add5H:Vg,add5L:zg},[Kg,Hg]=Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),Vt=new Uint32Array(80),Kt=new Uint32Array(80);let Wg=class extends _g{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:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|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 w=0;w<16;w++,n+=4)Vt[w]=e.getUint32(n),Kt[w]=e.getUint32(n+=4);for(let w=16;w<80;w++){const m=Vt[w-15]|0,x=Kt[w-15]|0,_=Y.rotrSH(m,x,1)^Y.rotrSH(m,x,8)^Y.shrSH(m,x,7),T=Y.rotrSL(m,x,1)^Y.rotrSL(m,x,8)^Y.shrSL(m,x,7),$=Vt[w-2]|0,P=Kt[w-2]|0,k=Y.rotrSH($,P,19)^Y.rotrBH($,P,61)^Y.shrSH($,P,6),U=Y.rotrSL($,P,19)^Y.rotrBL($,P,61)^Y.shrSL($,P,6),N=Y.add4L(T,U,Kt[w-7],Kt[w-16]),S=Y.add4H(N,_,k,Vt[w-7],Vt[w-16]);Vt[w]=S|0,Kt[w]=N|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:b,Hl:A}=this;for(let w=0;w<80;w++){const m=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),_=h&p^~h&g,T=f&d^~f&y,$=Y.add5L(A,x,T,Hg[w],Kt[w]),P=Y.add5H($,b,m,_,Kg[w],Vt[w]),k=$|0,U=Y.rotrSH(r,s,28)^Y.rotrBH(r,s,34)^Y.rotrBH(r,s,39),N=Y.rotrSL(r,s,28)^Y.rotrBL(r,s,34)^Y.rotrBL(r,s,39),S=r&i^r&a^i&a,R=s&o^s&c^o&c;b=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(l|0,u|0,P|0,k|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const v=Y.add3L(k,N,R);r=Y.add3H(v,P,U,S),s=v|0}({h:r,l:s}=Y.add(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=Y.add(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Y.add(this.Dh|0,this.Dl|0,l|0,u|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:b,l:A}=Y.add(this.Hh|0,this.Hl|0,b|0,A|0),this.set(r,s,i,o,a,c,l,u,h,f,p,d,g,y,b,A)}roundClean(){Vt.fill(0),Kt.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 Gg=Eg(()=>new Wg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ei=BigInt(0),oc=BigInt(1),Yg=BigInt(2);function xi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _i(t){if(!xi(t))throw new Error("Uint8Array expected")}function Ii(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Zg=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Si(t){_i(t);let e="";for(let n=0;n<t.length;n++)e+=Zg[t[n]];return e}function ac(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ei:BigInt("0x"+t)}const vt={_0:48,_9:57,A:65,F:70,a:97,f:102};function cc(t){if(t>=vt._0&&t<=vt._9)return t-vt._0;if(t>=vt.A&&t<=vt.F)return t-(vt.A-10);if(t>=vt.a&&t<=vt.f)return t-(vt.a-10)}function lc(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 s=0,i=0;s<n;s++,i+=2){const o=cc(t.charCodeAt(i)),a=cc(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function Xg(t){return ac(Si(t))}function Xr(t){return _i(t),ac(Si(Uint8Array.from(t).reverse()))}function uc(t,e){return lc(t.toString(16).padStart(e*2,"0"))}function Di(t,e){return uc(t,e).reverse()}function Et(t,e,n){let r;if(typeof e=="string")try{r=lc(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(xi(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function hc(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];_i(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}const Ai=t=>typeof t=="bigint"&&Ei<=t;function Jg(t,e,n){return Ai(t)&&Ai(e)&&Ai(n)&&e<=t&&t<n}function ir(t,e,n,r){if(!Jg(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Qg(t){let e;for(e=0;t>Ei;t>>=oc,e+=1);return e}const ey=t=>(Yg<<BigInt(t-1))-oc,ty={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"||xi(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 Ti(t,e,n={}){const r=(s,i,o)=>{const a=ty[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function fc(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}const ge=BigInt(0),re=BigInt(1),wn=BigInt(2),ny=BigInt(3),Oi=BigInt(4),dc=BigInt(5),pc=BigInt(8);function le(t,e){const n=t%e;return n>=ge?n:e+n}function ry(t,e,n){if(e<ge)throw new Error("invalid exponent, negatives unsupported");if(n<=ge)throw new Error("invalid modulus");if(n===re)return ge;let r=re;for(;e>ge;)e&re&&(r=r*t%n),t=t*t%n,e>>=re;return r}function ht(t,e,n){let r=t;for(;e-- >ge;)r*=r,r%=n;return r}function gc(t,e){if(t===ge)throw new Error("invert: expected non-zero number");if(e<=ge)throw new Error("invert: expected positive modulus, got "+e);let n=le(t,e),r=e,s=ge,i=re;for(;n!==ge;){const o=r/n,a=r%n,c=s-i*o;r=n,n=a,s=i,i=c}if(r!==re)throw new Error("invert: does not exist");return le(s,e)}function sy(t){const e=(t-re)/wn;let n,r,s;for(n=t-re,r=0;n%wn===ge;n/=wn,r++);for(s=wn;s<t&&ry(s,e,t)!==t-re;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+re)/Oi;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const i=(n+re)/wn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,s),n),u=o.pow(a,i),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(l,re<<BigInt(c-f-1));l=o.sqr(p),u=o.mul(u,p),h=o.mul(h,l),c=f}return u}}function iy(t){if(t%Oi===ny){const e=(t+re)/Oi;return function(n,r){const s=n.pow(r,e);if(!n.eql(n.sqr(s),r))throw new Error("Cannot find square root");return s}}if(t%pc===dc){const e=(t-dc)/pc;return function(n,r){const s=n.mul(r,wn),i=n.pow(s,e),o=n.mul(r,i),a=n.mul(n.mul(o,wn),i),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 sy(t)}const oy=(t,e)=>(le(t,e)&re)===re,ay=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function cy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=ay.reduce((r,s)=>(r[s]="function",r),e);return Ti(t,n)}function ly(t,e,n){if(n<ge)throw new Error("invalid exponent, negatives unsupported");if(n===ge)return t.ONE;if(n===re)return e;let r=t.ONE,s=e;for(;n>ge;)n&re&&(r=t.mul(r,s)),s=t.sqr(s),n>>=re;return r}function uy(t,e){const n=new Array(e.length),r=e.reduce((i,o,a)=>t.is0(o)?i:(n[a]=i,t.mul(i,o)),t.ONE),s=t.inv(r);return e.reduceRight((i,o,a)=>t.is0(o)?i:(n[a]=t.mul(i,n[a]),t.mul(i,o)),s),n}function yc(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function wc(t,e,n=!1,r={}){if(t<=ge)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=yc(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:ey(s),ZERO:ge,ONE:re,create:c=>le(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return ge<=c&&c<t},is0:c=>c===ge,isOdd:c=>(c&re)===re,neg:c=>le(-c,t),eql:(c,l)=>c===l,sqr:c=>le(c*c,t),add:(c,l)=>le(c+l,t),sub:(c,l)=>le(c-l,t),mul:(c,l)=>le(c*l,t),pow:(c,l)=>ly(a,c,l),div:(c,l)=>le(c*gc(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>gc(c,t),sqrt:r.sqrt||(c=>(o||(o=iy(t)),o(a,c))),invertBatch:c=>uy(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>n?Di(c,i):uc(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?Xr(c):Xg(c)}});return Object.freeze(a)}const mc=BigInt(0),Jr=BigInt(1);function $i(t,e){const n=e.negate();return t?n:e}function bc(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ri(t,e){bc(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function hy(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 fy(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 Bi=new WeakMap,vc=new WeakMap;function Pi(t){return vc.get(t)||1}function dy(t,e){return{constTimeNegate:$i,hasPrecomputes(n){return Pi(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>mc;)r&Jr&&(s=s.add(i)),i=i.double(),r>>=Jr;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=Ri(r,e),o=[];let a=n,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<i;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,s){const{windows:i,windowSize:o}=Ri(n,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**n-1),u=2**n,h=BigInt(n);for(let f=0;f<i;f++){const p=f*o;let d=Number(s&l);s>>=h,d>o&&(d-=u,s+=Jr);const g=p,y=p+Math.abs(d)-1,b=f%2!==0,A=d<0;d===0?c=c.add($i(b,r[g])):a=a.add($i(A,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,s,i=t.ZERO){const{windows:o,windowSize:a}=Ri(n,e),c=BigInt(2**n-1),l=2**n,u=BigInt(n);for(let h=0;h<o;h++){const f=h*a;if(s===mc)break;let p=Number(s&c);if(s>>=u,p>a&&(p-=l,s+=Jr),p===0)continue;let d=r[f+Math.abs(p)-1];p<0&&(d=d.negate()),i=i.add(d)}return i},getPrecomputes(n,r,s){let i=Bi.get(r);return i||(i=this.precomputeWindow(r,n),n!==1&&Bi.set(r,s(i))),i},wNAFCached(n,r,s){const i=Pi(n);return this.wNAF(i,this.getPrecomputes(i,n,s),r)},wNAFCachedUnsafe(n,r,s,i){const o=Pi(n);return o===1?this.unsafeLadder(n,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,n,s),r,i)},setWindowSize(n,r){bc(r,e),vc.set(n,r),Bi.delete(n)}}}function py(t,e,n,r){if(hy(n,t),fy(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,i=Qg(BigInt(n.length)),o=i>12?i-3:i>4?i-2:i?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),l=Math.floor((e.BITS-1)/o)*o;let u=s;for(let h=l;h>=0;h-=o){c.fill(s);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=s;for(let p=c.length-1,d=s;p>0;p--)d=d.add(c[p]),f=f.add(d);if(u=u.add(f),h!==0)for(let p=0;p<o;p++)u=u.double()}return u}function gy(t){return cy(t.Fp),Ti(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yc(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Qe=BigInt(0),Pe=BigInt(1),Qr=BigInt(2),yy=BigInt(8),wy={zip215:!0};function my(t){const e=gy(t);return Ti(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function by(t){const e=my(t),{Fp:n,n:r,prehash:s,hash:i,randomBytes:o,nByteLength:a,h:c}=e,l=Qr<<BigInt(a*8)-Pe,u=n.create,h=wc(e.n,e.nBitLength),f=e.uvRatio||((v,E)=>{try{return{isValid:!0,value:n.sqrt(v*n.inv(E))}}catch{return{isValid:!1,value:Qe}}}),p=e.adjustScalarBytes||(v=>v),d=e.domain||((v,E,D)=>{if(Ii("phflag",D),E.length||D)throw new Error("Contexts/pre-hash are not supported");return v});function g(v,E){ir("coordinate "+v,E,Qe,l)}function y(v){if(!(v instanceof w))throw new Error("ExtendedPoint expected")}const b=fc((v,E)=>{const{ex:D,ey:B,ez:I}=v,O=v.is0();E==null&&(E=O?yy:n.inv(I));const C=u(D*E),L=u(B*E),V=u(I*E);if(O)return{x:Qe,y:Pe};if(V!==Pe)throw new Error("invZ was invalid");return{x:C,y:L}}),A=fc(v=>{const{a:E,d:D}=e;if(v.is0())throw new Error("bad point: ZERO");const{ex:B,ey:I,ez:O,et:C}=v,L=u(B*B),V=u(I*I),j=u(O*O),q=u(j*j),K=u(L*E),W=u(j*u(K+V)),G=u(q+u(D*u(L*V)));if(W!==G)throw new Error("bad point: equation left != right (1)");const H=u(B*I),Z=u(O*C);if(H!==Z)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(E,D,B,I){this.ex=E,this.ey=D,this.ez=B,this.et=I,g("x",E),g("y",D),g("z",B),g("t",I),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(E){if(E instanceof w)throw new Error("extended point not allowed");const{x:D,y:B}=E||{};return g("x",D),g("y",B),new w(D,B,Pe,u(D*B))}static normalizeZ(E){const D=n.invertBatch(E.map(B=>B.ez));return E.map((B,I)=>B.toAffine(D[I])).map(w.fromAffine)}static msm(E,D){return py(w,h,E,D)}_setWindowSize(E){_.setWindowSize(this,E)}assertValidity(){A(this)}equals(E){y(E);const{ex:D,ey:B,ez:I}=this,{ex:O,ey:C,ez:L}=E,V=u(D*L),j=u(O*I),q=u(B*L),K=u(C*I);return V===j&&q===K}is0(){return this.equals(w.ZERO)}negate(){return new w(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:E}=e,{ex:D,ey:B,ez:I}=this,O=u(D*D),C=u(B*B),L=u(Qr*u(I*I)),V=u(E*O),j=D+B,q=u(u(j*j)-O-C),K=V+C,W=K-L,G=V-C,H=u(q*W),Z=u(K*G),ae=u(q*G),ce=u(W*K);return new w(H,Z,ce,ae)}add(E){y(E);const{a:D,d:B}=e,{ex:I,ey:O,ez:C,et:L}=this,{ex:V,ey:j,ez:q,et:K}=E;if(D===BigInt(-1)){const jf=u((O-I)*(j+V)),zf=u((O+I)*(j-V)),ma=u(zf-jf);if(ma===Qe)return this.double();const Vf=u(C*Qr*K),Kf=u(L*Qr*q),Hf=Kf+Vf,Wf=zf+jf,Gf=Kf-Vf,wS=u(Hf*ma),mS=u(Wf*Gf),bS=u(Hf*Gf),vS=u(ma*Wf);return new w(wS,mS,vS,bS)}const W=u(I*V),G=u(O*j),H=u(L*B*K),Z=u(C*q),ae=u((I+O)*(V+j)-W-G),ce=Z-H,we=Z+H,at=u(G-D*W),ct=u(ae*ce),Ys=u(we*at),gS=u(ae*at),yS=u(ce*we);return new w(ct,Ys,yS,gS)}subtract(E){return this.add(E.negate())}wNAF(E){return _.wNAFCached(this,E,w.normalizeZ)}multiply(E){const D=E;ir("scalar",D,Pe,r);const{p:B,f:I}=this.wNAF(D);return w.normalizeZ([B,I])[0]}multiplyUnsafe(E,D=w.ZERO){const B=E;return ir("scalar",B,Qe,r),B===Qe?x:this.is0()||B===Pe?this:_.wNAFCachedUnsafe(this,B,w.normalizeZ,D)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return _.unsafeLadder(this,r).is0()}toAffine(E){return b(this,E)}clearCofactor(){const{h:E}=e;return E===Pe?this:this.multiplyUnsafe(E)}static fromHex(E,D=!1){const{d:B,a:I}=e,O=n.BYTES;E=Et("pointHex",E,O),Ii("zip215",D);const C=E.slice(),L=E[O-1];C[O-1]=L&-129;const V=Xr(C),j=D?l:n.ORDER;ir("pointHex.y",V,Qe,j);const q=u(V*V),K=u(q-Pe),W=u(B*q-I);let{isValid:G,value:H}=f(K,W);if(!G)throw new Error("Point.fromHex: invalid y coordinate");const Z=(H&Pe)===Pe,ae=(L&128)!==0;if(!D&&H===Qe&&ae)throw new Error("Point.fromHex: x=0 and x_0=1");return ae!==Z&&(H=u(-H)),w.fromAffine({x:H,y:V})}static fromPrivateKey(E){return P(E).point}toRawBytes(){const{x:E,y:D}=this.toAffine(),B=Di(D,n.BYTES);return B[B.length-1]|=E&Pe?128:0,B}toHex(){return Si(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Pe,u(e.Gx*e.Gy)),w.ZERO=new w(Qe,Pe,Pe,Qe);const{BASE:m,ZERO:x}=w,_=dy(w,a*8);function T(v){return le(v,r)}function $(v){return T(Xr(v))}function P(v){const E=n.BYTES;v=Et("private key",v,E);const D=Et("hashed private key",i(v),2*E),B=p(D.slice(0,E)),I=D.slice(E,2*E),O=$(B),C=m.multiply(O),L=C.toRawBytes();return{head:B,prefix:I,scalar:O,point:C,pointBytes:L}}function k(v){return P(v).pointBytes}function U(v=new Uint8Array,...E){const D=hc(...E);return $(i(d(D,Et("context",v),!!s)))}function N(v,E,D={}){v=Et("message",v),s&&(v=s(v));const{prefix:B,scalar:I,pointBytes:O}=P(E),C=U(D.context,B,v),L=m.multiply(C).toRawBytes(),V=U(D.context,L,O,v),j=T(C+V*I);ir("signature.s",j,Qe,r);const q=hc(L,Di(j,n.BYTES));return Et("result",q,n.BYTES*2)}const S=wy;function R(v,E,D,B=S){const{context:I,zip215:O}=B,C=n.BYTES;v=Et("signature",v,2*C),E=Et("message",E),D=Et("publicKey",D,C),O!==void 0&&Ii("zip215",O),s&&(E=s(E));const L=Xr(v.slice(C,2*C));let V,j,q;try{V=w.fromHex(D,O),j=w.fromHex(v.slice(0,C),O),q=m.multiplyUnsafe(L)}catch{return!1}if(!O&&V.isSmallOrder())return!1;const K=U(I,j.toRawBytes(),V.toRawBytes(),E);return j.add(V.multiplyUnsafe(K)).subtract(q).clearCofactor().equals(w.ZERO)}return m._setWindowSize(8),{CURVE:e,getPublicKey:k,sign:N,verify:R,ExtendedPoint:w,utils:{getExtendedPublicKey:P,randomPrivateKey:()=>o(n.BYTES),precompute(v=8,E=w.BASE){return E._setWindowSize(v),E.multiply(BigInt(3)),E}}}}BigInt(0),BigInt(1);const Ci=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ec=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const vy=BigInt(1),xc=BigInt(2);BigInt(3);const Ey=BigInt(5),xy=BigInt(8);function _y(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=Ci,o=t*t%i*t%i,a=ht(o,xc,i)*o%i,c=ht(a,vy,i)*t%i,l=ht(c,Ey,i)*c%i,u=ht(l,e,i)*l%i,h=ht(u,n,i)*u%i,f=ht(h,r,i)*h%i,p=ht(f,s,i)*f%i,d=ht(p,s,i)*f%i,g=ht(d,e,i)*l%i;return{pow_p_5_8:ht(g,xc,i)*t%i,b2:o}}function Iy(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Sy(t,e){const n=Ci,r=le(e*e*e,n),s=le(r*r*e,n),i=_y(t*s).pow_p_5_8;let o=le(t*r*i,n);const a=le(e*o*o,n),c=o,l=le(o*Ec,n),u=a===t,h=a===le(-t,n),f=a===le(-t*Ec,n);return u&&(o=c),(h||f)&&(o=l),oy(o,n)&&(o=le(-o,n)),{isValid:u||h,value:o}}const Dy=wc(Ci,void 0,!0),Ay={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Dy,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:xy,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Gg,randomBytes:sc,adjustScalarBytes:Iy,uvRatio:Sy},_c=by(Ay),Ty="EdDSA",Oy="JWT",es=".",ts="base64url",Ic="utf8",Sc="utf8",$y=":",Ry="did",By="key",Dc="base58btc",Py="z",Cy="K36",Ny=32;function Ni(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Ac(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ni(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Tc(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=Ac(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Ni(n)}function Uy(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 s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=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,b=0,A=d.length;b!==A&&d[b]===0;)b++,g++;for(var w=(A-b)*u+1>>>0,m=new Uint8Array(w);b!==A;){for(var x=d[b],_=0,T=w-1;(x!==0||_<y)&&T!==-1;T--,_++)x+=256*m[T]>>>0,m[T]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=_,b++}for(var $=w-y;$!==w&&m[$]===0;)$++;for(var P=c.repeat(g);$<w;++$)P+=t.charAt(m[$]);return P}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,b=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*l+1>>>0,w=new Uint8Array(A);d[g];){var m=n[d.charCodeAt(g)];if(m===255)return;for(var x=0,_=A-1;(m!==0||x<b)&&_!==-1;_--,x++)m+=a*w[_]>>>0,w[_]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");b=x,g++}if(d[g]!==" "){for(var T=A-b;T!==A&&w[T]===0;)T++;for(var $=new Uint8Array(y+(A-T)),P=y;T!==A;)$[P++]=w[T++];return $}}}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 ky=Uy,Ly=ky;const Oc=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")},Fy=t=>new TextEncoder().encode(t),My=t=>new TextDecoder().decode(t);let qy=class{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")}},jy=class{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 $c(this,e)}},zy=class{constructor(e){this.decoders=e}or(e){return $c(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 $c=(t,e)=>new zy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Vy=class{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new qy(e,n,r),this.decoder=new jy(e,n,s)}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 Vy(t,e,n,r),or=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=Ly(n,e);return ns({prefix:t,name:e,encode:r,decode:i=>Oc(s(i))})},Ky=(t,e,n,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Hy=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},me=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ns({prefix:e,name:t,encode(s){return Hy(s,r,n)},decode(s){return Ky(s,r,n,t)}}),Wy=ns({prefix:"\0",name:"identity",encode:t=>My(t),decode:t=>Fy(t)});var Gy=Object.freeze({__proto__:null,identity:Wy});const Yy=me({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Zy=Object.freeze({__proto__:null,base2:Yy});const Xy=me({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Jy=Object.freeze({__proto__:null,base8:Xy});const Qy=or({prefix:"9",name:"base10",alphabet:"0123456789"});var e0=Object.freeze({__proto__:null,base10:Qy});const t0=me({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),n0=me({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var r0=Object.freeze({__proto__:null,base16:t0,base16upper:n0});const s0=me({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),i0=me({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o0=me({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a0=me({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c0=me({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),l0=me({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),u0=me({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),h0=me({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),f0=me({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var d0=Object.freeze({__proto__:null,base32:s0,base32upper:i0,base32pad:o0,base32padupper:a0,base32hex:c0,base32hexupper:l0,base32hexpad:u0,base32hexpadupper:h0,base32z:f0});const p0=or({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),g0=or({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y0=Object.freeze({__proto__:null,base36:p0,base36upper:g0});const w0=or({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),m0=or({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var b0=Object.freeze({__proto__:null,base58btc:w0,base58flickr:m0});const v0=me({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),E0=me({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),x0=me({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_0=me({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var I0=Object.freeze({__proto__:null,base64:v0,base64pad:E0,base64url:x0,base64urlpad:_0});const Rc=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}"),S0=Rc.reduce((t,e,n)=>(t[n]=e,t),[]),D0=Rc.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function A0(t){return t.reduce((e,n)=>(e+=S0[n],e),"")}function T0(t){const e=[];for(const n of t){const r=D0[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const O0=ns({prefix:"\u{1F680}",name:"base256emoji",encode:A0,decode:T0});var $0=Object.freeze({__proto__:null,base256emoji:O0}),R0=Pc,Bc=128,B0=-128,P0=Math.pow(2,31);function Pc(t,e,n){e=e||[],n=n||0;for(var r=n;t>=P0;)e[n++]=t&255|Bc,t/=128;for(;t&B0;)e[n++]=t&255|Bc,t>>>=7;return e[n]=t|0,Pc.bytes=n-r+1,e}var C0=Ui,N0=128,Cc=127;function Ui(t,r){var n=0,r=r||0,s=0,i=r,o,a=t.length;do{if(i>=a)throw Ui.bytes=0,new RangeError("Could not decode varint");o=t[i++],n+=s<28?(o&Cc)<<s:(o&Cc)*Math.pow(2,s),s+=7}while(o>=N0);return Ui.bytes=i-r,n}var U0=Math.pow(2,7),k0=Math.pow(2,14),L0=Math.pow(2,21),F0=Math.pow(2,28),M0=Math.pow(2,35),q0=Math.pow(2,42),j0=Math.pow(2,49),z0=Math.pow(2,56),V0=Math.pow(2,63),K0=function(t){return t<U0?1:t<k0?2:t<L0?3:t<F0?4:t<M0?5:t<q0?6:t<j0?7:t<z0?8:t<V0?9:10},H0={encode:R0,decode:C0,encodingLength:K0},Nc=H0;const Uc=(t,e,n=0)=>(Nc.encode(t,e,n),e),kc=t=>Nc.encodingLength(t),ki=(t,e)=>{const n=e.byteLength,r=kc(t),s=r+kc(n),i=new Uint8Array(s+n);return Uc(t,i,0),Uc(n,i,r),i.set(e,s),new W0(t,n,e,i)};class W0{constructor(e,n,r,s){this.code=e,this.size=n,this.digest=r,this.bytes=s}}const Lc=({name:t,code:e,encode:n})=>new G0(t,e,n);class G0{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?ki(this.code,n):n.then(r=>ki(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Fc=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Y0=Lc({name:"sha2-256",code:18,encode:Fc("SHA-256")}),Z0=Lc({name:"sha2-512",code:19,encode:Fc("SHA-512")});var X0=Object.freeze({__proto__:null,sha256:Y0,sha512:Z0});const Mc=0,J0="identity",qc=Oc;var Q0=Object.freeze({__proto__:null,identity:{code:Mc,name:J0,encode:qc,digest:t=>ki(Mc,qc(t))}});const jc={...Gy,...Zy,...Jy,...e0,...r0,...d0,...y0,...b0,...I0,...$0};({...X0,...Q0});function zc(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Vc=zc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Li=zc("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=Ac(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Kc={utf8:Vc,"utf-8":Vc,hex:jc.base16,latin1:Li,ascii:Li,binary:Li,...jc};function rs(t,e="utf8"){const n=Kc[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 Fn(t,e="utf8"){const n=Kc[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ni(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Hc(t){return Un(rs(Fn(t,ts),Ic))}function ss(t){return rs(Fn(rr(t),Ic),ts)}function Wc(t){const e=Fn(Cy,Dc),n=Py+rs(Tc([e,t]),Dc);return[Ry,By,n].join($y)}function ew(t){return rs(t,ts)}function tw(t){return Fn(t,ts)}function nw(t){return Fn([ss(t.header),ss(t.payload)].join(es),Sc)}function rw(t){return[ss(t.header),ss(t.payload),ew(t.signature)].join(es)}function Fi(t){const e=t.split(es),n=Hc(e[0]),r=Hc(e[1]),s=tw(e[2]),i=Fn(e.slice(0,2).join(es),Sc);return{header:n,payload:r,signature:s,data:i}}function Gc(t=sc(Ny)){const e=_c.getPublicKey(t);return{secretKey:Tc([t,e]),publicKey:e}}async function sw(t,e,n,r,s=F.fromMiliseconds(Date.now())){const i={alg:Ty,typ:Oy},o=Wc(r.publicKey),a=s+n,c={iss:o,sub:t,aud:e,iat:s,exp:a},l=nw({header:i,payload:c}),u=_c.sign(l,r.secretKey.slice(0,32));return rw({header:i,payload:c,signature:u})}function iw(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 s=0;s<t.length;s++){var i=t.charAt(s),o=i.charCodeAt(0);if(n[o]!==255)throw new TypeError(i+" is ambiguous");n[o]=s}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=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,b=0,A=d.length;b!==A&&d[b]===0;)b++,g++;for(var w=(A-b)*u+1>>>0,m=new Uint8Array(w);b!==A;){for(var x=d[b],_=0,T=w-1;(x!==0||_<y)&&T!==-1;T--,_++)x+=256*m[T]>>>0,m[T]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=_,b++}for(var $=w-y;$!==w&&m[$]===0;)$++;for(var P=c.repeat(g);$<w;++$)P+=t.charAt(m[$]);return P}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,b=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*l+1>>>0,w=new Uint8Array(A);d[g];){var m=n[d.charCodeAt(g)];if(m===255)return;for(var x=0,_=A-1;(m!==0||x<b)&&_!==-1;_--,x++)m+=a*w[_]>>>0,w[_]=m%256>>>0,m=m/256>>>0;if(m!==0)throw new Error("Non-zero carry");b=x,g++}if(d[g]!==" "){for(var T=A-b;T!==A&&w[T]===0;)T++;for(var $=new Uint8Array(y+(A-T)),P=y;T!==A;)$[P++]=w[T++];return $}}}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 ow=iw,aw=ow;const cw=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")},lw=t=>new TextEncoder().encode(t),uw=t=>new TextDecoder().decode(t);let hw=class{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")}},fw=class{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 Yc(this,e)}};class dw{constructor(e){this.decoders=e}or(e){return Yc(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 Yc=(t,e)=>new dw({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class pw{constructor(e,n,r,s){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=s,this.encoder=new hw(e,n,r),this.decoder=new fw(e,n,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const is=({name:t,prefix:e,encode:n,decode:r})=>new pw(t,e,n,r),ar=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:s}=aw(n,e);return is({prefix:t,name:e,encode:r,decode:i=>cw(s(i))})},gw=(t,e,n,r)=>{const s={};for(let u=0;u<e.length;++u)s[e[u]]=u;let i=t.length;for(;t[i-1]==="=";)--i;const o=new Uint8Array(i*n/8|0);let a=0,c=0,l=0;for(let u=0;u<i;++u){const h=s[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},yw=(t,e,n)=>{const r=e[e.length-1]==="=",s=(1<<n)-1;let i="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,i+=e[s&a>>o];if(o&&(i+=e[s&a<<n-o]),r)for(;i.length*n&7;)i+="=";return i},be=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>is({prefix:e,name:t,encode(s){return yw(s,r,n)},decode(s){return gw(s,r,n,t)}}),ww=is({prefix:"\0",name:"identity",encode:t=>uw(t),decode:t=>lw(t)});var mw=Object.freeze({__proto__:null,identity:ww});const bw=be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var vw=Object.freeze({__proto__:null,base2:bw});const Ew=be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var xw=Object.freeze({__proto__:null,base8:Ew});const _w=ar({prefix:"9",name:"base10",alphabet:"0123456789"});var Iw=Object.freeze({__proto__:null,base10:_w});const Sw=be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Dw=be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Aw=Object.freeze({__proto__:null,base16:Sw,base16upper:Dw});const Tw=be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ow=be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),$w=be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Rw=be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Bw=be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Pw=be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cw=be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Nw=be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Uw=be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var kw=Object.freeze({__proto__:null,base32:Tw,base32hex:Bw,base32hexpad:Cw,base32hexpadupper:Nw,base32hexupper:Pw,base32pad:$w,base32padupper:Rw,base32upper:Ow,base32z:Uw});const Lw=ar({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Fw=ar({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Mw=Object.freeze({__proto__:null,base36:Lw,base36upper:Fw});const qw=ar({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),jw=ar({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var zw=Object.freeze({__proto__:null,base58btc:qw,base58flickr:jw});const Vw=be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Kw=be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Hw=be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ww=be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Gw=Object.freeze({__proto__:null,base64:Vw,base64pad:Kw,base64url:Hw,base64urlpad:Ww});const Zc=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}"),Yw=Zc.reduce((t,e,n)=>(t[n]=e,t),[]),Zw=Zc.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Xw(t){return t.reduce((e,n)=>(e+=Yw[n],e),"")}function Jw(t){const e=[];for(const n of t){const r=Zw[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Qw=is({prefix:"\u{1F680}",name:"base256emoji",encode:Xw,decode:Jw});var em=Object.freeze({__proto__:null,base256emoji:Qw});const Xc={...mw,...vw,...xw,...Iw,...Aw,...kw,...Mw,...zw,...Gw,...em};function Mi(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Jc(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Mi(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Qc(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const el=Qc("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),qi=Qc("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=Jc(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),tl={utf8:el,"utf-8":el,hex:Xc.base16,latin1:qi,ascii:qi,binary:qi,...Xc};function _e(t,e="utf8"){const n=tl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Mi(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var nl=function(t,e,n){if(n||arguments.length===2)for(var r=0,s=e.length,i;r<s;r++)(i||!(r in e))&&(i||(i=Array.prototype.slice.call(e,0,r)),i[r]=e[r]);return t.concat(i||Array.prototype.slice.call(e))},tm=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),nm=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),rm=function(){function t(e,n,r,s){this.name=e,this.version=n,this.os=r,this.bot=s,this.type="bot-device"}return t}(),sm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),im=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),om=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,am=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,rl=3,cm=[["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",om]],sl=[["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 lm(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new im:typeof navigator<"u"?hm(navigator.userAgent):dm()}function um(t){return t!==""&&cm.reduce(function(e,n){var r=n[0],s=n[1];if(e)return e;var i=s.exec(t);return!!i&&[r,i]},!1)}function hm(t){var e=um(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new sm;var s=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);s?s.length<rl&&(s=nl(nl([],s,!0),pm(rl-s.length),!0)):s=[];var i=s.join("."),o=fm(t),a=am.exec(t);return a&&a[1]?new rm(n,i,o,a[1]):new tm(n,i,o)}function fm(t){for(var e=0,n=sl.length;e<n;e++){var r=sl[e],s=r[0],i=r[1],o=i.exec(t);if(o)return s}return null}function dm(){var t=typeof process<"u"&&process.version;return t?new nm(process.version.slice(1)):null}function pm(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var Q={},il;function ol(){if(il)return Q;il=1,Object.defineProperty(Q,"__esModule",{value:!0}),Q.getLocalStorage=Q.getLocalStorageOrThrow=Q.getCrypto=Q.getCryptoOrThrow=Q.getLocation=Q.getLocationOrThrow=Q.getNavigator=Q.getNavigatorOrThrow=Q.getDocument=Q.getDocumentOrThrow=Q.getFromWindowOrThrow=Q.getFromWindow=void 0;function t(f){let p;return typeof window<"u"&&typeof window[f]<"u"&&(p=window[f]),p}Q.getFromWindow=t;function e(f){const p=t(f);if(!p)throw new Error(`${f} is not defined in Window`);return p}Q.getFromWindowOrThrow=e;function n(){return e("document")}Q.getDocumentOrThrow=n;function r(){return t("document")}Q.getDocument=r;function s(){return e("navigator")}Q.getNavigatorOrThrow=s;function i(){return t("navigator")}Q.getNavigator=i;function o(){return e("location")}Q.getLocationOrThrow=o;function a(){return t("location")}Q.getLocation=a;function c(){return e("crypto")}Q.getCryptoOrThrow=c;function l(){return t("crypto")}Q.getCrypto=l;function u(){return e("localStorage")}Q.getLocalStorageOrThrow=u;function h(){return t("localStorage")}return Q.getLocalStorage=h,Q}var xt=ol(),cr={},al;function gm(){if(al)return cr;al=1,Object.defineProperty(cr,"__esModule",{value:!0}),cr.getWindowMetadata=void 0;const t=ol();function e(){let n,r;try{n=t.getDocumentOrThrow(),r=t.getLocationOrThrow()}catch{return null}function s(){const p=n.getElementsByTagName("link"),d=[];for(let g=0;g<p.length;g++){const y=p[g],b=y.getAttribute("rel");if(b&&b.toLowerCase().indexOf("icon")>-1){const A=y.getAttribute("href");if(A)if(A.toLowerCase().indexOf("https:")===-1&&A.toLowerCase().indexOf("http:")===-1&&A.indexOf("//")!==0){let w=r.protocol+"//"+r.host;if(A.indexOf("/")===0)w+=A;else{const m=r.pathname.split("/");m.pop();const x=m.join("/");w+=x+"/"+A}d.push(w)}else if(A.indexOf("//")===0){const w=r.protocol+A;d.push(w)}else d.push(A)}}return d}function i(...p){const d=n.getElementsByTagName("meta");for(let g=0;g<d.length;g++){const y=d[g],b=["itemprop","property","name"].map(A=>y.getAttribute(A)).filter(A=>A?p.includes(A):!1);if(b.length&&b){const A=y.getAttribute("content");if(A)return A}}return""}function o(){let p=i("name","og:site_name","og:title","twitter:title");return p||(p=n.title),p}function a(){return i("description","og:description","twitter:description","keywords")}const c=o(),l=a(),u=r.origin,h=s();return{description:l,url:u,icons:h,name:c}}return cr.getWindowMetadata=e,cr}var ym=gm();const os=BigInt(2**32-1),cl=BigInt(32);function ll(t,e=!1){return e?{h:Number(t&os),l:Number(t>>cl&os)}:{h:Number(t>>cl&os)|0,l:Number(t&os)|0}}function ul(t,e=!1){const n=t.length;let r=new Uint32Array(n),s=new Uint32Array(n);for(let i=0;i<n;i++){const{h:o,l:a}=ll(t[i],e);[r[i],s[i]]=[o,a]}return[r,s]}const hl=(t,e,n)=>t>>>n,fl=(t,e,n)=>t<<32-n|e>>>n,Ht=(t,e,n)=>t>>>n|e<<32-n,Wt=(t,e,n)=>t<<32-n|e>>>n,lr=(t,e,n)=>t<<64-n|e>>>n-32,ur=(t,e,n)=>t>>>n-32|e<<64-n,wm=(t,e)=>e,mm=(t,e)=>t,bm=(t,e,n)=>t<<n|e>>>32-n,vm=(t,e,n)=>e<<n|t>>>32-n,Em=(t,e,n)=>e<<n-32|t>>>64-n,xm=(t,e,n)=>t<<n-32|e>>>64-n;function et(t,e,n,r){const s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}const ji=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),zi=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,_m=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Im=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Sm=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Dm=(t,e,n,r,s,i)=>e+n+r+s+i+(t/2**32|0)|0,Mn=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function as(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ft(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function tt(t,...e){if(!as(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 cs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ft(t.outputLen),ft(t.blockLen)}function Gt(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 Vi(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 hr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ke(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Ki(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function dt(t,e){return t<<32-e|t>>>e}const dl=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function pl(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const _t=dl?t=>t:t=>pl(t);function Am(t){for(let e=0;e<t.length;e++)t[e]=pl(t[e]);return t}const Yt=dl?t=>t:Am,gl=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Tm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function qn(t){if(tt(t),gl)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Tm[t[n]];return e}const It={_0:48,_9:57,A:65,F:70,a:97,f:102};function yl(t){if(t>=It._0&&t<=It._9)return t-It._0;if(t>=It.A&&t<=It.F)return t-(It.A-10);if(t>=It.a&&t<=It.f)return t-(It.a-10)}function ls(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(gl)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 s=0,i=0;s<n;s++,i+=2){const o=yl(t.charCodeAt(i)),a=yl(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function wl(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function nt(t){return typeof t=="string"&&(t=wl(t)),tt(t),t}function St(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];tt(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}class us{}function fr(t){const e=r=>t().update(nt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Om(t){const e=(r,s)=>t(s).update(nt(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Zt(t=32){if(Mn&&typeof Mn.getRandomValues=="function")return Mn.getRandomValues(new Uint8Array(t));if(Mn&&typeof Mn.randomBytes=="function")return Uint8Array.from(Mn.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const $m=BigInt(0),dr=BigInt(1),Rm=BigInt(2),Bm=BigInt(7),Pm=BigInt(256),Cm=BigInt(113),ml=[],bl=[],vl=[];for(let t=0,e=dr,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],ml.push(2*(5*r+n)),bl.push((t+1)*(t+2)/2%64);let s=$m;for(let i=0;i<7;i++)e=(e<<dr^(e>>Bm)*Cm)%Pm,e&Rm&&(s^=dr<<(dr<<BigInt(i))-dr);vl.push(s)}const El=ul(vl,!0),Nm=El[0],Um=El[1],xl=(t,e,n)=>n>32?Em(t,e,n):bm(t,e,n),_l=(t,e,n)=>n>32?xm(t,e,n):vm(t,e,n);function km(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,l=n[c],u=n[c+1],h=xl(l,u,1)^n[a],f=_l(l,u,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let s=t[2],i=t[3];for(let o=0;o<24;o++){const a=bl[o],c=xl(s,i,a),l=_l(s,i,a),u=ml[o];s=t[u],i=t[u+1],t[u]=c,t[u+1]=l}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]^=Nm[r],t[1]^=Um[r]}Ke(n)}class Hi extends us{constructor(e,n,r,s=!1,i=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=s,this.rounds=i,ft(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=hr(this.state)}clone(){return this._cloneInto()}keccak(){Yt(this.state32),km(this.state32,this.rounds),Yt(this.state32),this.posOut=0,this.pos=0}update(e){Gt(this),e=nt(e),tt(e);const{blockLen:n,state:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(n-this.pos,s-i);for(let a=0;a<o;a++)r[this.pos++]^=e[i++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,(n&128)!==0&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){Gt(this,!1),tt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let s=0,i=e.length;s<i;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,i-s);e.set(n.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ft(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Vi(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,Ke(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:s,rounds:i,enableXOF:o}=this;return e||(e=new Hi(n,r,s,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=r,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Lm=(t,e,n)=>fr(()=>new Hi(e,t,n)),Il=Lm(1,136,256/8),Fm="0.1.1";function Mm(){return Fm}class ne extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof ne){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})(),s=n.cause instanceof ne&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||s?["",r?`Details: ${r}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
15
+ `);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Mm()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return Sl(this,e)}}function Sl(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Sl(t.cause,e):e?null:t}function qm(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function jm(t,e,n){return t&e^~t&n}function zm(t,e,n){return t&e^t&n^e&n}class Dl extends us{constructor(e,n,r,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=s,this.buffer=new Uint8Array(e),this.view=Ki(this.buffer)}update(e){Gt(this),e=nt(e),tt(e);const{view:n,buffer:r,blockLen:s}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(s-this.pos,i-o);if(a===s){const c=Ki(e);for(;s<=i-o;o+=s)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Gt(this),Vi(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:s,isLE:i}=this;let{pos:o}=this;n[o++]=128,Ke(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(r,0),o=0);for(let h=o;h<s;h++)n[h]=0;qm(r,s-8,BigInt(this.length*8),i),this.process(r,0);const a=Ki(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],i)}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:s,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=s,e.pos=a,s%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Xt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ie=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Se=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Vm=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]),Jt=new Uint32Array(64);class Km extends Dl{constructor(e=32){super(64,e,8,!1),this.A=Xt[0]|0,this.B=Xt[1]|0,this.C=Xt[2]|0,this.D=Xt[3]|0,this.E=Xt[4]|0,this.F=Xt[5]|0,this.G=Xt[6]|0,this.H=Xt[7]|0}get(){const{A:e,B:n,C:r,D:s,E:i,F:o,G:a,H:c}=this;return[e,n,r,s,i,o,a,c]}set(e,n,r,s,i,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=s|0,this.E=i|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)Jt[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=Jt[h-15],p=Jt[h-2],d=dt(f,7)^dt(f,18)^f>>>3,g=dt(p,17)^dt(p,19)^p>>>10;Jt[h]=g+Jt[h-7]+d+Jt[h-16]|0}let{A:r,B:s,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=dt(a,6)^dt(a,11)^dt(a,25),p=u+f+jm(a,c,l)+Vm[h]+Jt[h]|0,g=(dt(r,2)^dt(r,13)^dt(r,22))+zm(r,s,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=s,s=r,r=p+g|0}r=r+this.A|0,s=s+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,s,i,o,a,c,l,u)}roundClean(){Ke(Jt)}destroy(){this.set(0,0,0,0,0,0,0,0),Ke(this.buffer)}}const Al=ul(["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))),Hm=Al[0],Wm=Al[1],Qt=new Uint32Array(80),en=new Uint32Array(80);class Wi extends Dl{constructor(e=64){super(128,e,16,!1),this.Ah=Se[0]|0,this.Al=Se[1]|0,this.Bh=Se[2]|0,this.Bl=Se[3]|0,this.Ch=Se[4]|0,this.Cl=Se[5]|0,this.Dh=Se[6]|0,this.Dl=Se[7]|0,this.Eh=Se[8]|0,this.El=Se[9]|0,this.Fh=Se[10]|0,this.Fl=Se[11]|0,this.Gh=Se[12]|0,this.Gl=Se[13]|0,this.Hh=Se[14]|0,this.Hl=Se[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:s,Ch:i,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=s|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|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 w=0;w<16;w++,n+=4)Qt[w]=e.getUint32(n),en[w]=e.getUint32(n+=4);for(let w=16;w<80;w++){const m=Qt[w-15]|0,x=en[w-15]|0,_=Ht(m,x,1)^Ht(m,x,8)^hl(m,x,7),T=Wt(m,x,1)^Wt(m,x,8)^fl(m,x,7),$=Qt[w-2]|0,P=en[w-2]|0,k=Ht($,P,19)^lr($,P,61)^hl($,P,6),U=Wt($,P,19)^ur($,P,61)^fl($,P,6),N=_m(T,U,en[w-7],en[w-16]),S=Im(N,_,k,Qt[w-7],Qt[w-16]);Qt[w]=S|0,en[w]=N|0}let{Ah:r,Al:s,Bh:i,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:b,Hl:A}=this;for(let w=0;w<80;w++){const m=Ht(h,f,14)^Ht(h,f,18)^lr(h,f,41),x=Wt(h,f,14)^Wt(h,f,18)^ur(h,f,41),_=h&p^~h&g,T=f&d^~f&y,$=Sm(A,x,T,Wm[w],en[w]),P=Dm($,b,m,_,Hm[w],Qt[w]),k=$|0,U=Ht(r,s,28)^lr(r,s,34)^lr(r,s,39),N=Wt(r,s,28)^ur(r,s,34)^ur(r,s,39),S=r&i^r&a^i&a,R=s&o^s&c^o&c;b=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=et(l|0,u|0,P|0,k|0),l=a|0,u=c|0,a=i|0,c=o|0,i=r|0,o=s|0;const v=ji(k,N,R);r=zi(v,P,U,S),s=v|0}({h:r,l:s}=et(this.Ah|0,this.Al|0,r|0,s|0)),{h:i,l:o}=et(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:c}=et(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=et(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=et(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=et(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=et(this.Gh|0,this.Gl|0,g|0,y|0),{h:b,l:A}=et(this.Hh|0,this.Hl|0,b|0,A|0),this.set(r,s,i,o,a,c,l,u,h,f,p,d,g,y,b,A)}roundClean(){Ke(Qt,en)}destroy(){Ke(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Gm extends Wi{constructor(){super(48),this.Ah=Ie[0]|0,this.Al=Ie[1]|0,this.Bh=Ie[2]|0,this.Bl=Ie[3]|0,this.Ch=Ie[4]|0,this.Cl=Ie[5]|0,this.Dh=Ie[6]|0,this.Dl=Ie[7]|0,this.Eh=Ie[8]|0,this.El=Ie[9]|0,this.Fh=Ie[10]|0,this.Fl=Ie[11]|0,this.Gh=Ie[12]|0,this.Gl=Ie[13]|0,this.Hh=Ie[14]|0,this.Hl=Ie[15]|0}}const De=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class Ym extends Wi{constructor(){super(32),this.Ah=De[0]|0,this.Al=De[1]|0,this.Bh=De[2]|0,this.Bl=De[3]|0,this.Ch=De[4]|0,this.Cl=De[5]|0,this.Dh=De[6]|0,this.Dl=De[7]|0,this.Eh=De[8]|0,this.El=De[9]|0,this.Fh=De[10]|0,this.Fl=De[11]|0,this.Gh=De[12]|0,this.Gl=De[13]|0,this.Hh=De[14]|0,this.Hl=De[15]|0}}const mn=fr(()=>new Km),Zm=fr(()=>new Wi),Xm=fr(()=>new Gm),Jm=fr(()=>new Ym),hs=mn;/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Gi=BigInt(0),Yi=BigInt(1);function pr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Zi(t){if(!pr(t))throw new Error("Uint8Array expected")}function gr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function fs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Tl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Gi:BigInt("0x"+t)}const Ol=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qm=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function yr(t){if(Zi(t),Ol)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Qm[t[n]];return e}const Dt={_0:48,_9:57,A:65,F:70,a:97,f:102};function $l(t){if(t>=Dt._0&&t<=Dt._9)return t-Dt._0;if(t>=Dt.A&&t<=Dt.F)return t-(Dt.A-10);if(t>=Dt.a&&t<=Dt.f)return t-(Dt.a-10)}function ds(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ol)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 s=0,i=0;s<n;s++,i+=2){const o=$l(t.charCodeAt(i)),a=$l(t.charCodeAt(i+1));if(o===void 0||a===void 0){const c=t[i]+t[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}r[s]=o*16+a}return r}function bn(t){return Tl(yr(t))}function Rl(t){return Zi(t),Tl(yr(Uint8Array.from(t).reverse()))}function wr(t,e){return ds(t.toString(16).padStart(e*2,"0"))}function Bl(t,e){return wr(t,e).reverse()}function He(t,e,n){let r;if(typeof e=="string")try{r=ds(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(pr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}function ps(...t){let e=0;for(let r=0;r<t.length;r++){const s=t[r];Zi(s),e+=s.length}const n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){const i=t[r];n.set(i,s),s+=i.length}return n}const Xi=t=>typeof t=="bigint"&&Gi<=t;function Ji(t,e,n){return Xi(t)&&Xi(e)&&Xi(n)&&e<=t&&t<n}function jn(t,e,n,r){if(!Ji(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function eb(t){let e;for(e=0;t>Gi;t>>=Yi,e+=1);return e}const gs=t=>(Yi<<BigInt(t))-Yi,Qi=t=>new Uint8Array(t),Pl=t=>Uint8Array.from(t);function tb(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=Qi(t),s=Qi(t),i=0;const o=()=>{r.fill(1),s.fill(0),i=0},a=(...h)=>n(s,r,...h),c=(h=Qi(0))=>{s=a(Pl([0]),h),r=a(),h.length!==0&&(s=a(Pl([1]),h),r=a())},l=()=>{if(i++>=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 ps(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(l()));)c();return o(),p}}const nb={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"||pr(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 ys(t,e,n={}){const r=(s,i,o)=>{const a=nb[i];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+i+", got "+c)};for(const[s,i]of Object.entries(e))r(s,i,!1);for(const[s,i]of Object.entries(n))r(s,i,!0);return t}function Cl(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}function rb(t,e){if(jl(t)>e)throw new Ib({givenSize:jl(t),maxSize:e})}const At={zero:48,nine:57,A:65,F:70,a:97,f:102};function Nl(t){if(t>=At.zero&&t<=At.nine)return t-At.zero;if(t>=At.A&&t<=At.F)return t-(At.A-10);if(t>=At.a&&t<=At.f)return t-(At.a-10)}function sb(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new Sb({size:t.length,targetSize:r,type:"Bytes"});const s=new Uint8Array(r);for(let i=0;i<r;i++){const o=n==="right";s[o?i:r-i-1]=t[o?i:t.length-i-1]}return s}function Ul(t,e){if(tn(t)>e)throw new pb({givenSize:tn(t),maxSize:e})}function ib(t,e){if(typeof e=="number"&&e>0&&e>tn(t)-1)throw new ql({offset:e,position:"start",size:tn(t)})}function ob(t,e,n){if(typeof e=="number"&&typeof n=="number"&&tn(t)!==n-e)throw new ql({offset:n,position:"end",size:tn(t)})}function kl(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const s=t.replace("0x","");if(s.length>r*2)throw new gb({size:Math.ceil(s.length/2),targetSize:r,type:"Hex"});return`0x${s[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const ab="#__bigint";function eo(t,e,n){return JSON.stringify(t,(r,s)=>typeof s=="bigint"?s.toString()+ab:s,n)}const cb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function lb(t,e={}){const{strict:n=!1}=e;if(!t)throw new Fl(t);if(typeof t!="string")throw new Fl(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Ml(t);if(!t.startsWith("0x"))throw new Ml(t)}function ub(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function to(t){return t instanceof Uint8Array?ws(t):Array.isArray(t)?ws(new Uint8Array(t)):t}function ws(t,e={}){let n="";for(let s=0;s<t.length;s++)n+=cb[t[s]];const r=`0x${n}`;return typeof e.size=="number"?(Ul(r,e.size),Ll(r,e.size)):r}function no(t,e={}){const{signed:n,size:r}=e,s=BigInt(t);let i;r?n?i=(1n<<BigInt(r)*8n-1n)-1n:i=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(i=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof i=="bigint"&&n?-i-1n:0;if(i&&s>i||s<o){const l=typeof t=="bigint"?"n":"";throw new db({max:i?`${i}${l}`:void 0,min:`${o}${l}`,signed:n,size:r,value:`${t}${l}`})}const c=`0x${(n&&s<0?(1n<<BigInt(r*8))+BigInt(s):s).toString(16)}`;return r?hb(c,r):c}function hb(t,e){return kl(t,{dir:"left",size:e})}function Ll(t,e){return kl(t,{dir:"right",size:e})}function Tt(t,e,n,r={}){const{strict:s}=r;ib(t,e);const i=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return s&&ob(i,e,n),i}function tn(t){return Math.ceil((t.length-2)/2)}function fb(t,e={}){const{strict:n=!1}=e;try{return lb(t,{strict:n}),!0}catch{return!1}}class db extends ne{constructor({max:e,min:n,signed:r,size:s,value:i}){super(`Number \`${i}\` is not in safe${s?` ${s*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 Fl extends ne{constructor(e){super(`Value \`${typeof e=="object"?eo(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class Ml extends ne{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let pb=class extends ne{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 ql extends ne{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let gb=class extends ne{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const yb=new TextEncoder;function wb(t){if(!(t instanceof Uint8Array)){if(!t)throw new ms(t);if(typeof t!="object")throw new ms(t);if(!("BYTES_PER_ELEMENT"in t))throw new ms(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new ms(t)}}function mb(t){return t instanceof Uint8Array?t:typeof t=="string"?vb(t):bb(t)}function bb(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function vb(t,e={}){const{size:n}=e;let r=t;n&&(Ul(t,n),r=Ll(t,n));let s=r.slice(2);s.length%2&&(s=`0${s}`);const i=s.length/2,o=new Uint8Array(i);for(let a=0,c=0;a<i;a++){const l=Nl(s.charCodeAt(c++)),u=Nl(s.charCodeAt(c++));if(l===void 0||u===void 0)throw new ne(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=l*16+u}return o}function Eb(t,e={}){const{size:n}=e,r=yb.encode(t);return typeof n=="number"?(rb(r,n),xb(r,n)):r}function xb(t,e){return sb(t,{dir:"right",size:e})}function jl(t){return t.length}function _b(t){try{return wb(t),!0}catch{return!1}}class ms extends ne{constructor(e){super(`Value \`${typeof e=="object"?eo(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class Ib extends ne{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 Sb extends ne{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function zl(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=Il(mb(t));return n==="Bytes"?r:ws(r)}class Db 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 ro={checksum:new Db(8192)}.checksum;function Vl(t,e={}){const{compressed:n}=e,{prefix:r,x:s,y:i}=t;if(n===!1||typeof s=="bigint"&&typeof i=="bigint"){if(r!==4)throw new Hl({prefix:r,cause:new Bb});return}if(n===!0||typeof s=="bigint"&&typeof i>"u"){if(r!==3&&r!==2)throw new Hl({prefix:r,cause:new Rb});return}throw new $b({publicKey:t})}function Ab(t){const e=(()=>{if(fb(t))return Kl(t);if(_b(t))return Tb(t);const{prefix:n,x:r,y:s}=t;return typeof r=="bigint"&&typeof s=="bigint"?{prefix:n??4,x:r,y:s}:{prefix:n,x:r}})();return Vl(e),e}function Tb(t){return Kl(ws(t))}function Kl(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new Pb({publicKey:t});if(t.length===130){const r=BigInt(Tt(t,0,32)),s=BigInt(Tt(t,32,64));return{prefix:4,x:r,y:s}}if(t.length===132){const r=Number(Tt(t,0,1)),s=BigInt(Tt(t,1,33)),i=BigInt(Tt(t,33,65));return{prefix:r,x:s,y:i}}const e=Number(Tt(t,0,1)),n=BigInt(Tt(t,1,33));return{prefix:e,x:n}}function Ob(t,e={}){Vl(t);const{prefix:n,x:r,y:s}=t,{includePrefix:i=!0}=e;return ub(i?no(n,{size:1}):"0x",no(r,{size:32}),typeof s=="bigint"?no(s,{size:32}):"0x")}class $b extends ne{constructor({publicKey:e}){super(`Value \`${eo(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class Hl extends ne{constructor({prefix:e,cause:n}){super(`Prefix "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Rb extends ne{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class Bb extends ne{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let Pb=class extends ne{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${tn(to(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Cb=/^0x[a-fA-F0-9]{40}$/;function Wl(t,e={}){const{strict:n=!0}=e;if(!Cb.test(t))throw new Yl({address:t,cause:new kb});if(n){if(t.toLowerCase()===t)return;if(Gl(t)!==t)throw new Yl({address:t,cause:new Lb})}}function Gl(t){if(ro.has(t))return ro.get(t);Wl(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=zl(Eb(e),{as:"Bytes"}),r=e.split("");for(let i=0;i<40;i+=2)n[i>>1]>>4>=8&&r[i]&&(r[i]=r[i].toUpperCase()),(n[i>>1]&15)>=8&&r[i+1]&&(r[i+1]=r[i+1].toUpperCase());const s=`0x${r.join("")}`;return ro.set(t,s),s}function Nb(t,e={}){const{checksum:n=!1}=e;return Wl(t),n?Gl(t):t}function Ub(t,e={}){const n=zl(`0x${Ob(t).slice(4)}`).substring(26);return Nb(`0x${n}`,e)}class Yl extends ne{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 kb extends ne{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 Lb extends ne{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class Zl extends us{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,cs(e);const r=nt(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 s=this.blockLen,i=new Uint8Array(s);i.set(r.length>s?e.create().update(r).digest():r);for(let o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(let o=0;o<i.length;o++)i[o]^=106;this.oHash.update(i),Ke(i)}update(e){return Gt(this),this.iHash.update(e),this}digestInto(e){Gt(this),tt(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:s,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=i,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 mr=(t,e,n)=>new Zl(t,e).update(n).digest();mr.create=(t,e)=>new Zl(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ce=BigInt(0),Te=BigInt(1),vn=BigInt(2),Fb=BigInt(3),Xl=BigInt(4),Jl=BigInt(5),Ql=BigInt(8);function Ne(t,e){const n=t%e;return n>=Ce?n:e+n}function We(t,e,n){let r=t;for(;e-- >Ce;)r*=r,r%=n;return r}function so(t,e){if(t===Ce)throw new Error("invert: expected non-zero number");if(e<=Ce)throw new Error("invert: expected positive modulus, got "+e);let n=Ne(t,e),r=e,s=Ce,i=Te;for(;n!==Ce;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==Te)throw new Error("invert: does not exist");return Ne(s,e)}function eu(t,e){const n=(t.ORDER+Te)/Xl,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function Mb(t,e){const n=(t.ORDER-Jl)/Ql,r=t.mul(e,vn),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,vn),s),a=t.mul(i,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function qb(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Te,n=0;for(;e%vn===Ce;)e/=vn,n++;let r=vn;const s=io(t);for(;nu(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return eu;let i=s.pow(r,e);const o=(e+Te)/vn;return function(c,l){if(c.is0(l))return l;if(nu(c,l)!==1)throw new Error("Cannot find square root");let u=n,h=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,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===u)throw new Error("Cannot find square root");const y=Te<<BigInt(u-d-1),b=c.pow(h,y);u=d,h=c.sqr(b),f=c.mul(f,h),p=c.mul(p,b)}return p}}function jb(t){return t%Xl===Fb?eu:t%Ql===Jl?Mb:qb(t)}const zb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Vb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=zb.reduce((r,s)=>(r[s]="function",r),e);return ys(t,n)}function Kb(t,e,n){if(n<Ce)throw new Error("invalid exponent, negatives unsupported");if(n===Ce)return t.ONE;if(n===Te)return e;let r=t.ONE,s=e;for(;n>Ce;)n&Te&&(r=t.mul(r,s)),s=t.sqr(s),n>>=Te;return r}function tu(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function nu(t,e){const n=(t.ORDER-Te)/vn,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function ru(t,e){e!==void 0&&ft(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function io(t,e,n=!1,r={}){if(t<=Ce)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:i}=ru(t,e);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:s,BYTES:i,MASK:gs(s),ZERO:Ce,ONE:Te,create:c=>Ne(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ce<=c&&c<t},is0:c=>c===Ce,isOdd:c=>(c&Te)===Te,neg:c=>Ne(-c,t),eql:(c,l)=>c===l,sqr:c=>Ne(c*c,t),add:(c,l)=>Ne(c+l,t),sub:(c,l)=>Ne(c-l,t),mul:(c,l)=>Ne(c*l,t),pow:(c,l)=>Kb(a,c,l),div:(c,l)=>Ne(c*so(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>so(c,t),sqrt:r.sqrt||(c=>(o||(o=jb(t)),o(a,c))),toBytes:c=>n?Bl(c,i):wr(c,i),fromBytes:c=>{if(c.length!==i)throw new Error("Field.fromBytes: expected "+i+" bytes, got "+c.length);return n?Rl(c):bn(c)},invertBatch:c=>tu(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function su(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 iu(t){const e=su(t);return e+Math.ceil(e/2)}function Hb(t,e,n=!1){const r=t.length,s=su(e),i=iu(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?Rl(t):bn(t),a=Ne(o,e-Te)+Te;return n?Bl(a,s):wr(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ou=BigInt(0),oo=BigInt(1);function ao(t,e){const n=e.negate();return t?n:e}function au(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function co(t,e){au(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=gs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function cu(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=oo);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}function Wb(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 Gb(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 lo=new WeakMap,lu=new WeakMap;function uo(t){return lu.get(t)||1}function Yb(t,e){return{constTimeNegate:ao,hasPrecomputes(n){return uo(n)!==1},unsafeLadder(n,r,s=t.ZERO){let i=n;for(;r>ou;)r&oo&&(s=s.add(i)),i=i.double(),r>>=oo;return s},precomputeWindow(n,r){const{windows:s,windowSize:i}=co(r,e),o=[];let a=n,c=a;for(let l=0;l<s;l++){c=a,o.push(c);for(let u=1;u<i;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,s){let i=t.ZERO,o=t.BASE;const a=co(n,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:d}=cu(s,c,a);s=l,h?o=o.add(ao(p,r[d])):i=i.add(ao(f,r[u]))}return{p:i,f:o}},wNAFUnsafe(n,r,s,i=t.ZERO){const o=co(n,e);for(let a=0;a<o.windows&&s!==ou;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=cu(s,a,o);if(s=c,!u){const f=r[l];i=i.add(h?f.negate():f)}}return i},getPrecomputes(n,r,s){let i=lo.get(r);return i||(i=this.precomputeWindow(r,n),n!==1&&lo.set(r,s(i))),i},wNAFCached(n,r,s){const i=uo(n);return this.wNAF(i,this.getPrecomputes(i,n,s),r)},wNAFCachedUnsafe(n,r,s,i){const o=uo(n);return o===1?this.unsafeLadder(n,r,i):this.wNAFUnsafe(o,this.getPrecomputes(o,n,s),r,i)},setWindowSize(n,r){au(r,e),lu.set(n,r),lo.delete(n)}}}function Zb(t,e,n,r){Wb(n,t),Gb(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=eb(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=gs(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){u.fill(o);for(let g=0;g<i;g++){const y=r[g],b=Number(y>>BigInt(p)&l);u[b]=u[b].add(n[g])}let d=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[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 uu(t){return Vb(t.Fp),ys(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ru(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function hu(t){t.lowS!==void 0&&gr("lowS",t.lowS),t.prehash!==void 0&&gr("prehash",t.prehash)}function Xb(t){const e=uu(t);ys(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:s}=e;if(n){if(!r.eql(s,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})}const Ot={Err:class extends Error{constructor(e=""){super(e)}},_tlv:{encode:(t,e)=>{const{Err:n}=Ot;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,s=fs(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?fs(s.length/2|128):"";return fs(t)+i+s+e},decode(t,e){const{Err:n}=Ot;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 s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&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 l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;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}=Ot;if(t<$t)throw new e("integer: negative integers are not allowed");let n=fs(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}=Ot;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 bn(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Ot,s=He("signature",t),{v:i,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=Ot,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),i=r+s;return e.encode(48,i)}};function ho(t,e){return yr(wr(t,e))}const $t=BigInt(0),ye=BigInt(1);BigInt(2);const fo=BigInt(3),Jb=BigInt(4);function Qb(t){const e=Xb(t),{Fp:n}=e,r=io(e.n,e.nBitLength),s=e.toBytes||((w,m,x)=>{const _=m.toAffine();return ps(Uint8Array.from([4]),n.toBytes(_.x),n.toBytes(_.y))}),i=e.fromBytes||(w=>{const m=w.subarray(1),x=n.fromBytes(m.subarray(0,n.BYTES)),_=n.fromBytes(m.subarray(n.BYTES,2*n.BYTES));return{x,y:_}});function o(w){const{a:m,b:x}=e,_=n.sqr(w),T=n.mul(_,w);return n.add(n.add(T,n.mul(w,m)),x)}function a(w,m){const x=n.sqr(m),_=o(w);return n.eql(x,_)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,fo),Jb),l=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,l)))throw new Error("bad curve params: a or b");function u(w){return Ji(w,ye,e.n)}function h(w){const{allowedPrivateKeyLengths:m,nByteLength:x,wrapPrivateKey:_,n:T}=e;if(m&&typeof w!="bigint"){if(pr(w)&&(w=yr(w)),typeof w!="string"||!m.includes(w.length))throw new Error("invalid private key");w=w.padStart(x*2,"0")}let $;try{$=typeof w=="bigint"?w:bn(He("private key",w,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof w)}return _&&($=Ne($,T)),jn("private key",$,ye,T),$}function f(w){if(!(w instanceof g))throw new Error("ProjectivePoint expected")}const p=Cl((w,m)=>{const{px:x,py:_,pz:T}=w;if(n.eql(T,n.ONE))return{x,y:_};const $=w.is0();m==null&&(m=$?n.ONE:n.inv(T));const P=n.mul(x,m),k=n.mul(_,m),U=n.mul(T,m);if($)return{x:n.ZERO,y:n.ZERO};if(!n.eql(U,n.ONE))throw new Error("invZ was invalid");return{x:P,y:k}}),d=Cl(w=>{if(w.is0()){if(e.allowInfinityPoint&&!n.is0(w.py))return;throw new Error("bad point: ZERO")}const{x:m,y:x}=w.toAffine();if(!n.isValid(m)||!n.isValid(x))throw new Error("bad point: x or y not FE");if(!a(m,x))throw new Error("bad point: equation left != right");if(!w.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(m,x,_){if(m==null||!n.isValid(m))throw new Error("x required");if(x==null||!n.isValid(x)||n.is0(x))throw new Error("y required");if(_==null||!n.isValid(_))throw new Error("z required");this.px=m,this.py=x,this.pz=_,Object.freeze(this)}static fromAffine(m){const{x,y:_}=m||{};if(!m||!n.isValid(x)||!n.isValid(_))throw new Error("invalid affine point");if(m instanceof g)throw new Error("projective point not allowed");const T=$=>n.eql($,n.ZERO);return T(x)&&T(_)?g.ZERO:new g(x,_,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){const x=tu(n,m.map(_=>_.pz));return m.map((_,T)=>_.toAffine(x[T])).map(g.fromAffine)}static fromHex(m){const x=g.fromAffine(i(He("pointHex",m)));return x.assertValidity(),x}static fromPrivateKey(m){return g.BASE.multiply(h(m))}static msm(m,x){return Zb(g,r,m,x)}_setWindowSize(m){A.setWindowSize(this,m)}assertValidity(){d(this)}hasEvenY(){const{y:m}=this.toAffine();if(n.isOdd)return!n.isOdd(m);throw new Error("Field doesn't support isOdd")}equals(m){f(m);const{px:x,py:_,pz:T}=this,{px:$,py:P,pz:k}=m,U=n.eql(n.mul(x,k),n.mul($,T)),N=n.eql(n.mul(_,k),n.mul(P,T));return U&&N}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:m,b:x}=e,_=n.mul(x,fo),{px:T,py:$,pz:P}=this;let k=n.ZERO,U=n.ZERO,N=n.ZERO,S=n.mul(T,T),R=n.mul($,$),v=n.mul(P,P),E=n.mul(T,$);return E=n.add(E,E),N=n.mul(T,P),N=n.add(N,N),k=n.mul(m,N),U=n.mul(_,v),U=n.add(k,U),k=n.sub(R,U),U=n.add(R,U),U=n.mul(k,U),k=n.mul(E,k),N=n.mul(_,N),v=n.mul(m,v),E=n.sub(S,v),E=n.mul(m,E),E=n.add(E,N),N=n.add(S,S),S=n.add(N,S),S=n.add(S,v),S=n.mul(S,E),U=n.add(U,S),v=n.mul($,P),v=n.add(v,v),S=n.mul(v,E),k=n.sub(k,S),N=n.mul(v,R),N=n.add(N,N),N=n.add(N,N),new g(k,U,N)}add(m){f(m);const{px:x,py:_,pz:T}=this,{px:$,py:P,pz:k}=m;let U=n.ZERO,N=n.ZERO,S=n.ZERO;const R=e.a,v=n.mul(e.b,fo);let E=n.mul(x,$),D=n.mul(_,P),B=n.mul(T,k),I=n.add(x,_),O=n.add($,P);I=n.mul(I,O),O=n.add(E,D),I=n.sub(I,O),O=n.add(x,T);let C=n.add($,k);return O=n.mul(O,C),C=n.add(E,B),O=n.sub(O,C),C=n.add(_,T),U=n.add(P,k),C=n.mul(C,U),U=n.add(D,B),C=n.sub(C,U),S=n.mul(R,O),U=n.mul(v,B),S=n.add(U,S),U=n.sub(D,S),S=n.add(D,S),N=n.mul(U,S),D=n.add(E,E),D=n.add(D,E),B=n.mul(R,B),O=n.mul(v,O),D=n.add(D,B),B=n.sub(E,B),B=n.mul(R,B),O=n.add(O,B),E=n.mul(D,O),N=n.add(N,E),E=n.mul(C,O),U=n.mul(I,U),U=n.sub(U,E),E=n.mul(I,D),S=n.mul(C,S),S=n.add(S,E),new g(U,N,S)}subtract(m){return this.add(m.negate())}is0(){return this.equals(g.ZERO)}wNAF(m){return A.wNAFCached(this,m,g.normalizeZ)}multiplyUnsafe(m){const{endo:x,n:_}=e;jn("scalar",m,$t,_);const T=g.ZERO;if(m===$t)return T;if(this.is0()||m===ye)return this;if(!x||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,m,g.normalizeZ);let{k1neg:$,k1:P,k2neg:k,k2:U}=x.splitScalar(m),N=T,S=T,R=this;for(;P>$t||U>$t;)P&ye&&(N=N.add(R)),U&ye&&(S=S.add(R)),R=R.double(),P>>=ye,U>>=ye;return $&&(N=N.negate()),k&&(S=S.negate()),S=new g(n.mul(S.px,x.beta),S.py,S.pz),N.add(S)}multiply(m){const{endo:x,n:_}=e;jn("scalar",m,ye,_);let T,$;if(x){const{k1neg:P,k1:k,k2neg:U,k2:N}=x.splitScalar(m);let{p:S,f:R}=this.wNAF(k),{p:v,f:E}=this.wNAF(N);S=A.constTimeNegate(P,S),v=A.constTimeNegate(U,v),v=new g(n.mul(v.px,x.beta),v.py,v.pz),T=S.add(v),$=R.add(E)}else{const{p:P,f:k}=this.wNAF(m);T=P,$=k}return g.normalizeZ([T,$])[0]}multiplyAndAddUnsafe(m,x,_){const T=g.BASE,$=(k,U)=>U===$t||U===ye||!k.equals(T)?k.multiplyUnsafe(U):k.multiply(U),P=$(this,x).add($(m,_));return P.is0()?void 0:P}toAffine(m){return p(this,m)}isTorsionFree(){const{h:m,isTorsionFree:x}=e;if(m===ye)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:m,clearCofactor:x}=e;return m===ye?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(m=!0){return gr("isCompressed",m),this.assertValidity(),s(g,this,m)}toHex(m=!0){return gr("isCompressed",m),yr(this.toRawBytes(m))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:y,nBitLength:b}=e,A=Yb(g,y?Math.ceil(b/2):b);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function e1(t){const e=uu(t);return ys(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function t1(t){const e=e1(t),{Fp:n,n:r,nByteLength:s,nBitLength:i}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(v){return Ne(v,r)}function l(v){return so(v,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=Qb({...e,toBytes(v,E,D){const B=E.toAffine(),I=n.toBytes(B.x),O=ps;return gr("isCompressed",D),D?O(Uint8Array.from([E.hasEvenY()?2:3]),I):O(Uint8Array.from([4]),I,n.toBytes(B.y))},fromBytes(v){const E=v.length,D=v[0],B=v.subarray(1);if(E===o&&(D===2||D===3)){const I=bn(B);if(!Ji(I,ye,n.ORDER))throw new Error("Point is not on curve");const O=f(I);let C;try{C=n.sqrt(O)}catch(j){const q=j instanceof Error?": "+j.message:"";throw new Error("Point is not on curve"+q)}const L=(C&ye)===ye;return(D&1)===1!==L&&(C=n.neg(C)),{x:I,y:C}}else if(E===a&&D===4){const I=n.fromBytes(B.subarray(0,n.BYTES)),O=n.fromBytes(B.subarray(n.BYTES,2*n.BYTES));return{x:I,y:O}}else{const I=o,O=a;throw new Error("invalid Point, expected length of "+I+", or uncompressed "+O+", got "+E)}}});function d(v){const E=r>>ye;return v>E}function g(v){return d(v)?c(-v):v}const y=(v,E,D)=>bn(v.slice(E,D));class b{constructor(E,D,B){jn("r",E,ye,r),jn("s",D,ye,r),this.r=E,this.s=D,B!=null&&(this.recovery=B),Object.freeze(this)}static fromCompact(E){const D=s;return E=He("compactSignature",E,D*2),new b(y(E,0,D),y(E,D,2*D))}static fromDER(E){const{r:D,s:B}=Ot.toSig(He("DER",E));return new b(D,B)}assertValidity(){}addRecoveryBit(E){return new b(this.r,this.s,E)}recoverPublicKey(E){const{r:D,s:B,recovery:I}=this,O=T(He("msgHash",E));if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");const C=I===2||I===3?D+e.n:D;if(C>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(I&1)===0?"02":"03",V=u.fromHex(L+ho(C,n.BYTES)),j=l(C),q=c(-O*j),K=c(B*j),W=u.BASE.multiplyAndAddUnsafe(V,q,K);if(!W)throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new b(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ds(this.toDERHex())}toDERHex(){return Ot.hexFromSig(this)}toCompactRawBytes(){return ds(this.toCompactHex())}toCompactHex(){const E=s;return ho(this.r,E)+ho(this.s,E)}}const A={isValidPrivateKey(v){try{return h(v),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const v=iu(e.n);return Hb(e.randomBytes(v),e.n)},precompute(v=8,E=u.BASE){return E._setWindowSize(v),E.multiply(BigInt(3)),E}};function w(v,E=!0){return u.fromPrivateKey(v).toRawBytes(E)}function m(v){if(typeof v=="bigint")return!1;if(v instanceof u)return!0;const D=He("key",v).length,B=n.BYTES,I=B+1,O=2*B+1;if(!(e.allowedPrivateKeyLengths||s===I))return D===I||D===O}function x(v,E,D=!0){if(m(v)===!0)throw new Error("first arg must be private key");if(m(E)===!1)throw new Error("second arg must be public key");return u.fromHex(E).multiply(h(v)).toRawBytes(D)}const _=e.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const E=bn(v),D=v.length*8-i;return D>0?E>>BigInt(D):E},T=e.bits2int_modN||function(v){return c(_(v))},$=gs(i);function P(v){return jn("num < 2^"+i,v,$t,$),wr(v,s)}function k(v,E,D=U){if(["recovered","canonical"].some(H=>H in D))throw new Error("sign() legacy options not supported");const{hash:B,randomBytes:I}=e;let{lowS:O,prehash:C,extraEntropy:L}=D;O==null&&(O=!0),v=He("msgHash",v),hu(D),C&&(v=He("prehashed msgHash",B(v)));const V=T(v),j=h(E),q=[P(j),P(V)];if(L!=null&&L!==!1){const H=L===!0?I(n.BYTES):L;q.push(He("extraEntropy",H))}const K=ps(...q),W=V;function G(H){const Z=_(H);if(!p(Z))return;const ae=l(Z),ce=u.BASE.multiply(Z).toAffine(),we=c(ce.x);if(we===$t)return;const at=c(ae*c(W+we*j));if(at===$t)return;let ct=(ce.x===we?0:2)|Number(ce.y&ye),Ys=at;return O&&d(at)&&(Ys=g(at),ct^=1),new b(we,Ys,ct)}return{seed:K,k2sig:G}}const U={lowS:e.lowS,prehash:!1},N={lowS:e.lowS,prehash:!1};function S(v,E,D=U){const{seed:B,k2sig:I}=k(v,E,D),O=e;return tb(O.hash.outputLen,O.nByteLength,O.hmac)(B,I)}u.BASE._setWindowSize(8);function R(v,E,D,B=N){const I=v;E=He("msgHash",E),D=He("publicKey",D);const{lowS:O,prehash:C,format:L}=B;if(hu(B),"strict"in B)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 V=typeof I=="string"||pr(I),j=!V&&!L&&typeof I=="object"&&I!==null&&typeof I.r=="bigint"&&typeof I.s=="bigint";if(!V&&!j)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,K;try{if(j&&(q=new b(I.r,I.s)),V){try{L!=="compact"&&(q=b.fromDER(I))}catch(ct){if(!(ct instanceof Ot.Err))throw ct}!q&&L!=="der"&&(q=b.fromCompact(I))}K=u.fromHex(D)}catch{return!1}if(!q||O&&q.hasHighS())return!1;C&&(E=e.hash(E));const{r:W,s:G}=q,H=T(E),Z=l(G),ae=c(H*Z),ce=c(W*Z),we=u.BASE.multiplyAndAddUnsafe(K,ae,ce)?.toAffine();return we?c(we.x)===W:!1}return{CURVE:e,getPublicKey:w,getSharedSecret:x,sign:S,verify:R,ProjectivePoint:u,Signature:b,utils:A}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function n1(t){return{hash:t,hmac:(e,...n)=>mr(t,e,St(...n)),randomBytes:Zt}}function r1(t,e){const n=r=>t1({...t,...n1(r)});return{...n(e),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const fu=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),du=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),s1=BigInt(0),i1=BigInt(1),po=BigInt(2),pu=(t,e)=>(t+e/po)/e;function o1(t){const e=fu,n=BigInt(3),r=BigInt(6),s=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=We(u,n,e)*u%e,f=We(h,n,e)*u%e,p=We(f,po,e)*l%e,d=We(p,s,e)*p%e,g=We(d,i,e)*d%e,y=We(g,a,e)*g%e,b=We(y,c,e)*y%e,A=We(b,a,e)*g%e,w=We(A,n,e)*u%e,m=We(w,o,e)*d%e,x=We(m,r,e)*l%e,_=We(x,po,e);if(!go.eql(go.sqr(_),t))throw new Error("Cannot find square root");return _}const go=io(fu,void 0,void 0,{sqrt:o1}),a1=r1({a:s1,b:BigInt(7),Fp:go,n:du,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=du,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-i1*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),s=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),i=n,o=BigInt("0x100000000000000000000000000000000"),a=pu(i*t,e),c=pu(-r*t,e);let l=Ne(t-a*n-c*s,e),u=Ne(-a*r-c*i,e);const h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}}},mn);function c1(t){if(t.length!==130&&t.length!==132)throw new u1({signature:t});const e=BigInt(Tt(t,0,32)),n=BigInt(Tt(t,32,64)),r=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return l1(s)}catch{throw new h1({value:s})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function l1(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new f1({value:t})}class u1 extends ne{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${tn(to(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class h1 extends ne{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class f1 extends ne{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}const d1=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]),ue=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),z=new Uint32Array(32);function nn(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=z[2*t],l=z[2*t+1],u=z[2*e],h=z[2*e+1],f=z[2*n],p=z[2*n+1],d=z[2*r],g=z[2*r+1],y=ji(c,u,o);l=zi(y,l,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^l,Dl:d^c},{Dh:g,Dl:d}={Dh:wm(g,d),Dl:mm(g)},{h:p,l:f}=et(p,f,g,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:Ht(h,u,24),Bl:Wt(h,u,24)},z[2*t]=c,z[2*t+1]=l,z[2*e]=u,z[2*e+1]=h,z[2*n]=f,z[2*n+1]=p,z[2*r]=d,z[2*r+1]=g}function rn(t,e,n,r,s,i){const o=s[i],a=s[i+1];let c=z[2*t],l=z[2*t+1],u=z[2*e],h=z[2*e+1],f=z[2*n],p=z[2*n+1],d=z[2*r],g=z[2*r+1],y=ji(c,u,o);l=zi(y,l,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^l,Dl:d^c},{Dh:g,Dl:d}={Dh:Ht(g,d,16),Dl:Wt(g,d,16)},{h:p,l:f}=et(p,f,g,d),{Bh:h,Bl:u}={Bh:h^p,Bl:u^f},{Bh:h,Bl:u}={Bh:lr(h,u,63),Bl:ur(h,u,63)},z[2*t]=c,z[2*t+1]=l,z[2*e]=u,z[2*e+1]=h,z[2*n]=f,z[2*n+1]=p,z[2*r]=d,z[2*r+1]=g}function p1(t,e={},n,r,s){if(ft(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:i,salt:o,personalization:a}=e;if(i!==void 0&&(i.length<1||i.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!==s)throw new Error("personalization must be undefined or "+s)}class g1 extends us{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,ft(e),ft(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=hr(this.buffer)}update(e){Gt(this),e=nt(e),tt(e);const{blockLen:n,buffer:r,buffer32:s}=this,i=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<i;){this.pos===n&&(Yt(s),this.compress(s,0,!1),Yt(s),this.pos=0);const l=Math.min(n-this.pos,i-c),u=o+c;if(l===n&&!(u%4)&&c+l<i){const h=new Uint32Array(a,u,Math.floor((i-c)/4));Yt(h);for(let f=0;c+n<i;f+=s.length,c+=n)this.length+=n,this.compress(h,f,!1);Yt(h);continue}r.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Gt(this),Vi(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,Ke(this.buffer.subarray(n)),Yt(r),this.compress(r,0,!0),Yt(r);const s=hr(e);this.get().forEach((i,o)=>s[o]=_t(i))}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:s,destroyed:i,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=i,e.finished=s,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class y1 extends g1{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=ue[0]|0,this.v0h=ue[1]|0,this.v1l=ue[2]|0,this.v1h=ue[3]|0,this.v2l=ue[4]|0,this.v2h=ue[5]|0,this.v3l=ue[6]|0,this.v3h=ue[7]|0,this.v4l=ue[8]|0,this.v4h=ue[9]|0,this.v5l=ue[10]|0,this.v5h=ue[11]|0,this.v6l=ue[12]|0,this.v6h=ue[13]|0,this.v7l=ue[14]|0,this.v7h=ue[15]|0,p1(n,e,64,16,16);let{key:r,personalization:s,salt:i}=e,o=0;if(r!==void 0&&(r=nt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,i!==void 0){i=nt(i);const a=hr(i);this.v4l^=_t(a[0]),this.v4h^=_t(a[1]),this.v5l^=_t(a[2]),this.v5h^=_t(a[3])}if(s!==void 0){s=nt(s);const a=hr(s);this.v6l^=_t(a[0]),this.v6h^=_t(a[1]),this.v7l^=_t(a[2]),this.v7h^=_t(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:s,v2l:i,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:h,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y]}set(e,n,r,s,i,o,a,c,l,u,h,f,p,d,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=s|0,this.v2l=i|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|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,l)=>z[l]=c),z.set(ue,16);let{h:s,l:i}=ll(BigInt(this.length));z[24]=ue[8]^i,z[25]=ue[9]^s,r&&(z[28]=~z[28],z[29]=~z[29]);let o=0;const a=d1;for(let c=0;c<12;c++)nn(0,4,8,12,e,n+2*a[o++]),rn(0,4,8,12,e,n+2*a[o++]),nn(1,5,9,13,e,n+2*a[o++]),rn(1,5,9,13,e,n+2*a[o++]),nn(2,6,10,14,e,n+2*a[o++]),rn(2,6,10,14,e,n+2*a[o++]),nn(3,7,11,15,e,n+2*a[o++]),rn(3,7,11,15,e,n+2*a[o++]),nn(0,5,10,15,e,n+2*a[o++]),rn(0,5,10,15,e,n+2*a[o++]),nn(1,6,11,12,e,n+2*a[o++]),rn(1,6,11,12,e,n+2*a[o++]),nn(2,7,8,13,e,n+2*a[o++]),rn(2,7,8,13,e,n+2*a[o++]),nn(3,4,9,14,e,n+2*a[o++]),rn(3,4,9,14,e,n+2*a[o++]);this.v0l^=z[0]^z[16],this.v0h^=z[1]^z[17],this.v1l^=z[2]^z[18],this.v1h^=z[3]^z[19],this.v2l^=z[4]^z[20],this.v2h^=z[5]^z[21],this.v3l^=z[6]^z[22],this.v3h^=z[7]^z[23],this.v4l^=z[8]^z[24],this.v4h^=z[9]^z[25],this.v5l^=z[10]^z[26],this.v5h^=z[11]^z[27],this.v6l^=z[12]^z[28],this.v6h^=z[13]^z[29],this.v7l^=z[14]^z[30],this.v7h^=z[15]^z[31],Ke(z)}destroy(){this.destroyed=!0,Ke(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const w1=Om(t=>new y1(t));/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function gu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yu(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 bs(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function br(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function vs(t){if(!Array.isArray(t))throw new Error("array expected")}function Es(t,e){if(!yu(!0,e))throw new Error(`${t}: array of strings expected`)}function wu(t,e){if(!yu(!1,e))throw new Error(`${t}: array of numbers expected`)}function mu(...t){const e=i=>i,n=(i,o)=>a=>i(o(a)),r=t.map(i=>i.encode).reduceRight(n,e),s=t.map(i=>i.decode).reduce(n,e);return{encode:r,decode:s}}function bu(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Es("alphabet",e);const r=new Map(e.map((s,i)=>[s,i]));return{encode:s=>(vs(s),s.map(i=>{if(!Number.isSafeInteger(i)||i<0||i>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${i}". Allowed: ${t}`);return e[i]})),decode:s=>(vs(s),s.map(i=>{bs("alphabet.decode",i);const o=r.get(i);if(o===void 0)throw new Error(`Unknown letter: "${i}". Allowed: ${t}`);return o}))}}function vu(t=""){return bs("join",t),{encode:e=>(Es("join.decode",e),e.join(t)),decode:e=>(bs("join.decode",e),e.split(t))}}function m1(t,e="="){return br(t),bs("padding",e),{encode(n){for(Es("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Es("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 Eu(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(vs(t),!t.length)return[];let r=0;const s=[],i=Array.from(t,a=>{if(br(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=i.length;for(;;){let a=0,c=!0;for(let l=r;l<o;l++){const u=i[l],h=e*a,f=h+u;if(!Number.isSafeInteger(f)||h/e!==a||f-u!==h)throw new Error("convertRadix: carry overflow");const p=f/n;a=f%n;const d=Math.floor(p);if(i[l]=d,!Number.isSafeInteger(d)||d*n+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:r=l;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}const xu=(t,e)=>e===0?t:xu(e,t%e),xs=(t,e)=>t+(e-xu(t,e)),yo=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function _u(t,e,n,r){if(vs(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(xs(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${xs(e,n)}`);let s=0,i=0;const o=yo[e],a=yo[n]-1,c=[];for(const l of t){if(br(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(s=s<<e|l,i+e>32)throw new Error(`convertRadix2: carry overflow pos=${i} from=${e}`);for(i+=e;i>=n;i-=n)c.push((s>>i-n&a)>>>0);const u=yo[i];if(u===void 0)throw new Error("invalid carry");s&=u-1}if(s=s<<n-i&a,!r&&i>=e)throw new Error("Excess padding");if(!r&&s>0)throw new Error(`Non-zero padding: ${s}`);return r&&i>0&&c.push(s>>>0),c}function b1(t){br(t);const e=2**8;return{encode:n=>{if(!gu(n))throw new Error("radix.encode input should be Uint8Array");return Eu(Array.from(n),e,t)},decode:n=>(wu("radix.decode",n),Uint8Array.from(Eu(n,t,e)))}}function v1(t,e=!1){if(br(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(xs(8,t)>32||xs(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!gu(n))throw new Error("radix2.encode input should be Uint8Array");return _u(Array.from(n),8,t,!e)},decode:n=>(wu("radix2.decode",n),Uint8Array.from(_u(n,t,8,e)))}}const E1=mu(v1(5),bu("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),m1(5),vu("")),vr=(t=>mu(b1(58),bu(t),vu("")))("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function x1(t){return Ub(_1(t))}function _1(t){const{payload:e,signature:n}=t,{r,s,yParity:i}=n,a=new a1.Signature(BigInt(r),BigInt(s)).addRecoveryBit(i).recoverPublicKey(to(e).substring(2));return Ab(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Iu(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function mo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Ue(t,...e){if(!Iu(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 Su(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 I1(t,e){Ue(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function sn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function zn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function S1(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const D1=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function A1(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function bo(t){if(typeof t=="string")t=A1(t);else if(Iu(t))t=vo(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function T1(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function O1(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 $1=(t,e)=>{function n(r,...s){if(Ue(r),!D1)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?Ue(u):Ue(u,t.nonceLength)}const i=t.tagLength;i&&s[1]!==void 0&&Ue(s[1]);const o=e(r,...s),a=(u,h)=>{if(h!==void 0){if(u!==2)throw new Error("cipher output not supported");Ue(h)}};let c=!1;return{encrypt(u,h){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,Ue(u),a(o.encrypt.length,h),o.encrypt(u,h)},decrypt(u,h){if(Ue(u),i&&u.length<i)throw new Error("invalid ciphertext length: smaller than tagLength="+i);return a(o.decrypt.length,h),o.decrypt(u,h)}}}return Object.assign(n,t),n};function Du(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&&!B1(e))throw new Error("invalid output, must be aligned");return e}function Au(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const s=BigInt(32),i=BigInt(4294967295),o=Number(n>>s&i),a=Number(n&i),c=4,l=0;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function R1(t,e,n){wo(n);const r=new Uint8Array(16),s=S1(r);return Au(s,0,BigInt(e),n),Au(s,8,BigInt(t),n),r}function B1(t){return t.byteOffset%4===0}function vo(t){return Uint8Array.from(t)}function P1(t){const e=t.length;let n=0,r=0;for(;r<e;){let s=t.charCodeAt(r++);if((s&4294967168)===0){n++;continue}else if((s&4294965248)===0)n+=2;else{if(s>=55296&&s<=56319&&r<e){const i=t.charCodeAt(r);(i&64512)===56320&&(++r,s=((s&1023)<<10)+(i&1023)+65536)}(s&4294901760)===0?n+=3:n+=4}}return n}function C1(t,e,n){const r=t.length;let s=n,i=0;for(;i<r;){let o=t.charCodeAt(i++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&i<r){const a=t.charCodeAt(i);(a&64512)===56320&&(++i,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const N1=new TextEncoder,U1=50;function k1(t,e,n){N1.encodeInto(t,e.subarray(n))}function L1(t,e,n){t.length>U1?k1(t,e,n):C1(t,e,n)}const F1=4096;function Tu(t,e,n){let r=e;const s=r+n,i=[];let o="";for(;r<s;){const a=t[r++];if((a&128)===0)i.push(a);else if((a&224)===192){const c=t[r++]&63;i.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,l=t[r++]&63;i.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[r++]&63,l=t[r++]&63,u=t[r++]&63;let h=(a&7)<<18|c<<12|l<<6|u;h>65535&&(h-=65536,i.push(h>>>10&1023|55296),h=56320|h&1023),i.push(h)}else i.push(a);i.length>=F1&&(o+=String.fromCharCode(...i),i.length=0)}return i.length>0&&(o+=String.fromCharCode(...i)),o}const M1=new TextDecoder,q1=200;function j1(t,e,n){const r=t.subarray(e,e+n);return M1.decode(r)}function z1(t,e,n){return n>q1?j1(t,e,n):Tu(t,e,n)}class _s{type;data;constructor(e,n){this.type=e,this.data=n}}class Me extends Error{constructor(e){super(e);const n=Object.create(Me.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Me.name})}}const Er=4294967295;function V1(t,e,n){const r=n/4294967296,s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function Ou(t,e,n){const r=Math.floor(n/4294967296),s=n;t.setUint32(e,r),t.setUint32(e+4,s)}function $u(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function K1(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const H1=-1,W1=4294967296-1,G1=17179869184-1;function Y1({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=G1)if(e===0&&t<=W1){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,s=new Uint8Array(8),i=new DataView(s.buffer);return i.setUint32(0,e<<2|n&3),i.setUint32(4,r),s}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),Ou(r,4,t),n}}function Z1(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,s=Math.floor(r/1e9);return{sec:n+s,nsec:r-s*1e9}}function X1(t){if(t instanceof Date){const e=Z1(t);return Y1(e)}else return null}function J1(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),s=(n&3)*4294967296+r,i=n>>>2;return{sec:s,nsec:i}}case 12:{const n=$u(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Me(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Q1(t){const e=J1(t);return new Date(e.sec*1e3+e.nsec/1e6)}const ev={type:H1,encode:X1,decode:Q1};class Is{static defaultCodec=new Is;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(ev)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const s=-1-e;this.builtInEncoders[s]=n,this.builtInDecoders[s]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const s=this.builtInEncoders[r];if(s!=null){const i=s(e,n);if(i!=null){const o=-1-r;return new _s(o,i)}}}for(let r=0;r<this.encoders.length;r++){const s=this.encoders[r];if(s!=null){const i=s(e,n);if(i!=null){const o=r;return new _s(o,i)}}}return e instanceof _s?e:null}decode(e,n,r){const s=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return s?s(e,n,r):new _s(n,e)}}function tv(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Eo(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):tv(t)?new Uint8Array(t):Uint8Array.from(t)}const nv=100,rv=2048;class xo{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Is.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??nv,this.initialBufferSize=e?.initialBufferSize??rv,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 xo({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),s=new DataView(n);r.set(this.bytes),this.view=s,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=P1(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),L1(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=Eo(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 s of e)this.doEncode(s,n+1)}countWithoutUndefined(e,n){let r=0;for(const s of n)e[s]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const i of r){const o=e[i];this.ignoreUndefined&&o===void 0||(this.encodeString(i),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),s=r.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(r);return}const 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),V1(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Ou(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 sv(t,e){return new xo(e).encodeSharedRef(t)}function _o(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const iv=16,ov=16;class av{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=iv,n=ov){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 s=this.caches[r-1];e:for(const i of s){const o=i.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return i.str}return null}store(e,n){const r=this.caches[e.length-1],s={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=s:r.push(s)}decode(e,n,r){const s=this.find(e,n,r);if(s!=null)return this.hit++,s;this.miss++;const i=Tu(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,i),i}}const Io="array",xr="map_key",Ru="map_value",cv=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Me("The type of key must be string or number but "+typeof t)};class lv{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Io,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=xr,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===Io){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===xr||e.type===Ru){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 _r=-1,So=new DataView(new ArrayBuffer(0)),uv=new Uint8Array(So.buffer);try{So.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 Bu=new RangeError("Insufficient data"),hv=new av;class Do{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=So;bytes=uv;headByte=_r;stack=new lv;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Is.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??Er,this.maxBinLength=e?.maxBinLength??Er,this.maxArrayLength=e?.maxArrayLength??Er,this.maxMapLength=e?.maxMapLength??Er,this.maxExtLength=e?.maxExtLength??Er,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:hv,this.mapKeyConverter=e?.mapKeyConverter??cv}clone(){return new Do({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=_r,this.stack.reset()}setBuffer(e){const n=Eo(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===_r&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=Eo(e),s=new Uint8Array(n.length+r.length);s.set(n),s.set(r,n.length),this.setBuffer(s)}}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:s,pos:i,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${_o(s)} at ${o} (${i} 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,s=-1;for await(const i of e){if(n&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(i),r&&(s=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else{const s=e-160;n=this.decodeString(s,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 s=this.lookU8();n=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();n=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();n=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else n=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else n={}}else if(e===196){const s=this.lookU8();n=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();n=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();n=this.decodeBinary(s,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 s=this.lookU8();n=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();n=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();n=this.decodeExtension(s,4)}else throw new Me(`Unrecognized type byte: ${_o(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const s=r.top();if(s.type===Io)if(s.array[s.position]=n,s.position++,s.position===s.size)n=s.array,r.release(s);else continue e;else if(s.type===xr){if(n==="__proto__")throw new Me("The key __proto__ is not allowed");s.key=this.mapKeyConverter(n),s.type=Ru;continue e}else if(s.map[s.key]=n,s.readCount++,s.readCount===s.size)n=s.map,r.release(s);else{s.key=null,s.type=xr;continue e}}return n}}readHeadByte(){return this.headByte===_r&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=_r}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 Me(`Unrecognized array type byte: ${_o(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Me(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Me(`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 Me(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Bu;const r=this.pos+n;let s;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?s=this.keyDecoder.decode(this.bytes,r,e):s=z1(this.bytes,r,e),this.pos+=n+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===xr:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Me(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Bu;const r=this.pos+n,s=this.bytes.subarray(r,r+e);return this.pos+=n+e,s}decodeExtension(e,n){if(e>this.maxExtLength)throw new Me(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),s=this.decodeBinary(e,n+1);return this.extensionCodec.decode(s,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=K1(this.view,this.pos);return this.pos+=8,e}readI64(){const e=$u(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 fv(t,e){return new Do(e).decode(t)}function Rt(t,e){e||(e=t.reduce((s,i)=>s+i.length,0));const n=Jc(e);let r=0;for(const s of t)n.set(s,r),r+=s.length;return Mi(n)}function he(t,e="utf8"){const n=tl[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 Pu=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),dv=Pu("expand 16-byte k"),pv=Pu("expand 32-byte k"),gv=sn(dv),yv=sn(pv);function X(t,e){return t<<e|t>>>32-e}function Ao(t){return t.byteOffset%4===0}const Ss=64,wv=16,Cu=2**32-1,Nu=new Uint32Array;function mv(t,e,n,r,s,i,o,a){const c=s.length,l=new Uint8Array(Ss),u=sn(l),h=Ao(s)&&Ao(i),f=h?sn(s):Nu,p=h?sn(i):Nu;for(let d=0;d<c;o++){if(t(e,n,r,u,o,a),o>=Cu)throw new Error("arx: counter overflow");const g=Math.min(Ss,c-d);if(h&&g===Ss){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,A;b<wv;b++)A=y+b,p[A]=f[A]^u[b];d+=Ss;continue}for(let y=0,b;y<g;y++)b=d+y,i[b]=s[b]^l[y];d+=g}}function bv(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:s,counterRight:i,rounds:o}=T1({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return mo(s),mo(o),wo(i),wo(n),(a,c,l,u,h=0)=>{Ue(a),Ue(c),Ue(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),Ue(u),mo(h),h<0||h>=Cu)throw new Error("arx: counter overflow");if(u.length<f)throw new Error(`arx: output (${u.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=vo(a)),y=yv;else if(d===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=gv,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);Ao(c)||p.push(c=vo(c));const b=sn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,b,sn(c.subarray(0,16)),b),c=c.subarray(16)}const A=16-s;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){const m=new Uint8Array(12);m.set(c,i?0:12-c.length),c=m,p.push(c)}const w=sn(c);return mv(t,y,b,w,l,u,h,o),zn(...p),u}}const ve=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class vv{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=bo(e),Ue(e,32);const n=ve(e,0),r=ve(e,2),s=ve(e,4),i=ve(e,6),o=ve(e,8),a=ve(e,10),c=ve(e,12),l=ve(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|s<<6)&7939,this.r[3]=(s>>>7|i<<9)&8191,this.r[4]=(i>>>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|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=ve(e,16+2*u)}process(e,n,r=!1){const s=r?0:2048,{h:i,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],h=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],b=ve(e,n+0),A=ve(e,n+2),w=ve(e,n+4),m=ve(e,n+6),x=ve(e,n+8),_=ve(e,n+10),T=ve(e,n+12),$=ve(e,n+14);let P=i[0]+(b&8191),k=i[1]+((b>>>13|A<<3)&8191),U=i[2]+((A>>>10|w<<6)&8191),N=i[3]+((w>>>7|m<<9)&8191),S=i[4]+((m>>>4|x<<12)&8191),R=i[5]+(x>>>1&8191),v=i[6]+((x>>>14|_<<2)&8191),E=i[7]+((_>>>11|T<<5)&8191),D=i[8]+((T>>>8|$<<8)&8191),B=i[9]+($>>>5|s),I=0,O=I+P*a+k*(5*y)+U*(5*g)+N*(5*d)+S*(5*p);I=O>>>13,O&=8191,O+=R*(5*f)+v*(5*h)+E*(5*u)+D*(5*l)+B*(5*c),I+=O>>>13,O&=8191;let C=I+P*c+k*a+U*(5*y)+N*(5*g)+S*(5*d);I=C>>>13,C&=8191,C+=R*(5*p)+v*(5*f)+E*(5*h)+D*(5*u)+B*(5*l),I+=C>>>13,C&=8191;let L=I+P*l+k*c+U*a+N*(5*y)+S*(5*g);I=L>>>13,L&=8191,L+=R*(5*d)+v*(5*p)+E*(5*f)+D*(5*h)+B*(5*u),I+=L>>>13,L&=8191;let V=I+P*u+k*l+U*c+N*a+S*(5*y);I=V>>>13,V&=8191,V+=R*(5*g)+v*(5*d)+E*(5*p)+D*(5*f)+B*(5*h),I+=V>>>13,V&=8191;let j=I+P*h+k*u+U*l+N*c+S*a;I=j>>>13,j&=8191,j+=R*(5*y)+v*(5*g)+E*(5*d)+D*(5*p)+B*(5*f),I+=j>>>13,j&=8191;let q=I+P*f+k*h+U*u+N*l+S*c;I=q>>>13,q&=8191,q+=R*a+v*(5*y)+E*(5*g)+D*(5*d)+B*(5*p),I+=q>>>13,q&=8191;let K=I+P*p+k*f+U*h+N*u+S*l;I=K>>>13,K&=8191,K+=R*c+v*a+E*(5*y)+D*(5*g)+B*(5*d),I+=K>>>13,K&=8191;let W=I+P*d+k*p+U*f+N*h+S*u;I=W>>>13,W&=8191,W+=R*l+v*c+E*a+D*(5*y)+B*(5*g),I+=W>>>13,W&=8191;let G=I+P*g+k*d+U*p+N*f+S*h;I=G>>>13,G&=8191,G+=R*u+v*l+E*c+D*a+B*(5*y),I+=G>>>13,G&=8191;let H=I+P*y+k*g+U*d+N*p+S*f;I=H>>>13,H&=8191,H+=R*h+v*u+E*l+D*c+B*a,I+=H>>>13,H&=8191,I=(I<<2)+I|0,I=I+O|0,O=I&8191,I=I>>>13,C+=I,i[0]=O,i[1]=C,i[2]=L,i[3]=V,i[4]=j,i[5]=q,i[6]=K,i[7]=W,i[8]=G,i[9]=H}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,r[0]=e[0]+5,s=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+s,s=r[a]>>>13,r[a]&=8191;r[9]-=8192;let i=(s^1)-1;for(let a=0;a<10;a++)r[a]&=i;i=~i;for(let a=0;a<10;a++)e[a]=e[a]&i|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;zn(r)}update(e){Su(this),e=bo(e),Ue(e);const{buffer:n,blockLen:r}=this,s=e.length;for(let i=0;i<s;){const o=Math.min(r-this.pos,s-i);if(o===r){for(;r<=s-i;i+=r)this.process(e,i);continue}n.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){zn(this.h,this.r,this.buffer,this.pad)}digestInto(e){Su(this),I1(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:s}=this;if(s){for(n[s++]=1;s<16;s++)n[s]=0;this.process(n,0,!0)}this.finalize();let i=0;for(let o=0;o<8;o++)e[i++]=r[o]>>>0,e[i++]=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 Ev(t){const e=(r,s)=>t(s).update(bo(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const xv=Ev(t=>new vv(t));function _v(t,e,n,r,s,i=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],b=e[7],A=s,w=n[0],m=n[1],x=n[2],_=o,T=a,$=c,P=l,k=u,U=h,N=f,S=p,R=d,v=g,E=y,D=b,B=A,I=w,O=m,C=x;for(let V=0;V<i;V+=2)_=_+k|0,B=X(B^_,16),R=R+B|0,k=X(k^R,12),_=_+k|0,B=X(B^_,8),R=R+B|0,k=X(k^R,7),T=T+U|0,I=X(I^T,16),v=v+I|0,U=X(U^v,12),T=T+U|0,I=X(I^T,8),v=v+I|0,U=X(U^v,7),$=$+N|0,O=X(O^$,16),E=E+O|0,N=X(N^E,12),$=$+N|0,O=X(O^$,8),E=E+O|0,N=X(N^E,7),P=P+S|0,C=X(C^P,16),D=D+C|0,S=X(S^D,12),P=P+S|0,C=X(C^P,8),D=D+C|0,S=X(S^D,7),_=_+U|0,C=X(C^_,16),E=E+C|0,U=X(U^E,12),_=_+U|0,C=X(C^_,8),E=E+C|0,U=X(U^E,7),T=T+N|0,B=X(B^T,16),D=D+B|0,N=X(N^D,12),T=T+N|0,B=X(B^T,8),D=D+B|0,N=X(N^D,7),$=$+S|0,I=X(I^$,16),R=R+I|0,S=X(S^R,12),$=$+S|0,I=X(I^$,8),R=R+I|0,S=X(S^R,7),P=P+k|0,O=X(O^P,16),v=v+O|0,k=X(k^v,12),P=P+k|0,O=X(O^P,8),v=v+O|0,k=X(k^v,7);let L=0;r[L++]=o+_|0,r[L++]=a+T|0,r[L++]=c+$|0,r[L++]=l+P|0,r[L++]=u+k|0,r[L++]=h+U|0,r[L++]=f+N|0,r[L++]=p+S|0,r[L++]=d+R|0,r[L++]=g+v|0,r[L++]=y+E|0,r[L++]=b+D|0,r[L++]=A+B|0,r[L++]=w+I|0,r[L++]=m+O|0,r[L++]=x+C|0}const Iv=bv(_v,{counterRight:!1,counterLength:4,allowShortKeys:!1}),Sv=new Uint8Array(16),Uu=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(Sv.subarray(n))},Dv=new Uint8Array(32);function ku(t,e,n,r,s){const i=t(e,n,Dv),o=xv.create(i);s&&Uu(o,s),Uu(o,r);const a=R1(r.length,s?s.length:0,!0);o.update(a);const c=o.digest();return zn(i,a),c}const Lu=$1({blockSize:64,nonceLength:12,tagLength:16},(t=>(e,n,r)=>({encrypt(i,o){const a=i.length;o=Du(a+16,o,!1),o.set(i);const c=o.subarray(0,-16);t(e,n,c,c,1);const l=ku(t,e,n,c,r);return o.set(l,a),zn(l),o},decrypt(i,o){o=Du(i.length-16,o,!1);const a=i.subarray(0,-16),c=i.subarray(-16),l=ku(t,e,n,a,r);if(!O1(c,l))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),t(e,n,o,o,1),zn(l),o}}))(Iv));function Av(t,e,n){return cs(t),n===void 0&&(n=new Uint8Array(t.outputLen)),mr(t,nt(n),nt(e))}const To=Uint8Array.from([0]),Fu=Uint8Array.of();function Tv(t,e,n,r=32){cs(t),ft(r);const s=t.outputLen;if(r>255*s)throw new Error("Length should be <= 255*HashLen");const i=Math.ceil(r/s);n===void 0&&(n=Fu);const o=new Uint8Array(i*s),a=mr.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<i;u++)To[0]=u+1,c.update(u===0?Fu:l).update(n).update(To).digestInto(l),o.set(l,s*u),a._cloneInto(c);return a.destroy(),c.destroy(),Ke(l,To),o.slice(0,r)}const Ov=(t,e,n,r,s)=>Tv(t,Av(t,e,n),r,s);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Oo=BigInt(0),$o=BigInt(1);function Ds(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function En(t,e,n=""){const r=as(t),s=t?.length,i=e!==void 0;if(!r||i&&s!==e){const o=n&&`"${n}" `,a=i?` of length ${e}`:"",c=r?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function As(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Mu(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Oo:BigInt("0x"+t)}function Ts(t){return Mu(qn(t))}function Os(t){return tt(t),Mu(qn(Uint8Array.from(t).reverse()))}function Ro(t,e){return ls(t.toString(16).padStart(e*2,"0"))}function Bo(t,e){return Ro(t,e).reverse()}function Ae(t,e,n){let r;if(typeof e=="string")try{r=ls(e)}catch(i){throw new Error(t+" must be hex string or Uint8Array, cause: "+i)}else if(as(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=r.length;if(typeof n=="number"&&s!==n)throw new Error(t+" of length "+n+" expected, got "+s);return r}const Po=t=>typeof t=="bigint"&&Oo<=t;function $v(t,e,n){return Po(t)&&Po(e)&&Po(n)&&e<=t&&t<n}function Co(t,e,n,r){if(!$v(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function qu(t){let e;for(e=0;t>Oo;t>>=$o,e+=1);return e}const Ir=t=>($o<<BigInt(t))-$o;function Rv(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=p=>new Uint8Array(p),s=p=>Uint8Array.of(p);let i=r(t),o=r(t),a=0;const c=()=>{i.fill(1),o.fill(0),a=0},l=(...p)=>n(o,i,...p),u=(p=r(0))=>{o=l(s(0),p),i=l(),p.length!==0&&(o=l(s(1),p),i=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let p=0;const d=[];for(;p<e;){i=l();const g=i.slice();d.push(g),p+=i.length}return St(...d)};return(p,d)=>{c(),u(p);let g;for(;!(g=d(h()));)u();return c(),g}}function $s(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(s,i,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==i||a===null)throw new Error(`param "${s}" is invalid: expected ${i}, got ${c}`)}Object.entries(e).forEach(([s,i])=>r(s,i,!1)),Object.entries(n).forEach(([s,i])=>r(s,i,!0))}function ju(t){const e=new WeakMap;return(n,...r)=>{const s=e.get(n);if(s!==void 0)return s;const i=t(n,...r);return e.set(n,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ke=BigInt(0),Oe=BigInt(1),xn=BigInt(2),zu=BigInt(3),Vu=BigInt(4),Ku=BigInt(5),Bv=BigInt(7),Hu=BigInt(8),Pv=BigInt(9),Wu=BigInt(16);function qe(t,e){const n=t%e;return n>=ke?n:e+n}function rt(t,e,n){let r=t;for(;e-- >ke;)r*=r,r%=n;return r}function Gu(t,e){if(t===ke)throw new Error("invert: expected non-zero number");if(e<=ke)throw new Error("invert: expected positive modulus, got "+e);let n=qe(t,e),r=e,s=ke,i=Oe;for(;n!==ke;){const a=r/n,c=r%n,l=s-i*a;r=n,n=c,s=i,i=l}if(r!==Oe)throw new Error("invert: does not exist");return qe(s,e)}function No(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Yu(t,e){const n=(t.ORDER+Oe)/Vu,r=t.pow(e,n);return No(t,r,e),r}function Cv(t,e){const n=(t.ORDER-Ku)/Hu,r=t.mul(e,xn),s=t.pow(r,n),i=t.mul(e,s),o=t.mul(t.mul(i,xn),s),a=t.mul(i,t.sub(o,t.ONE));return No(t,a,e),a}function Nv(t){const e=on(t),n=Zu(t),r=n(e,e.neg(e.ONE)),s=n(e,r),i=n(e,e.neg(r)),o=(t+Bv)/Wu;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const h=a.mul(l,s),f=a.mul(l,i),p=a.eql(a.sqr(u),c),d=a.eql(a.sqr(h),c);l=a.cmov(l,u,p),u=a.cmov(f,h,d);const g=a.eql(a.sqr(u),c),y=a.cmov(l,u,g);return No(a,y,c),y}}function Zu(t){if(t<zu)throw new Error("sqrt is not defined for small field");let e=t-Oe,n=0;for(;e%xn===ke;)e/=xn,n++;let r=xn;const s=on(t);for(;Ju(s,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Yu;let i=s.pow(r,e);const o=(e+Oe)/xn;return function(c,l){if(c.is0(l))return l;if(Ju(c,l)!==1)throw new Error("Cannot find square root");let u=n,h=c.mul(c.ONE,i),f=c.pow(l,e),p=c.pow(l,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===u)throw new Error("Cannot find square root");const y=Oe<<BigInt(u-d-1),b=c.pow(h,y);u=d,h=c.sqr(b),f=c.mul(f,h),p=c.mul(p,b)}return p}}function Uv(t){return t%Vu===zu?Yu:t%Hu===Ku?Cv:t%Wu===Pv?Nv(t):Zu(t)}const kv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Lv(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=kv.reduce((r,s)=>(r[s]="function",r),e);return $s(t,n),t}function Fv(t,e,n){if(n<ke)throw new Error("invalid exponent, negatives unsupported");if(n===ke)return t.ONE;if(n===Oe)return e;let r=t.ONE,s=e;for(;n>ke;)n&Oe&&(r=t.mul(r,s)),s=t.sqr(s),n>>=Oe;return r}function Xu(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),i=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),i),r}function Ju(t,e){const n=(t.ORDER-Oe)/xn,r=t.pow(e,n),s=t.eql(r,t.ONE),i=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!s&&!i&&!o)throw new Error("invalid Legendre symbol result");return s?1:i?0:-1}function Qu(t,e){e!==void 0&&ft(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function on(t,e,n=!1,r={}){if(t<=ke)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,i,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(s=f.BITS),f.sqrt&&(i=f.sqrt),typeof f.isLE=="boolean"&&(n=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),r.sqrt&&(i=r.sqrt);const{nBitLength:c,nByteLength:l}=Qu(t,s);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:l,MASK:Ir(c),ZERO:ke,ONE:Oe,allowedLengths:a,create:f=>qe(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return ke<=f&&f<t},is0:f=>f===ke,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&Oe)===Oe,neg:f=>qe(-f,t),eql:(f,p)=>f===p,sqr:f=>qe(f*f,t),add:(f,p)=>qe(f+p,t),sub:(f,p)=>qe(f-p,t),mul:(f,p)=>qe(f*p,t),pow:(f,p)=>Fv(h,f,p),div:(f,p)=>qe(f*Gu(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>Gu(f,t),sqrt:i||(f=>(u||(u=Uv(t)),u(h,f))),toBytes:f=>n?Bo(f,l):Ro(f,l),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const g=new Uint8Array(l);g.set(f,n?0:g.length-f.length),f=g}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let d=n?Os(f):Ts(f);if(o&&(d=qe(d,t)),!p&&!h.isValid(d))throw new Error("invalid field element: outside of range 0..ORDER");return d},invertBatch:f=>Xu(h,f),cmov:(f,p,d)=>d?p:f});return Object.freeze(h)}function eh(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 th(t){const e=eh(t);return e+Math.ceil(e/2)}function Mv(t,e,n=!1){const r=t.length,s=eh(e),i=th(e);if(r<16||r<i||r>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+r);const o=n?Os(t):Ts(t),a=qe(o,e-Oe)+Oe;return n?Bo(a,s):Ro(a,s)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vn=BigInt(0),_n=BigInt(1);function Rs(t,e){const n=e.negate();return t?n:e}function Uo(t,e){const n=Xu(t.Fp,e.map(r=>r.Z));return e.map((r,s)=>t.fromAffine(r.toAffine(n[s])))}function nh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ko(t,e){nh(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),s=2**t,i=Ir(t),o=BigInt(t);return{windows:n,windowSize:r,mask:i,maxNumber:s,shiftBy:o}}function rh(t,e,n){const{windowSize:r,mask:s,maxNumber:i,shiftBy:o}=n;let a=Number(t&s),c=t>>o;a>r&&(a-=i,c+=_n);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:p,offsetF:l}}function qv(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 jv(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 Lo=new WeakMap,sh=new WeakMap;function Fo(t){return sh.get(t)||1}function ih(t){if(t!==Vn)throw new Error("invalid wNAF")}class zv{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 s=e;for(;n>Vn;)n&_n&&(r=r.add(s)),s=s.double(),n>>=_n;return r}precomputeWindow(e,n){const{windows:r,windowSize:s}=ko(n,this.bits),i=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,i.push(a);for(let l=1;l<s;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let s=this.ZERO,i=this.BASE;const o=ko(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:p}=rh(r,a,o);r=c,u?i=i.add(Rs(f,n[p])):s=s.add(Rs(h,n[l]))}return ih(r),{p:s,f:i}}wNAFUnsafe(e,n,r,s=this.ZERO){const i=ko(e,this.bits);for(let o=0;o<i.windows&&r!==Vn;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=rh(r,o,i);if(r=a,!l){const h=n[c];s=s.add(u?h.negate():h)}}return ih(r),s}getPrecomputes(e,n,r){let s=Lo.get(n);return s||(s=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(s=r(s)),Lo.set(n,s))),s}cached(e,n,r){const s=Fo(e);return this.wNAF(s,this.getPrecomputes(s,e,r),n)}unsafe(e,n,r,s){const i=Fo(e);return i===1?this._unsafeLadder(e,n,s):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),n,s)}createCache(e,n){nh(n,this.bits),sh.set(e,n),Lo.delete(e)}hasCache(e){return Fo(e)!==1}}function Vv(t,e,n,r){let s=e,i=t.ZERO,o=t.ZERO;for(;n>Vn||r>Vn;)n&_n&&(i=i.add(s)),r&_n&&(o=o.add(s)),s=s.double(),n>>=_n,r>>=_n;return{p1:i,p2:o}}function Kv(t,e,n,r){qv(n,t),jv(r,e);const s=n.length,i=r.length;if(s!==i)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=qu(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Ir(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){u.fill(o);for(let g=0;g<i;g++){const y=r[g],b=Number(y>>BigInt(p)&l);u[b]=u[b].add(n[g])}let d=o;for(let g=u.length-1,y=o;g>0;g--)y=y.add(u[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 oh(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Lv(e),e}else return on(t,{isLE:n})}function Hv(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 l=e[c];if(!(typeof l=="bigint"&&l>Vn))throw new Error(`CURVE.${c} must be positive bigint`)}const s=oh(e.p,n.Fp,r),i=oh(e.n,n.Fn,r),a=["Gx","Gy","a","b"];for(const c of a)if(!s.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:s,Fn:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */BigInt(0),BigInt(1),BigInt(2),BigInt(8),wl("HashToScalar-");/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Sr=BigInt(0),Kn=BigInt(1),Bs=BigInt(2);function Wv(t){return $s(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function Gv(t){const e=Wv(t),{P:n,type:r,adjustScalarBytes:s,powPminus2:i,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||Zt,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?Bs**BigInt(254):Bs**BigInt(447),d=a?BigInt(8)*Bs**BigInt(251)-Kn:BigInt(4)*Bs**BigInt(445)-Kn,g=p+d+Kn,y=S=>qe(S,n),b=A(h);function A(S){return Bo(y(S),u)}function w(S){const R=Ae("u coordinate",S,u);return a&&(R[31]&=127),y(Os(R))}function m(S){return Os(s(Ae("scalar",S,u)))}function x(S,R){const v=$(w(R),m(S));if(v===Sr)throw new Error("invalid private or public key received");return A(v)}function _(S){return x(S,b)}function T(S,R,v){const E=y(S*(R-v));return R=y(R-E),v=y(v+E),{x_2:R,x_3:v}}function $(S,R){Co("u",S,Sr,n),Co("scalar",R,p,g);const v=R,E=S;let D=Kn,B=Sr,I=S,O=Kn,C=Sr;for(let V=BigInt(l-1);V>=Sr;V--){const j=v>>V&Kn;C^=j,{x_2:D,x_3:I}=T(C,D,I),{x_2:B,x_3:O}=T(C,B,O),C=j;const q=D+B,K=y(q*q),W=D-B,G=y(W*W),H=K-G,Z=I+O,ae=I-O,ce=y(ae*q),we=y(Z*W),at=ce+we,ct=ce-we;I=y(at*at),O=y(E*y(ct*ct)),D=y(K*G),B=y(H*(K+y(f*H)))}({x_2:D,x_3:I}=T(C,D,I)),{x_2:B,x_3:O}=T(C,B,O);const L=i(B);return y(D*L)}const P={secretKey:u,publicKey:u,seed:u},k=(S=c(u))=>(tt(S,P.seed),S);function U(S){const R=k(S);return{secretKey:R,publicKey:_(R)}}return{keygen:U,getSharedSecret:(S,R)=>x(S,R),getPublicKey:S=>_(S),scalarMult:x,scalarMultBase:_,utils:{randomSecretKey:k,randomPrivateKey:k},GuBytes:b.slice(),lengths:P}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Yv=BigInt(1),ah=BigInt(2),Zv=BigInt(3),Xv=BigInt(5),Jv=BigInt(8),ch=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Qv={p:ch,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:Jv,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eE(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),s=BigInt(80),i=ch,a=t*t%i*t%i,c=rt(a,ah,i)*a%i,l=rt(c,Yv,i)*t%i,u=rt(l,Xv,i)*l%i,h=rt(u,e,i)*u%i,f=rt(h,n,i)*h%i,p=rt(f,r,i)*f%i,d=rt(p,s,i)*p%i,g=rt(d,s,i)*p%i,y=rt(g,e,i)*u%i;return{pow_p_5_8:rt(y,ah,i)*t%i,b2:a}}function tE(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const nE=on(Qv.p,{isLE:!0}),Mo=(()=>{const t=nE.ORDER;return Gv({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=eE(e);return qe(rt(n,Zv,t)*r,t)},adjustScalarBytes:tE})})();/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const lh=(t,e)=>(t+(t>=0?e:-e)/uh)/e;function rE(t,e,n){const[[r,s],[i,o]]=e,a=lh(o*t,n),c=lh(-s*t,n);let l=t-a*r-c*i,u=-a*s-c*o;const h=l<Pt,f=u<Pt;h&&(l=-l),f&&(u=-u);const p=Ir(Math.ceil(qu(n)/2))+Hn;if(l<Pt||l>=p||u<Pt||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}function qo(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function jo(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Ds(n.lowS,"lowS"),Ds(n.prehash,"prehash"),n.format!==void 0&&qo(n.format),n}class sE extends Error{constructor(e=""){super(e)}}const Bt={Err:sE,_tlv:{encode:(t,e)=>{const{Err:n}=Bt;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,s=As(r);if(s.length/2&128)throw new n("tlv.encode: long form length too big");const i=r>127?As(s.length/2|128):"";return As(t)+i+s+e},decode(t,e){const{Err:n}=Bt;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 s=e[r++],i=!!(s&128);let o=0;if(!i)o=s;else{const c=s&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 l=e.subarray(r,r+c);if(l.length!==c)throw new n("tlv.decode: length bytes not complete");if(l[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;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}=Bt;if(t<Pt)throw new e("integer: negative integers are not allowed");let n=As(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}=Bt;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 Ts(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Bt,s=Ae("signature",t),{v:i,l:o}=r.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,i),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(l)}},hexFromSig(t){const{_tlv:e,_int:n}=Bt,r=e.encode(2,n.encode(t.r)),s=e.encode(2,n.encode(t.s)),i=r+s;return e.encode(48,i)}},Pt=BigInt(0),Hn=BigInt(1),uh=BigInt(2),Ps=BigInt(3),iE=BigInt(4);function Wn(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let s=Ae("private key",e);try{r=t.fromBytes(s)}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 oE(t,e={}){const n=Hv("weierstrass",t,e),{Fp:r,Fn:s}=n;let i=n.CURVE;const{h:o,n:a}=i;$s(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=fh(r,s);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(N,S,R){const{x:v,y:E}=S.toAffine(),D=r.toBytes(v);if(Ds(R,"isCompressed"),R){u();const B=!r.isOdd(E);return St(hh(B),D)}else return St(Uint8Array.of(4),D,r.toBytes(E))}function f(N){En(N,void 0,"Point");const{publicKey:S,publicKeyUncompressed:R}=l,v=N.length,E=N[0],D=N.subarray(1);if(v===S&&(E===2||E===3)){const B=r.fromBytes(D);if(!r.isValid(B))throw new Error("bad point: is not on curve, wrong x");const I=g(B);let O;try{O=r.sqrt(I)}catch(V){const j=V instanceof Error?": "+V.message:"";throw new Error("bad point: is not on curve, sqrt error"+j)}u();const C=r.isOdd(O);return(E&1)===1!==C&&(O=r.neg(O)),{x:B,y:O}}else if(v===R&&E===4){const B=r.BYTES,I=r.fromBytes(D.subarray(0,B)),O=r.fromBytes(D.subarray(B,B*2));if(!y(I,O))throw new Error("bad point: is not on curve");return{x:I,y:O}}else throw new Error(`bad point: got length ${v}, expected compressed=${S} or uncompressed=${R}`)}const p=e.toBytes||h,d=e.fromBytes||f;function g(N){const S=r.sqr(N),R=r.mul(S,N);return r.add(r.add(R,r.mul(N,i.a)),i.b)}function y(N,S){const R=r.sqr(S),v=g(N);return r.eql(R,v)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const b=r.mul(r.pow(i.a,Ps),iE),A=r.mul(r.sqr(i.b),BigInt(27));if(r.is0(r.add(b,A)))throw new Error("bad curve params: a or b");function w(N,S,R=!1){if(!r.isValid(S)||R&&r.is0(S))throw new Error(`bad point coordinate ${N}`);return S}function m(N){if(!(N instanceof P))throw new Error("ProjectivePoint expected")}function x(N){if(!c||!c.basises)throw new Error("no endo");return rE(N,c.basises,s.ORDER)}const _=ju((N,S)=>{const{X:R,Y:v,Z:E}=N;if(r.eql(E,r.ONE))return{x:R,y:v};const D=N.is0();S==null&&(S=D?r.ONE:r.inv(E));const B=r.mul(R,S),I=r.mul(v,S),O=r.mul(E,S);if(D)return{x:r.ZERO,y:r.ZERO};if(!r.eql(O,r.ONE))throw new Error("invZ was invalid");return{x:B,y:I}}),T=ju(N=>{if(N.is0()){if(e.allowInfinityPoint&&!r.is0(N.Y))return;throw new Error("bad point: ZERO")}const{x:S,y:R}=N.toAffine();if(!r.isValid(S)||!r.isValid(R))throw new Error("bad point: x or y not field elements");if(!y(S,R))throw new Error("bad point: equation left != right");if(!N.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function $(N,S,R,v,E){return R=new P(r.mul(R.X,N),R.Y,R.Z),S=Rs(v,S),R=Rs(E,R),S.add(R)}class P{constructor(S,R,v){this.X=w("x",S),this.Y=w("y",R,!0),this.Z=w("z",v),Object.freeze(this)}static CURVE(){return i}static fromAffine(S){const{x:R,y:v}=S||{};if(!S||!r.isValid(R)||!r.isValid(v))throw new Error("invalid affine point");if(S instanceof P)throw new Error("projective point not allowed");return r.is0(R)&&r.is0(v)?P.ZERO:new P(R,v,r.ONE)}static fromBytes(S){const R=P.fromAffine(d(En(S,void 0,"point")));return R.assertValidity(),R}static fromHex(S){return P.fromBytes(Ae("pointHex",S))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(S=8,R=!0){return U.createCache(this,S),R||this.multiply(Ps),this}assertValidity(){T(this)}hasEvenY(){const{y:S}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(S)}equals(S){m(S);const{X:R,Y:v,Z:E}=this,{X:D,Y:B,Z:I}=S,O=r.eql(r.mul(R,I),r.mul(D,E)),C=r.eql(r.mul(v,I),r.mul(B,E));return O&&C}negate(){return new P(this.X,r.neg(this.Y),this.Z)}double(){const{a:S,b:R}=i,v=r.mul(R,Ps),{X:E,Y:D,Z:B}=this;let I=r.ZERO,O=r.ZERO,C=r.ZERO,L=r.mul(E,E),V=r.mul(D,D),j=r.mul(B,B),q=r.mul(E,D);return q=r.add(q,q),C=r.mul(E,B),C=r.add(C,C),I=r.mul(S,C),O=r.mul(v,j),O=r.add(I,O),I=r.sub(V,O),O=r.add(V,O),O=r.mul(I,O),I=r.mul(q,I),C=r.mul(v,C),j=r.mul(S,j),q=r.sub(L,j),q=r.mul(S,q),q=r.add(q,C),C=r.add(L,L),L=r.add(C,L),L=r.add(L,j),L=r.mul(L,q),O=r.add(O,L),j=r.mul(D,B),j=r.add(j,j),L=r.mul(j,q),I=r.sub(I,L),C=r.mul(j,V),C=r.add(C,C),C=r.add(C,C),new P(I,O,C)}add(S){m(S);const{X:R,Y:v,Z:E}=this,{X:D,Y:B,Z:I}=S;let O=r.ZERO,C=r.ZERO,L=r.ZERO;const V=i.a,j=r.mul(i.b,Ps);let q=r.mul(R,D),K=r.mul(v,B),W=r.mul(E,I),G=r.add(R,v),H=r.add(D,B);G=r.mul(G,H),H=r.add(q,K),G=r.sub(G,H),H=r.add(R,E);let Z=r.add(D,I);return H=r.mul(H,Z),Z=r.add(q,W),H=r.sub(H,Z),Z=r.add(v,E),O=r.add(B,I),Z=r.mul(Z,O),O=r.add(K,W),Z=r.sub(Z,O),L=r.mul(V,H),O=r.mul(j,W),L=r.add(O,L),O=r.sub(K,L),L=r.add(K,L),C=r.mul(O,L),K=r.add(q,q),K=r.add(K,q),W=r.mul(V,W),H=r.mul(j,H),K=r.add(K,W),W=r.sub(q,W),W=r.mul(V,W),H=r.add(H,W),q=r.mul(K,H),C=r.add(C,q),q=r.mul(Z,H),O=r.mul(G,O),O=r.sub(O,q),q=r.mul(G,K),L=r.mul(Z,L),L=r.add(L,q),new P(O,C,L)}subtract(S){return this.add(S.negate())}is0(){return this.equals(P.ZERO)}multiply(S){const{endo:R}=e;if(!s.isValidNot0(S))throw new Error("invalid scalar: out of range");let v,E;const D=B=>U.cached(this,B,I=>Uo(P,I));if(R){const{k1neg:B,k1:I,k2neg:O,k2:C}=x(S),{p:L,f:V}=D(I),{p:j,f:q}=D(C);E=V.add(q),v=$(R.beta,L,j,B,O)}else{const{p:B,f:I}=D(S);v=B,E=I}return Uo(P,[v,E])[0]}multiplyUnsafe(S){const{endo:R}=e,v=this;if(!s.isValid(S))throw new Error("invalid scalar: out of range");if(S===Pt||v.is0())return P.ZERO;if(S===Hn)return v;if(U.hasCache(this))return this.multiply(S);if(R){const{k1neg:E,k1:D,k2neg:B,k2:I}=x(S),{p1:O,p2:C}=Vv(P,v,D,I);return $(R.beta,O,C,E,B)}else return U.unsafe(v,S)}multiplyAndAddUnsafe(S,R,v){const E=this.multiplyUnsafe(R).add(S.multiplyUnsafe(v));return E.is0()?void 0:E}toAffine(S){return _(this,S)}isTorsionFree(){const{isTorsionFree:S}=e;return o===Hn?!0:S?S(P,this):U.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:S}=e;return o===Hn?this:S?S(P,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(S=!0){return Ds(S,"isCompressed"),this.assertValidity(),p(P,this,S)}toHex(S=!0){return qn(this.toBytes(S))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(S=!0){return this.toBytes(S)}_setWindowSize(S){this.precompute(S)}static normalizeZ(S){return Uo(P,S)}static msm(S,R){return Kv(P,s,S,R)}static fromPrivateKey(S){return P.BASE.multiply(Wn(s,S))}}P.BASE=new P(i.Gx,i.Gy,r.ONE),P.ZERO=new P(r.ZERO,r.ONE,r.ZERO),P.Fp=r,P.Fn=s;const k=s.BITS,U=new zv(P,e.endo?Math.ceil(k/2):k);return P.BASE.precompute(8),P}function hh(t){return Uint8Array.of(t?2:3)}function fh(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function aE(t,e={}){const{Fn:n}=t,r=e.randomBytes||Zt,s=Object.assign(fh(t.Fp,n),{seed:th(n.ORDER)});function i(p){try{return!!Wn(n,p)}catch{return!1}}function o(p,d){const{publicKey:g,publicKeyUncompressed:y}=s;try{const b=p.length;return d===!0&&b!==g||d===!1&&b!==y?!1:!!t.fromBytes(p)}catch{return!1}}function a(p=r(s.seed)){return Mv(En(p,s.seed,"seed"),n.ORDER)}function c(p,d=!0){return t.BASE.multiply(Wn(n,p)).toBytes(d)}function l(p){const d=a(p);return{secretKey:d,publicKey:c(d)}}function u(p){if(typeof p=="bigint")return!1;if(p instanceof t)return!0;const{secretKey:d,publicKey:g,publicKeyUncompressed:y}=s;if(n.allowedLengths||d===g)return;const b=Ae("key",p).length;return b===g||b===y}function h(p,d,g=!0){if(u(p)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");const y=Wn(n,p);return t.fromHex(d).multiply(y).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:i,randomPrivateKey:a,normPrivateKeyToScalar:p=>Wn(n,p),precompute(p=8,d=t.BASE){return d.precompute(p,!1)}},lengths:s})}function cE(t,e,n={}){cs(e),$s(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Zt,s=n.hmac||((R,...v)=>mr(e,R,St(...v))),{Fp:i,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p}=aE(t,n),d={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(R){const v=a>>Hn;return R>v}function b(R,v){if(!o.isValidNot0(v))throw new Error(`invalid signature ${R}: out of range 1..Point.Fn.ORDER`);return v}function A(R,v){qo(v);const E=p.signature,D=v==="compact"?E:v==="recovered"?E+1:void 0;return En(R,D,`${v} signature`)}class w{constructor(v,E,D){this.r=b("r",v),this.s=b("s",E),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(v,E=g){A(v,E);let D;if(E==="der"){const{r:C,s:L}=Bt.toSig(En(v));return new w(C,L)}E==="recovered"&&(D=v[0],E="compact",v=v.subarray(1));const B=o.BYTES,I=v.subarray(0,B),O=v.subarray(B,B*2);return new w(o.fromBytes(I),o.fromBytes(O),D)}static fromHex(v,E){return this.fromBytes(ls(v),E)}addRecoveryBit(v){return new w(this.r,this.s,v)}recoverPublicKey(v){const E=i.ORDER,{r:D,s:B,recovery:I}=this;if(I==null||![0,1,2,3].includes(I))throw new Error("recovery id invalid");if(a*uh<E&&I>1)throw new Error("recovery id is ambiguous for h>1 curve");const C=I===2||I===3?D+a:D;if(!i.isValid(C))throw new Error("recovery id 2 or 3 invalid");const L=i.toBytes(C),V=t.fromBytes(St(hh((I&1)===0),L)),j=o.inv(C),q=x(Ae("msgHash",v)),K=o.create(-q*j),W=o.create(B*j),G=t.BASE.multiplyUnsafe(K).add(V.multiplyUnsafe(W));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return y(this.s)}toBytes(v=g){if(qo(v),v==="der")return ls(Bt.hexFromSig(this));const E=o.toBytes(this.r),D=o.toBytes(this.s);if(v==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return St(Uint8Array.of(this.recovery),E,D)}return St(E,D)}toHex(v){return qn(this.toBytes(v))}assertValidity(){}static fromCompact(v){return w.fromBytes(Ae("sig",v),"compact")}static fromDER(v){return w.fromBytes(Ae("sig",v),"der")}normalizeS(){return this.hasHighS()?new w(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return qn(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return qn(this.toBytes("compact"))}}const m=n.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const E=Ts(v),D=v.length*8-c;return D>0?E>>BigInt(D):E},x=n.bits2int_modN||function(v){return o.create(m(v))},_=Ir(c);function T(R){return Co("num < 2^"+c,R,Pt,_),o.toBytes(R)}function $(R,v){return En(R,void 0,"message"),v?En(e(R),void 0,"prehashed message"):R}function P(R,v,E){if(["recovered","canonical"].some(K=>K in E))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:B,extraEntropy:I}=jo(E,d);R=$(R,B);const O=x(R),C=Wn(o,v),L=[T(C),T(O)];if(I!=null&&I!==!1){const K=I===!0?r(p.secretKey):I;L.push(Ae("extraEntropy",K))}const V=St(...L),j=O;function q(K){const W=m(K);if(!o.isValidNot0(W))return;const G=o.inv(W),H=t.BASE.multiply(W).toAffine(),Z=o.create(H.x);if(Z===Pt)return;const ae=o.create(G*o.create(j+Z*C));if(ae===Pt)return;let ce=(H.x===Z?0:2)|Number(H.y&Hn),we=ae;return D&&y(ae)&&(we=o.neg(ae),ce^=1),new w(Z,we,ce)}return{seed:V,k2sig:q}}function k(R,v,E={}){R=Ae("message",R);const{seed:D,k2sig:B}=P(R,v,E);return Rv(e.outputLen,o.BYTES,s)(D,B)}function U(R){let v;const E=typeof R=="string"||as(R),D=!E&&R!==null&&typeof R=="object"&&typeof R.r=="bigint"&&typeof R.s=="bigint";if(!E&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)v=new w(R.r,R.s);else if(E){try{v=w.fromBytes(Ae("sig",R),"der")}catch(B){if(!(B instanceof Bt.Err))throw B}if(!v)try{v=w.fromBytes(Ae("sig",R),"compact")}catch{return!1}}return v||!1}function N(R,v,E,D={}){const{lowS:B,prehash:I,format:O}=jo(D,d);if(E=Ae("publicKey",E),v=$(Ae("message",v),I),"strict"in D)throw new Error("options.strict was renamed to lowS");const C=O===void 0?U(R):w.fromBytes(Ae("sig",R),O);if(C===!1)return!1;try{const L=t.fromBytes(E);if(B&&C.hasHighS())return!1;const{r:V,s:j}=C,q=x(v),K=o.inv(j),W=o.create(q*K),G=o.create(V*K),H=t.BASE.multiplyUnsafe(W).add(L.multiplyUnsafe(G));return H.is0()?!1:o.create(H.x)===V}catch{return!1}}function S(R,v,E={}){const{prehash:D}=jo(E,d);return v=$(v,D),w.fromBytes(R,"recovered").recoverPublicKey(v).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:p,Point:t,sign:k,verify:N,recoverPublicKey:S,Signature:w,hash:e})}function lE(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 s=on(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),i={Fp:n,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function uE(t){const{CURVE:e,curveOpts:n}=lE(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 hE(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Qu(n.Fn.ORDER,n.Fn.BITS))})}function fE(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:s}=uE(t),i=oE(e,n),o=cE(i,r,s);return hE(t,o)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function zo(t,e){const n=r=>fE({...t,hash:r});return{...n(e),create:n}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const dh={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},ph={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},gh={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},dE=on(dh.p),pE=on(ph.p),gE=on(gh.p),yE=zo({...dh,Fp:dE,lowS:!1},mn);zo({...ph,Fp:pE,lowS:!1},Xm),zo({...gh,Fp:gE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},Zm);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const wE=yE,mE={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"}};var Vo,yh;function wh(){if(yh)return Vo;yh=1;const t="Input must be an string, Buffer or Uint8Array";function e(o){let a;if(o instanceof Uint8Array)a=o;else if(typeof o=="string")a=new TextEncoder().encode(o);else throw new Error(t);return a}function n(o){return Array.prototype.map.call(o,function(a){return(a<16?"0":"")+a.toString(16)}).join("")}function r(o){return(4294967296+o).toString(16).substring(1)}function s(o,a,c){let l=`
16
16
  `+o+" = ";for(let u=0;u<a.length;u+=2){if(c===32)l+=r(a[u]).toUpperCase(),l+=" ",l+=r(a[u+1]).toUpperCase();else if(c===64)l+=r(a[u+1]).toUpperCase(),l+=r(a[u]).toUpperCase();else throw new Error("Invalid size "+c);u%6===4?l+=`
17
- `+new Array(o.length+4).join(" "):u<a.length-2&&(l+=" ")}console.log(l)}function i(o,a,c){let l=new Date().getTime();const u=new Uint8Array(a);for(let f=0;f<a;f++)u[f]=f%256;const h=new Date().getTime();console.log("Generated random input in "+(h-l)+"ms"),l=h;for(let f=0;f<c;f++){const p=o(u),d=new Date().getTime(),g=d-l;l=d,console.log("Hashed in "+g+"ms: "+p.substring(0,20)+"..."),console.log(Math.round(a/(1<<20)/(g/1e3)*100)/100+" MB PER SECOND")}}return jo={normalizeInput:e,toHex:n,debugPrint:s,testSpeed:i},jo}var Vo,wh;function bE(){if(wh)return Vo;wh=1;const t=yh();function e(v,A,w){const m=v[A]+v[w];let x=v[A+1]+v[w+1];m>=4294967296&&x++,v[A]=m,v[A+1]=x}function n(v,A,w,m){let x=v[A]+w;w<0&&(x+=4294967296);let _=v[A+1]+m;x>=4294967296&&_++,v[A]=x,v[A+1]=_}function r(v,A){return v[A]^v[A+1]<<8^v[A+2]<<16^v[A+3]<<24}function s(v,A,w,m,x,_){const T=l[x],$=l[x+1],P=l[_],k=l[_+1];e(c,v,A),n(c,v,T,$);let U=c[m]^c[v],N=c[m+1]^c[v+1];c[m]=N,c[m+1]=U,e(c,w,m),U=c[A]^c[w],N=c[A+1]^c[w+1],c[A]=U>>>24^N<<8,c[A+1]=N>>>24^U<<8,e(c,v,A),n(c,v,P,k),U=c[m]^c[v],N=c[m+1]^c[v+1],c[m]=U>>>16^N<<16,c[m+1]=N>>>16^U<<16,e(c,w,m),U=c[A]^c[w],N=c[A+1]^c[w+1],c[A]=N>>>31^U<<1,c[A+1]=U>>>31^N<<1}const i=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),o=[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],a=new Uint8Array(o.map(function(v){return v*2})),c=new Uint32Array(32),l=new Uint32Array(32);function u(v,A){let w=0;for(w=0;w<16;w++)c[w]=v.h[w],c[w+16]=i[w];for(c[24]=c[24]^v.t,c[25]=c[25]^v.t/4294967296,A&&(c[28]=~c[28],c[29]=~c[29]),w=0;w<32;w++)l[w]=r(v.b,4*w);for(w=0;w<12;w++)s(0,8,16,24,a[w*16+0],a[w*16+1]),s(2,10,18,26,a[w*16+2],a[w*16+3]),s(4,12,20,28,a[w*16+4],a[w*16+5]),s(6,14,22,30,a[w*16+6],a[w*16+7]),s(0,10,20,30,a[w*16+8],a[w*16+9]),s(2,12,22,24,a[w*16+10],a[w*16+11]),s(4,14,16,26,a[w*16+12],a[w*16+13]),s(6,8,18,28,a[w*16+14],a[w*16+15]);for(w=0;w<16;w++)v.h[w]=v.h[w]^c[w]^c[w+16]}const h=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 f(v,A,w,m){if(v===0||v>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(A&&A.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(w&&w.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(m&&m.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const x={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:v};h.fill(0),h[0]=v,A&&(h[1]=A.length),h[2]=1,h[3]=1,w&&h.set(w,32),m&&h.set(m,48);for(let _=0;_<16;_++)x.h[_]=i[_]^r(h,_*4);return A&&(p(x,A),x.c=128),x}function p(v,A){for(let w=0;w<A.length;w++)v.c===128&&(v.t+=v.c,u(v,!1),v.c=0),v.b[v.c++]=A[w]}function d(v){for(v.t+=v.c;v.c<128;)v.b[v.c++]=0;u(v,!0);const A=new Uint8Array(v.outlen);for(let w=0;w<v.outlen;w++)A[w]=v.h[w>>2]>>8*(w&3);return A}function g(v,A,w,m,x){w=w||64,v=t.normalizeInput(v),m&&(m=t.normalizeInput(m)),x&&(x=t.normalizeInput(x));const _=f(w,A,m,x);return p(_,v),d(_)}function y(v,A,w,m,x){const _=g(v,A,w,m,x);return t.toHex(_)}return Vo={blake2b:g,blake2bHex:y,blake2bInit:f,blake2bUpdate:p,blake2bFinal:d},Vo}var Ko,mh;function vE(){if(mh)return Ko;mh=1;const t=yh();function e(d,g){return d[g]^d[g+1]<<8^d[g+2]<<16^d[g+3]<<24}function n(d,g,y,v,A,w){o[d]=o[d]+o[g]+A,o[v]=r(o[v]^o[d],16),o[y]=o[y]+o[v],o[g]=r(o[g]^o[y],12),o[d]=o[d]+o[g]+w,o[v]=r(o[v]^o[d],8),o[y]=o[y]+o[v],o[g]=r(o[g]^o[y],7)}function r(d,g){return d>>>g^d<<32-g}const s=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=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]),o=new Uint32Array(16),a=new Uint32Array(16);function c(d,g){let y=0;for(y=0;y<8;y++)o[y]=d.h[y],o[y+8]=s[y];for(o[12]^=d.t,o[13]^=d.t/4294967296,g&&(o[14]=~o[14]),y=0;y<16;y++)a[y]=e(d.b,4*y);for(y=0;y<10;y++)n(0,4,8,12,a[i[y*16+0]],a[i[y*16+1]]),n(1,5,9,13,a[i[y*16+2]],a[i[y*16+3]]),n(2,6,10,14,a[i[y*16+4]],a[i[y*16+5]]),n(3,7,11,15,a[i[y*16+6]],a[i[y*16+7]]),n(0,5,10,15,a[i[y*16+8]],a[i[y*16+9]]),n(1,6,11,12,a[i[y*16+10]],a[i[y*16+11]]),n(2,7,8,13,a[i[y*16+12]],a[i[y*16+13]]),n(3,4,9,14,a[i[y*16+14]],a[i[y*16+15]]);for(y=0;y<8;y++)d.h[y]^=o[y]^o[y+8]}function l(d,g){if(!(d>0&&d<=32))throw new Error("Incorrect output length, should be in [1, 32]");const y=g?g.length:0;if(g&&!(y>0&&y<=32))throw new Error("Incorrect key length, should be in [1, 32]");const v={h:new Uint32Array(s),b:new Uint8Array(64),c:0,t:0,outlen:d};return v.h[0]^=16842752^y<<8^d,y>0&&(u(v,g),v.c=64),v}function u(d,g){for(let y=0;y<g.length;y++)d.c===64&&(d.t+=d.c,c(d,!1),d.c=0),d.b[d.c++]=g[y]}function h(d){for(d.t+=d.c;d.c<64;)d.b[d.c++]=0;c(d,!0);const g=new Uint8Array(d.outlen);for(let y=0;y<d.outlen;y++)g[y]=d.h[y>>2]>>8*(y&3)&255;return g}function f(d,g,y){y=y||32,d=t.normalizeInput(d);const v=l(y,g);return u(v,d),h(v)}function p(d,g,y){const v=f(d,g,y);return t.toHex(v)}return Ko={blake2s:f,blake2sHex:p,blake2sInit:l,blake2sUpdate:u,blake2sFinal:h},Ko}var Ho,bh;function EE(){if(bh)return Ho;bh=1;const t=bE(),e=vE();return Ho={blake2b:t.blake2b,blake2bHex:t.blake2bHex,blake2bInit:t.blake2bInit,blake2bUpdate:t.blake2bUpdate,blake2bFinal:t.blake2bFinal,blake2s:e.blake2s,blake2sHex:e.blake2sHex,blake2sInit:e.blake2sInit,blake2sUpdate:e.blake2sUpdate,blake2sFinal:e.blake2sFinal},Ho}var xE=EE();const _E=":";function Ct(t){const[e,n]=t.split(_E);return{namespace:e,reference:n}}function vh(t,e){return t.includes(":")?[t]:e.chains||[]}const IE={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}},SE={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function M(t,e){const{message:n,code:r}=SE[t];return{message:e?`${n} ${e}`:n,code:r}}function te(t,e){const{message:n,code:r}=IE[t];return{message:e?`${n} ${e}`:n,code:r}}const DE="ReactNative",ze={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},AE="js";function Cs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function an(){return!xt.getDocument()&&!!xt.getNavigator()&&navigator.product===DE}function TE(){return an()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="android"}function OE(){return an()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="ios"}function Gn(){return!Cs()&&!!xt.getNavigator()&&!!xt.getDocument()}function Dr(){return an()?ze.reactNative:Cs()?ze.node:Gn()?ze.browser:ze.unknown}function Eh(){try{return an()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function $E(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{s!=null&&n.set(r,String(s))}),n.toString()}function RE(t){const e=xh();try{return t?.url&&e.url&&new URL(t.url).host!==new URL(e.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${e.url}. This is probably unintended and can lead to issues.`),t.url=e.url),t?.icons?.length&&t.icons.length>0&&(t.icons=t.icons.filter(n=>n!=="")),{...e,...t,url:t?.url||e.url,name:t?.name||e.name,description:t?.description||e.description,icons:t?.icons?.length&&t.icons.length>0?t.icons:e.icons}}catch(n){return console.warn("Error populating app metadata",n),t||e}}function xh(){return ym.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function BE(){if(Dr()===ze.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=lm();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 PE(){const t=Dr();return t===ze.browser?[t,xt.getLocation()?.host||"unknown"].join(":"):t}function _h(t,e,n){const r=BE(),s=PE();return[[t,e].join("-"),[AE,n].join("-"),r,s].join("/")}function CE({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:s,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),u=_h(t,e,r),h={auth:s,ua:u,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},f=$E(l[1]||"",h);return l[0]+"?"+f}function In(t,e){return t.filter(n=>e.includes(n)).length===t.length}function Wo(t){return Object.fromEntries(t.entries())}function Go(t){return new Map(Object.entries(t))}function Sn(t=F.FIVE_MINUTES,e){const n=F.toMiliseconds(t||F.FIVE_MINUTES);let r,s,i,o;return{resolve:a=>{i&&r&&(clearTimeout(i),r(a),o=Promise.resolve(a))},reject:a=>{i&&s&&(clearTimeout(i),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=M("EXPIRED"),u=new Error(e||l.message);u.code=l.code,c(u)},n),r=a,s=c})}}function st(t,e,n){return new Promise(async(r,s)=>{const i=setTimeout(()=>s(new Error(n)),e);try{const o=await t;r(o)}catch(o){s(o)}clearTimeout(i)})}function Ih(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 NE(t){return Ih("topic",t)}function UE(t){return Ih("id",t)}function Sh(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 fe(t,e){return F.fromMiliseconds(Date.now()+F.toMiliseconds(t))}function cn(t){return Date.now()>=F.toMiliseconds(t)}function J(t,e){return`${t}${e?`:${e}`:""}`}function Dn(t=[],e=[]){return[...new Set([...t,...e])]}async function kE({id:t,topic:e,wcDeepLink:n}){try{if(!n)return;const r=(typeof n=="string"?JSON.parse(n):n)?.href;if(typeof r!="string")return;const s=LE(r,t,e),i=Dr();if(i===ze.browser){if(!xt.getDocument()?.hasFocus()){console.warn("Document does not have focus, skipping deeplink.");return}FE(s)}else i===ze.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(s)}catch(r){console.error(r)}}function LE(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${i}${jE(r,!0)}`}else s=`${s}/wc?${r}`;return s}function FE(t){let e="_self";zE()?e="_top":(qE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function ME(t,e){let n="";try{if(Gn()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function Dh(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function Ah(){return typeof crypto<"u"&&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 Yo(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function qE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function zE(){try{return window.self!==window.top}catch{return!1}}function jE(t,e=!1){const n=new TextEncoder().encode(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=String.fromCharCode(n[i]);const s=btoa(r.join(""));return e?s.replace(/[=]/g,""):s}function Th(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return new TextDecoder().decode(r)}function VE(t){return new Promise(e=>setTimeout(e,t))}class KE{constructor({limit:e}){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 HE="https://rpc.walletconnect.org/v1";function An(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}const WE=/^0x[0-9a-fA-F]{64}$/;function GE(t){return WE.test(t)}function Oh(t){const e=new TextEncoder().encode(t),n=new TextEncoder().encode(`Ethereum Signed Message:
18
- ${e.length}`);return"0x"+he(_l(Rt([n,e])),"base16")}async function YE(t,e,n,r,s,i){switch(n.t){case"eip191":return await ZE(t,e,n.s);case"eip1271":return await XE(t,e,n.s,r,s,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function ZE(t,e,n){const r=c1(n);return x1({payload:Oh(e),signature:r}).toLowerCase()===t.toLowerCase()}async function XE(t,e,n,r,s,i){const o=Ct(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",l=n.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),h=(GE(e)?e:Oh(e)).substring(2),f=a+h+c+u+l,p=await fetch(`${i||HE}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:JE(),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 JE(){return Date.now()+Math.floor(Math.random()*1e3)}function QE(t){const e=An(t),n=e[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(e.length<r)throw new Error("Transaction data too short for claimed signature count");if(e.length<100)throw new Error("Transaction too short");const s=e.slice(1,65);return vr.encode(s)}function e2(t){const e=An(t),n=new TextEncoder().encode("TransactionData::"),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const s=w1(r,{dkLen:32});return vr.encode(s)}function $h(t){const e=new Uint8Array(mn(t2(t)));return vr.encode(e)}function t2(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&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 Rh(t){const e=An(t),n=fv(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=sv(n),s=new TextEncoder().encode("TX"),i=Rt([s,new Uint8Array(r)]),o=Jm(i);return E1.encode(o).replace(/=+$/,"")}function Zo(t){const e=[];let n=BigInt(t);for(;n>=0x80n;)e.push(Number(n&0x7fn|0x80n)),n>>=7n;return e.push(Number(n)),new Uint8Array(e)}function n2(t){const e=An(t.signed.bodyBytes),n=An(t.signed.authInfoBytes),r=An(t.signature.signature),s=[];s.push(new Uint8Array([10])),s.push(Zo(e.length)),s.push(e),s.push(new Uint8Array([18])),s.push(Zo(n.length)),s.push(n),s.push(new Uint8Array([26])),s.push(Zo(r.length)),s.push(r);const i=Rt(s),o=mn(i);return he(o,"base16").toUpperCase()}const r2={pubnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"},s2=0,Xo=2,Bh=5,Ph=72,i2=64,o2=20;function Jo(t,e){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(e,!1)}function a2(t){for(let e=o2;e>=0;e--){const n=t.length-4-Ph*e;if(n<4||Jo(t,n)!==e)continue;let r=!0;for(let s=0;s<e;s++){const i=n+4+Ph*s;if(Jo(t,i+4)!==i2){r=!1;break}}if(r)return n}throw new Error("getStellarTransactionHash: could not locate envelope signature array")}function c2(t,e){const n=An(t);if(n.length<8)throw new Error("getStellarTransactionHash: envelope too short");const r=Jo(n,0);let s,i;switch(r){case s2:s=Xo,i=0;break;case Xo:s=Xo,i=4;break;case Bh:s=Bh,i=4;break;default:throw new Error(`getStellarTransactionHash: unsupported envelope type: ${r}`)}const o=a2(n),a=e?.split(":").pop()??"pubnet",c=r2[a];if(!c)throw new Error(`getStellarTransactionHash: unknown Stellar network: ${a}`);const l=mn(new TextEncoder().encode(c)),u=new Uint8Array([0,0,0,s]),h=Rt([l,u,n.slice(i,o)]);return he(mn(h),"base16")}function l2(t){const e=[];try{if(typeof t=="string")return e.push(t),e;if(typeof t!="object")return e;t?.id&&e.push(t.id);const n=t?.capabilities?.caip345?.transactionHashes;n&&e.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return e}const Ch="did:pkh:",u2={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},h2=t=>t?u2[t]||t:"",Ns=t=>t?.split(":"),f2=t=>{const e=t&&Ns(t);if(e)return t.includes(Ch)?e[3]:e[1]},d2=t=>{const e=t&&Ns(t);if(e)return t.includes(Ch)?e[2]:e[0]},Us=t=>{const e=t&&Ns(t);if(e)return e[2]+":"+e[3]},ks=t=>{const e=t&&Ns(t);if(e)return e.pop()};async function Nh(t){const{cacao:e,projectId:n}=t,{s:r,p:s}=e;let i;try{i=Uh(s,s.iss)}catch{return!1}const o=ks(s.iss);try{return await YE(o,i,r,Us(s.iss),n)}catch{return!1}}function p2(t){const{cacao:e,request:n}=t,{p:r}=e;if(r.domain!==n.domain)return{valid:!1,reason:`domain mismatch: requested ${n.domain}, got ${r.domain}`};if(r.nonce!==n.nonce)return{valid:!1,reason:`nonce mismatch: requested ${n.nonce}, got ${r.nonce}`};const s=n.aud||n.uri,i=r.aud||r.uri;if(s&&i!==s)return{valid:!1,reason:`aud mismatch: requested ${s}, got ${i}`};if(n.chains?.length){const a=Us(r.iss);if(!a||!n.chains.includes(a))return{valid:!1,reason:`cacao issued for chain ${a} which was not requested`}}const o=Date.now();if(r.exp){const a=new Date(r.exp).getTime();if(isNaN(a))return{valid:!1,reason:`malformed exp: ${r.exp}`};if(a<o)return{valid:!1,reason:"cacao has expired"}}if(r.nbf){const a=new Date(r.nbf).getTime();if(isNaN(a))return{valid:!1,reason:`malformed nbf: ${r.nbf}`};if(a>o)return{valid:!1,reason:"cacao is not yet valid"}}return{valid:!0}}const Uh=(t,e)=>{const n=d2(e);if(!n)throw new Error("Invalid issuer: "+e);const r=`${t.domain} wants you to sign in with your ${h2(n)} account:`,s=ks(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 o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${f2(e)}`,l=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,p=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(y=>`
19
- - ${y}`).join("")}`:void 0,g=Ls(t.resources);if(g){const y=Ar(g);i=_2(i,y)}if(i&&/\r|\n/.test(i))throw new Error("Statement must not contain line breaks (`\\r` or `\\n`)");return[r,s,"",i,"",o,a,c,l,u,h,f,p,d].filter(y=>y!=null).join(`
20
- `)};function g2(t){const e=JSON.stringify(t),n=new TextEncoder().encode(e),r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=String.fromCharCode(n[s]);return btoa(r.join(""))}function y2(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return JSON.parse(new TextDecoder().decode(r))}function Tn(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?.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(s=>{const i=r[s];if(!Array.isArray(i))throw new Error(`Ability limits ${s} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function w2(t,e,n,r={}){return n?.sort((s,i)=>s.localeCompare(i)),{att:{[t]:m2(e,n,r)}}}function m2(t,e,n={}){e=e?.sort((s,i)=>s.localeCompare(i));const r=e.map(s=>({[`${t}/${s}`]:[n]}));return Object.assign({},...r)}function kh(t){return Tn(t),`urn:recap:${g2(t).replace(/=/g,"")}`}function Ar(t){const e=y2(t.replace("urn:recap:",""));return Tn(e),e}function b2(t,e,n){const r=w2(t,e,n);return kh(r)}function v2(t){return t&&t.includes("urn:recap:")}function E2(t,e){const n=Ar(t),r=Ar(e),s=x2(n,r);return kh(s)}function x2(t,e){Tn(t),Tn(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,i)=>s.localeCompare(i)),r={att:{}};return n.forEach(s=>{Object.keys(t.att?.[s]||{}).concat(Object.keys(e.att?.[s]||{})).sort((i,o)=>i.localeCompare(o)).forEach(i=>{r.att[s]={...r.att[s],[i]:t.att[s]?.[i]||e.att[s]?.[i]}})}),r}function _2(t="",e){Tn(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 s=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 l={};c.forEach(h=>{l[h.ability]||(l[h.ability]=[]),l[h.ability].push(h.action)});const u=Object.keys(l).map(h=>(s++,`(${s}) '${h}': '${l[h].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const i=r.join(" "),o=`${n}${i}`;return`${t?t+" ":""}${o}`}function Lh(t){const e=Ar(t);Tn(e);const n=e.att?.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function Fh(t){const e=Ar(t);Tn(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{s?.[0]?.chains&&n.push(s[0].chains)})}),[...new Set(n.flat())]}function Ls(t){if(!t)return;const e=t?.[t.length-1];return v2(e)?e:void 0}const Mh="base10",$e="base16",Ee="base64pad",pt="base64url",Tr="utf8",qh=0,Nt=1,On=2,I2=0,zh=1,Or=12,Qo=32;function S2(){const t=Fo.utils.randomPrivateKey(),e=Fo.getPublicKey(t);return{privateKey:he(t,$e),publicKey:he(e,$e)}}function ea(){const t=Zt(Qo);return he(t,$e)}function D2(t,e){const n=Fo.getSharedSecret(_e(t,$e),_e(e,$e)),r=Ov(hs,n,void 0,void 0,Qo);return he(r,$e)}function Fs(t){const e=hs(_e(t,$e));return he(e,$e)}function Ge(t){const e=hs(_e(t,Tr));return he(e,$e)}function jh(t){return _e(`${t}`,Mh)}function $n(t){return Number(he(t,Mh))}function Vh(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ms(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function A2(t){const e=jh(typeof t.type<"u"?t.type:qh);if($n(e)===Nt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?_e(t.senderPublicKey,$e):void 0,r=typeof t.iv<"u"?_e(t.iv,$e):Zt(Or),s=_e(t.symKey,$e),i=ku(s,r).encrypt(_e(t.message,Tr)),o=Kh({type:e,sealed:i,iv:r,senderPublicKey:n});return t.encoding===pt?Vh(o):o}function T2(t){const e=_e(t.symKey,$e),{sealed:n,iv:r}=$r({encoded:t.encoded,encoding:t.encoding}),s=ku(e,r).decrypt(n);if(s===null)throw new Error("Failed to decrypt");return he(s,Tr)}function O2(t,e){const n=jh(On),r=Zt(Or),s=_e(t,Tr),i=Kh({type:n,sealed:s,iv:r});return e===pt?Vh(i):i}function $2(t,e){const{sealed:n}=$r({encoded:t,encoding:e});return he(n,Tr)}function Kh(t){if($n(t.type)===On)return he(Rt([t.type,t.sealed]),Ee);if($n(t.type)===Nt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return he(Rt([t.type,t.senderPublicKey,t.iv,t.sealed]),Ee)}return he(Rt([t.type,t.iv,t.sealed]),Ee)}function $r(t){const e=(t.encoding||Ee)===pt?Ms(t.encoded):t.encoded,n=_e(e,Ee),r=n.slice(I2,zh),s=zh;if($n(r)===Nt){const c=s+Qo,l=c+Or,u=n.slice(s,c),h=n.slice(c,l),f=n.slice(l);return{type:r,sealed:f,iv:h,senderPublicKey:u}}if($n(r)===On){const c=n.slice(s),l=Zt(Or);return{type:r,sealed:c,iv:l}}const i=s+Or,o=n.slice(s,i),a=n.slice(i);return{type:r,sealed:a,iv:o}}function R2(t,e){const n=$r({encoded:t,encoding:e?.encoding});return Hh({type:$n(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?he(n.senderPublicKey,$e):void 0,receiverPublicKey:e?.receiverPublicKey})}function Hh(t){const e=t?.type||qh;if(e===Nt){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 Wh(t){return t.type===Nt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Gh(t){return t.type===On}function B2(t){const e=_e(Ms(t.x),Ee),n=_e(Ms(t.y),Ee);return Rt([new Uint8Array([4]),e,n])}function P2(t,e){const[n,r,s]=t.split("."),i=_e(Ms(s),Ee);if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${n}.${r}`,l=hs(c),u=B2(e);if(!wE.verify(Rt([o,a]),l,u))throw new Error("Invalid signature");return Li(t).payload}const C2="irn";function qs(t){return t?.relay||{protocol:C2}}function Yn(t){const e=mE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function N2(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(r)){const i=s.replace(r,""),o=t[s];n[i]=o}}),n}function Yh(t){if(!t.includes("wc:")){const l=Th(t);l?.includes("wc:")&&(t=l)}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),s=t.substring(e+1,n).split("@"),i=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:U2(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:N2(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function U2(t){return t.startsWith("//")?t.substring(2):t}function k2(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(s=>{const i=s,o=n+e+i;t[i]&&(r[o]=t[i])}),r}function Zh(t){const e=new URLSearchParams,n={...k2(t.relay),symKey:t.symKey,...t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()},...t.methods&&{methods:t.methods.join(",")}};return Object.entries(n).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{s!==void 0&&e.append(r,String(s))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function zs(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}function Zn(t){const e=[];return t.forEach(n=>{const[r,s]=n.split(":");e.push(`${r}:${s}`)}),e}function Xh(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Zn(n.accounts))}),[...new Set(e)]}function L2(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.methods)}),[...new Set(e)]}function F2(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.events)}),[...new Set(e)]}function M2(t,e){const n=[];return Object.values(t).forEach(r=>{Zn(r.accounts).includes(e)&&n.push(...r.methods)}),n}function q2(t,e){const n=[];return Object.values(t).forEach(r=>{Zn(r.accounts).includes(e)&&n.push(...r.events)}),n}function Jh(t){return t.includes(":")}function z2(t){return Jh(t)?t.split(":")[0]:t}function Qh(t){const e={};if(!Rr(t))return e;for(const[n,r]of Object.entries(t)){const s=Jh(n)?[n]:r.chains,i=r.methods||[],o=r.events||[],a=z2(n);e[a]={...e[a],chains:Dn(s,e[a]?.chains),methods:Dn(i,e[a]?.methods),events:Dn(o,e[a]?.events)}}return e}function j2(t){const e={};return t?.forEach(n=>{const[r,s]=n.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(n),e[r].chains?.push(`${r}:${s}`)}),e}function ef(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=j2(e);for(const[r,s]of Object.entries(n))s.methods?s.methods=Dn(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return n}function V2(t,e){const n=Qh(t),r=Qh(e),s={},i=Object.keys(n).concat(Object.keys(r));for(const o of i)s[o]={chains:Dn(n[o]?.chains,r[o]?.chains),methods:Dn(n[o]?.methods,r[o]?.methods),events:Dn(n[o]?.events,r[o]?.events)};return s}function Xn(t,e){return!!Array.isArray(t)}function Rr(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function de(t){return typeof t>"u"}function oe(t,e){return e&&de(t)?!0:typeof t=="string"&&!!t.trim().length}function ta(t,e){return e&&de(t)?!0:typeof t=="number"&&!isNaN(t)}function K2(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),s=Object.keys(n);let i=!0;return In(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=Zn(a),h=n[o];(!In(vh(o,h),u)||!In(h.methods,c)||!In(h.events,l))&&(i=!1)}),i):!1}function Br(t){return oe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function H2(t){if(oe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Br(n)}}return!1}function W2(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(oe(t,!1)){if(e(t))return!0;const n=Th(t);return e(n)}}catch{}return!1}function G2(t){return t?.proposer?.publicKey}function Y2(t){return t?.topic}function Z2(t,e){let n=null;return oe(t?.publicKey,!1)||(n=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function tf(t){let e=!0;return Xn(t)?t.length&&(e=t.every(n=>oe(n,!1))):e=!1,e}function X2(t,e,n){let r=null;return Xn(e)&&e.length?e.forEach(s=>{r||Br(s)||(r=te("UNSUPPORTED_CHAINS",`${n}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Br(t)||(r=te("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 J2(t,e,n){let r=null;return Object.entries(t).forEach(([s,i])=>{if(r)return;const o=X2(s,vh(s,i),`${e} ${n}`);o&&(r=o)}),r}function Q2(t,e){let n=null;return Xn(t)?t.forEach(r=>{n||H2(r)||(n=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function ex(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=Q2(r?.accounts,`${e} namespace`);s&&(n=s)}),n}function tx(t,e){let n=null;return tf(t?.methods)?tf(t?.events)||(n=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function nf(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=tx(r,`${e}, namespace`);s&&(n=s)}),n}function nx(t,e,n){let r=null;if(t&&Rr(t)){const s=nf(t,e);s&&(r=s);const i=J2(t,e,n);i&&(r=i)}else r=M("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function na(t,e){let n=null;if(t&&Rr(t)){const r=nf(t,e);r&&(n=r);const s=ex(t,e);s&&(n=s)}else n=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function rf(t){return oe(t.protocol,!0)}function rx(t,e){let n=!1;return t?t&&Xn(t)&&t.length&&t.forEach(r=>{n=rf(r)}):n=!0,n}function sx(t){return typeof t=="number"}function Le(t){return typeof t<"u"&&typeof t!==null}function ix(t){return!(!t||typeof t!="object"||!t.code||!ta(t.code,!1)||!t.message||!oe(t.message,!1))}function ox(t){return!(de(t)||!oe(t.method,!1))}function ax(t){return!(de(t)||de(t.result)&&de(t.error)||!ta(t.id,!1)||!oe(t.jsonrpc,!1))}function cx(t){return!(de(t)||!oe(t.name,!1))}function sf(t,e){return!(!Br(e)||!Xh(t).includes(e))}function lx(t,e,n){return oe(n,!1)?M2(t,e).includes(n):!1}function ux(t,e,n){return oe(n,!1)?q2(t,e).includes(n):!1}function of(t,e,n){let r=null;const s=hx(t),i=fx(e),o=Object.keys(s),a=Object.keys(i),c=af(Object.keys(t)),l=af(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
17
+ `+new Array(o.length+4).join(" "):u<a.length-2&&(l+=" ")}console.log(l)}function i(o,a,c){let l=new Date().getTime();const u=new Uint8Array(a);for(let f=0;f<a;f++)u[f]=f%256;const h=new Date().getTime();console.log("Generated random input in "+(h-l)+"ms"),l=h;for(let f=0;f<c;f++){const p=o(u),d=new Date().getTime(),g=d-l;l=d,console.log("Hashed in "+g+"ms: "+p.substring(0,20)+"..."),console.log(Math.round(a/(1<<20)/(g/1e3)*100)/100+" MB PER SECOND")}}return Vo={normalizeInput:e,toHex:n,debugPrint:s,testSpeed:i},Vo}var Ko,mh;function bE(){if(mh)return Ko;mh=1;const t=wh();function e(b,A,w){const m=b[A]+b[w];let x=b[A+1]+b[w+1];m>=4294967296&&x++,b[A]=m,b[A+1]=x}function n(b,A,w,m){let x=b[A]+w;w<0&&(x+=4294967296);let _=b[A+1]+m;x>=4294967296&&_++,b[A]=x,b[A+1]=_}function r(b,A){return b[A]^b[A+1]<<8^b[A+2]<<16^b[A+3]<<24}function s(b,A,w,m,x,_){const T=l[x],$=l[x+1],P=l[_],k=l[_+1];e(c,b,A),n(c,b,T,$);let U=c[m]^c[b],N=c[m+1]^c[b+1];c[m]=N,c[m+1]=U,e(c,w,m),U=c[A]^c[w],N=c[A+1]^c[w+1],c[A]=U>>>24^N<<8,c[A+1]=N>>>24^U<<8,e(c,b,A),n(c,b,P,k),U=c[m]^c[b],N=c[m+1]^c[b+1],c[m]=U>>>16^N<<16,c[m+1]=N>>>16^U<<16,e(c,w,m),U=c[A]^c[w],N=c[A+1]^c[w+1],c[A]=N>>>31^U<<1,c[A+1]=U>>>31^N<<1}const i=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),o=[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],a=new Uint8Array(o.map(function(b){return b*2})),c=new Uint32Array(32),l=new Uint32Array(32);function u(b,A){let w=0;for(w=0;w<16;w++)c[w]=b.h[w],c[w+16]=i[w];for(c[24]=c[24]^b.t,c[25]=c[25]^b.t/4294967296,A&&(c[28]=~c[28],c[29]=~c[29]),w=0;w<32;w++)l[w]=r(b.b,4*w);for(w=0;w<12;w++)s(0,8,16,24,a[w*16+0],a[w*16+1]),s(2,10,18,26,a[w*16+2],a[w*16+3]),s(4,12,20,28,a[w*16+4],a[w*16+5]),s(6,14,22,30,a[w*16+6],a[w*16+7]),s(0,10,20,30,a[w*16+8],a[w*16+9]),s(2,12,22,24,a[w*16+10],a[w*16+11]),s(4,14,16,26,a[w*16+12],a[w*16+13]),s(6,8,18,28,a[w*16+14],a[w*16+15]);for(w=0;w<16;w++)b.h[w]=b.h[w]^c[w]^c[w+16]}const h=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 f(b,A,w,m){if(b===0||b>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(A&&A.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(w&&w.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(m&&m.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const x={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:b};h.fill(0),h[0]=b,A&&(h[1]=A.length),h[2]=1,h[3]=1,w&&h.set(w,32),m&&h.set(m,48);for(let _=0;_<16;_++)x.h[_]=i[_]^r(h,_*4);return A&&(p(x,A),x.c=128),x}function p(b,A){for(let w=0;w<A.length;w++)b.c===128&&(b.t+=b.c,u(b,!1),b.c=0),b.b[b.c++]=A[w]}function d(b){for(b.t+=b.c;b.c<128;)b.b[b.c++]=0;u(b,!0);const A=new Uint8Array(b.outlen);for(let w=0;w<b.outlen;w++)A[w]=b.h[w>>2]>>8*(w&3);return A}function g(b,A,w,m,x){w=w||64,b=t.normalizeInput(b),m&&(m=t.normalizeInput(m)),x&&(x=t.normalizeInput(x));const _=f(w,A,m,x);return p(_,b),d(_)}function y(b,A,w,m,x){const _=g(b,A,w,m,x);return t.toHex(_)}return Ko={blake2b:g,blake2bHex:y,blake2bInit:f,blake2bUpdate:p,blake2bFinal:d},Ko}var Ho,bh;function vE(){if(bh)return Ho;bh=1;const t=wh();function e(d,g){return d[g]^d[g+1]<<8^d[g+2]<<16^d[g+3]<<24}function n(d,g,y,b,A,w){o[d]=o[d]+o[g]+A,o[b]=r(o[b]^o[d],16),o[y]=o[y]+o[b],o[g]=r(o[g]^o[y],12),o[d]=o[d]+o[g]+w,o[b]=r(o[b]^o[d],8),o[y]=o[y]+o[b],o[g]=r(o[g]^o[y],7)}function r(d,g){return d>>>g^d<<32-g}const s=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),i=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]),o=new Uint32Array(16),a=new Uint32Array(16);function c(d,g){let y=0;for(y=0;y<8;y++)o[y]=d.h[y],o[y+8]=s[y];for(o[12]^=d.t,o[13]^=d.t/4294967296,g&&(o[14]=~o[14]),y=0;y<16;y++)a[y]=e(d.b,4*y);for(y=0;y<10;y++)n(0,4,8,12,a[i[y*16+0]],a[i[y*16+1]]),n(1,5,9,13,a[i[y*16+2]],a[i[y*16+3]]),n(2,6,10,14,a[i[y*16+4]],a[i[y*16+5]]),n(3,7,11,15,a[i[y*16+6]],a[i[y*16+7]]),n(0,5,10,15,a[i[y*16+8]],a[i[y*16+9]]),n(1,6,11,12,a[i[y*16+10]],a[i[y*16+11]]),n(2,7,8,13,a[i[y*16+12]],a[i[y*16+13]]),n(3,4,9,14,a[i[y*16+14]],a[i[y*16+15]]);for(y=0;y<8;y++)d.h[y]^=o[y]^o[y+8]}function l(d,g){if(!(d>0&&d<=32))throw new Error("Incorrect output length, should be in [1, 32]");const y=g?g.length:0;if(g&&!(y>0&&y<=32))throw new Error("Incorrect key length, should be in [1, 32]");const b={h:new Uint32Array(s),b:new Uint8Array(64),c:0,t:0,outlen:d};return b.h[0]^=16842752^y<<8^d,y>0&&(u(b,g),b.c=64),b}function u(d,g){for(let y=0;y<g.length;y++)d.c===64&&(d.t+=d.c,c(d,!1),d.c=0),d.b[d.c++]=g[y]}function h(d){for(d.t+=d.c;d.c<64;)d.b[d.c++]=0;c(d,!0);const g=new Uint8Array(d.outlen);for(let y=0;y<d.outlen;y++)g[y]=d.h[y>>2]>>8*(y&3)&255;return g}function f(d,g,y){y=y||32,d=t.normalizeInput(d);const b=l(y,g);return u(b,d),h(b)}function p(d,g,y){const b=f(d,g,y);return t.toHex(b)}return Ho={blake2s:f,blake2sHex:p,blake2sInit:l,blake2sUpdate:u,blake2sFinal:h},Ho}var Wo,vh;function EE(){if(vh)return Wo;vh=1;const t=bE(),e=vE();return Wo={blake2b:t.blake2b,blake2bHex:t.blake2bHex,blake2bInit:t.blake2bInit,blake2bUpdate:t.blake2bUpdate,blake2bFinal:t.blake2bFinal,blake2s:e.blake2s,blake2sHex:e.blake2sHex,blake2sInit:e.blake2sInit,blake2sUpdate:e.blake2sUpdate,blake2sFinal:e.blake2sFinal},Wo}var xE=EE();const _E=":";function Ct(t){const[e,n]=t.split(_E);return{namespace:e,reference:n}}function Eh(t,e){return t.includes(":")?[t]:e.chains||[]}const IE={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}},SE={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function M(t,e){const{message:n,code:r}=SE[t];return{message:e?`${n} ${e}`:n,code:r}}function te(t,e){const{message:n,code:r}=IE[t];return{message:e?`${n} ${e}`:n,code:r}}const DE="ReactNative",je={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},AE="js";function Cs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function an(){return!xt.getDocument()&&!!xt.getNavigator()&&navigator.product===DE}function TE(){return an()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="android"}function OE(){return an()&&typeof global<"u"&&typeof global?.Platform<"u"&&global?.Platform.OS==="ios"}function Gn(){return!Cs()&&!!xt.getNavigator()&&!!xt.getDocument()}function Dr(){return an()?je.reactNative:Cs()?je.node:Gn()?je.browser:je.unknown}function xh(){try{return an()&&typeof global<"u"&&typeof global?.Application<"u"?global.Application?.applicationId:void 0}catch{return}}function $E(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{s!=null&&n.set(r,String(s))}),n.toString()}function RE(t){const e=_h();try{return t?.url&&e.url&&new URL(t.url).host!==new URL(e.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${e.url}. This is probably unintended and can lead to issues.`),t.url=e.url),t?.icons?.length&&t.icons.length>0&&(t.icons=t.icons.filter(n=>n!=="")),{...e,...t,url:t?.url||e.url,name:t?.name||e.name,description:t?.description||e.description,icons:t?.icons?.length&&t.icons.length>0?t.icons:e.icons}}catch(n){return console.warn("Error populating app metadata",n),t||e}}function _h(){return ym.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function BE(){if(Dr()===je.reactNative&&typeof global<"u"&&typeof global?.Platform<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=lm();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 PE(){const t=Dr();return t===je.browser?[t,xt.getLocation()?.host||"unknown"].join(":"):t}function Ih(t,e,n){const r=BE(),s=PE();return[[t,e].join("-"),[AE,n].join("-"),r,s].join("/")}function CE({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:s,projectId:i,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=n.split("?"),u=Ih(t,e,r),h={auth:s,ua:u,projectId:i,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},f=$E(l[1]||"",h);return l[0]+"?"+f}function In(t,e){return t.filter(n=>e.includes(n)).length===t.length}function Go(t){return Object.fromEntries(t.entries())}function Yo(t){return new Map(Object.entries(t))}function Sn(t=F.FIVE_MINUTES,e){const n=F.toMiliseconds(t||F.FIVE_MINUTES);let r,s,i,o;return{resolve:a=>{i&&r&&(clearTimeout(i),r(a),o=Promise.resolve(a))},reject:a=>{i&&s&&(clearTimeout(i),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);i=setTimeout(()=>{const l=M("EXPIRED"),u=new Error(e||l.message);u.code=l.code,c(u)},n),r=a,s=c})}}function st(t,e,n){return new Promise(async(r,s)=>{const i=setTimeout(()=>s(new Error(n)),e);try{const o=await t;r(o)}catch(o){s(o)}clearTimeout(i)})}function Sh(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 NE(t){return Sh("topic",t)}function UE(t){return Sh("id",t)}function Dh(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 fe(t,e){return F.fromMiliseconds(Date.now()+F.toMiliseconds(t))}function cn(t){return Date.now()>=F.toMiliseconds(t)}function J(t,e){return`${t}${e?`:${e}`:""}`}function Dn(t=[],e=[]){return[...new Set([...t,...e])]}async function kE({id:t,topic:e,wcDeepLink:n}){try{if(!n)return;const r=(typeof n=="string"?JSON.parse(n):n)?.href;if(typeof r!="string")return;const s=LE(r,t,e),i=Dr();if(i===je.browser){if(!xt.getDocument()?.hasFocus()){console.warn("Document does not have focus, skipping deeplink.");return}FE(s)}else i===je.reactNative&&typeof global?.Linking<"u"&&await global.Linking.openURL(s)}catch(r){console.error(r)}}function LE(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const i=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${i}${zE(r,!0)}`}else s=`${s}/wc?${r}`;return s}function FE(t){let e="_self";jE()?e="_top":(qE()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function ME(t,e){let n="";try{if(Gn()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function Ah(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function Zo(){return typeof crypto<"u"&&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 Ns(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function qE(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function jE(){try{return window.self!==window.top}catch{return!1}}function zE(t,e=!1){const n=new TextEncoder().encode(t),r=new Array(n.length);for(let i=0;i<n.length;i++)r[i]=String.fromCharCode(n[i]);const s=btoa(r.join(""));return e?s.replace(/[=]/g,""):s}function Th(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return new TextDecoder().decode(r)}function VE(t){return new Promise(e=>setTimeout(e,t))}class KE{constructor({limit:e}){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 HE="https://rpc.walletconnect.org/v1";function An(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return r}const WE=/^0x[0-9a-fA-F]{64}$/;function GE(t){return WE.test(t)}function Oh(t){const e=new TextEncoder().encode(t),n=new TextEncoder().encode(`Ethereum Signed Message:
18
+ ${e.length}`);return"0x"+he(Il(Rt([n,e])),"base16")}async function YE(t,e,n,r,s,i){switch(n.t){case"eip191":return await ZE(t,e,n.s);case"eip1271":return await XE(t,e,n.s,r,s,i);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function ZE(t,e,n){const r=c1(n);return x1({payload:Oh(e),signature:r}).toLowerCase()===t.toLowerCase()}async function XE(t,e,n,r,s,i){const o=Ct(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",l=n.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),h=(GE(e)?e:Oh(e)).substring(2),f=a+h+c+u+l,p=await fetch(`${i||HE}/?chainId=${r}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:JE(),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 JE(){return Date.now()+Math.floor(Math.random()*1e3)}function QE(t){const e=An(t),n=e[0];if(n===0)throw new Error("No signatures found");const r=1+n*64;if(e.length<r)throw new Error("Transaction data too short for claimed signature count");if(e.length<100)throw new Error("Transaction too short");const s=e.slice(1,65);return vr.encode(s)}function e2(t){const e=An(t),n=new TextEncoder().encode("TransactionData::"),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const s=w1(r,{dkLen:32});return vr.encode(s)}function $h(t){const e=new Uint8Array(mn(t2(t)));return vr.encode(e)}function t2(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&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 Rh(t){const e=An(t),n=fv(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=sv(n),s=new TextEncoder().encode("TX"),i=Rt([s,new Uint8Array(r)]),o=Jm(i);return E1.encode(o).replace(/=+$/,"")}function Xo(t){const e=[];let n=BigInt(t);for(;n>=0x80n;)e.push(Number(n&0x7fn|0x80n)),n>>=7n;return e.push(Number(n)),new Uint8Array(e)}function n2(t){const e=An(t.signed.bodyBytes),n=An(t.signed.authInfoBytes),r=An(t.signature.signature),s=[];s.push(new Uint8Array([10])),s.push(Xo(e.length)),s.push(e),s.push(new Uint8Array([18])),s.push(Xo(n.length)),s.push(n),s.push(new Uint8Array([26])),s.push(Xo(r.length)),s.push(r);const i=Rt(s),o=mn(i);return he(o,"base16").toUpperCase()}const r2={pubnet:"Public Global Stellar Network ; September 2015",testnet:"Test SDF Network ; September 2015"},s2=0,Jo=2,Bh=5,Ph=72,i2=64,o2=20;function Qo(t,e){return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint32(e,!1)}function a2(t){for(let e=o2;e>=0;e--){const n=t.length-4-Ph*e;if(n<4||Qo(t,n)!==e)continue;let r=!0;for(let s=0;s<e;s++){const i=n+4+Ph*s;if(Qo(t,i+4)!==i2){r=!1;break}}if(r)return n}throw new Error("getStellarTransactionHash: could not locate envelope signature array")}function c2(t,e){const n=An(t);if(n.length<8)throw new Error("getStellarTransactionHash: envelope too short");const r=Qo(n,0);let s,i;switch(r){case s2:s=Jo,i=0;break;case Jo:s=Jo,i=4;break;case Bh:s=Bh,i=4;break;default:throw new Error(`getStellarTransactionHash: unsupported envelope type: ${r}`)}const o=a2(n),a=e?.split(":").pop()??"pubnet",c=r2[a];if(!c)throw new Error(`getStellarTransactionHash: unknown Stellar network: ${a}`);const l=mn(new TextEncoder().encode(c)),u=new Uint8Array([0,0,0,s]),h=Rt([l,u,n.slice(i,o)]);return he(mn(h),"base16")}function l2(t){const e=[];try{if(typeof t=="string")return e.push(t),e;if(typeof t!="object")return e;t?.id&&e.push(t.id);const n=t?.capabilities?.caip345?.transactionHashes;n&&e.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return e}const Ch="did:pkh:",u2={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},h2=t=>t?u2[t]||t:"",Us=t=>t?.split(":"),f2=t=>{const e=t&&Us(t);if(e)return t.includes(Ch)?e[3]:e[1]},d2=t=>{const e=t&&Us(t);if(e)return t.includes(Ch)?e[2]:e[0]},ks=t=>{const e=t&&Us(t);if(e)return e[2]+":"+e[3]},Ls=t=>{const e=t&&Us(t);if(e)return e.pop()};async function Nh(t){const{cacao:e,projectId:n}=t,{s:r,p:s}=e;let i;try{i=Uh(s,s.iss)}catch{return!1}const o=Ls(s.iss);try{return await YE(o,i,r,ks(s.iss),n)}catch{return!1}}function p2(t){const{cacao:e,request:n}=t,{p:r}=e;if(r.domain!==n.domain)return{valid:!1,reason:`domain mismatch: requested ${n.domain}, got ${r.domain}`};if(r.nonce!==n.nonce)return{valid:!1,reason:`nonce mismatch: requested ${n.nonce}, got ${r.nonce}`};const s=n.aud||n.uri,i=r.aud||r.uri;if(s&&i!==s)return{valid:!1,reason:`aud mismatch: requested ${s}, got ${i}`};if(n.chains?.length){const a=ks(r.iss);if(!a||!n.chains.includes(a))return{valid:!1,reason:`cacao issued for chain ${a} which was not requested`}}const o=Date.now();if(r.exp){const a=new Date(r.exp).getTime();if(isNaN(a))return{valid:!1,reason:`malformed exp: ${r.exp}`};if(a<o)return{valid:!1,reason:"cacao has expired"}}if(r.nbf){const a=new Date(r.nbf).getTime();if(isNaN(a))return{valid:!1,reason:`malformed nbf: ${r.nbf}`};if(a>o)return{valid:!1,reason:"cacao is not yet valid"}}return{valid:!0}}const Uh=(t,e)=>{const n=d2(e);if(!n)throw new Error("Invalid issuer: "+e);const r=`${t.domain} wants you to sign in with your ${h2(n)} account:`,s=Ls(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 o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${f2(e)}`,l=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,p=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(y=>`
19
+ - ${y}`).join("")}`:void 0,g=Fs(t.resources);if(g){const y=Ar(g);i=_2(i,y)}if(i&&/\r|\n/.test(i))throw new Error("Statement must not contain line breaks (`\\r` or `\\n`)");return[r,s,"",i,"",o,a,c,l,u,h,f,p,d].filter(y=>y!=null).join(`
20
+ `)};function g2(t){const e=JSON.stringify(t),n=new TextEncoder().encode(e),r=new Array(n.length);for(let s=0;s<n.length;s++)r[s]=String.fromCharCode(n[s]);return btoa(r.join(""))}function y2(t){const e=t+"=".repeat((4-t.length%4)%4),n=atob(e),r=new Uint8Array(n.length);for(let s=0;s<n.length;s++)r[s]=n.charCodeAt(s);return JSON.parse(new TextDecoder().decode(r))}function Tn(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?.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(s=>{const i=r[s];if(!Array.isArray(i))throw new Error(`Ability limits ${s} must be an array of objects, found: ${i}`);if(!i.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);i.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function w2(t,e,n,r={}){return n?.sort((s,i)=>s.localeCompare(i)),{att:{[t]:m2(e,n,r)}}}function m2(t,e,n={}){e=e?.sort((s,i)=>s.localeCompare(i));const r=e.map(s=>({[`${t}/${s}`]:[n]}));return Object.assign({},...r)}function kh(t){return Tn(t),`urn:recap:${g2(t).replace(/=/g,"")}`}function Ar(t){const e=y2(t.replace("urn:recap:",""));return Tn(e),e}function b2(t,e,n){const r=w2(t,e,n);return kh(r)}function v2(t){return t&&t.includes("urn:recap:")}function E2(t,e){const n=Ar(t),r=Ar(e),s=x2(n,r);return kh(s)}function x2(t,e){Tn(t),Tn(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,i)=>s.localeCompare(i)),r={att:{}};return n.forEach(s=>{Object.keys(t.att?.[s]||{}).concat(Object.keys(e.att?.[s]||{})).sort((i,o)=>i.localeCompare(o)).forEach(i=>{r.att[s]={...r.att[s],[i]:t.att[s]?.[i]||e.att[s]?.[i]}})}),r}function _2(t="",e){Tn(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 s=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 l={};c.forEach(h=>{l[h.ability]||(l[h.ability]=[]),l[h.ability].push(h.action)});const u=Object.keys(l).map(h=>(s++,`(${s}) '${h}': '${l[h].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const i=r.join(" "),o=`${n}${i}`;return`${t?t+" ":""}${o}`}function Lh(t){const e=Ar(t);Tn(e);const n=e.att?.eip155;return n?Object.keys(n).map(r=>r.split("/")[1]):[]}function Fh(t){const e=Ar(t);Tn(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(s=>{s?.[0]?.chains&&n.push(s[0].chains)})}),[...new Set(n.flat())]}function Fs(t){if(!t)return;const e=t?.[t.length-1];return v2(e)?e:void 0}const Mh="base10",$e="base16",Ee="base64pad",pt="base64url",Tr="utf8",qh=0,Nt=1,On=2,I2=0,jh=1,Or=12,ea=32;function S2(){const t=Mo.utils.randomPrivateKey(),e=Mo.getPublicKey(t);return{privateKey:he(t,$e),publicKey:he(e,$e)}}function ta(){const t=Zt(ea);return he(t,$e)}function D2(t,e){const n=Mo.getSharedSecret(_e(t,$e),_e(e,$e)),r=Ov(hs,n,void 0,void 0,ea);return he(r,$e)}function Ms(t){const e=hs(_e(t,$e));return he(e,$e)}function Ge(t){const e=hs(_e(t,Tr));return he(e,$e)}function zh(t){return _e(`${t}`,Mh)}function $n(t){return Number(he(t,Mh))}function Vh(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function qs(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function A2(t){const e=zh(typeof t.type<"u"?t.type:qh);if($n(e)===Nt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?_e(t.senderPublicKey,$e):void 0,r=typeof t.iv<"u"?_e(t.iv,$e):Zt(Or),s=_e(t.symKey,$e),i=Lu(s,r).encrypt(_e(t.message,Tr)),o=Kh({type:e,sealed:i,iv:r,senderPublicKey:n});return t.encoding===pt?Vh(o):o}function T2(t){const e=_e(t.symKey,$e),{sealed:n,iv:r}=$r({encoded:t.encoded,encoding:t.encoding}),s=Lu(e,r).decrypt(n);if(s===null)throw new Error("Failed to decrypt");return he(s,Tr)}function O2(t,e){const n=zh(On),r=Zt(Or),s=_e(t,Tr),i=Kh({type:n,sealed:s,iv:r});return e===pt?Vh(i):i}function $2(t,e){const{sealed:n}=$r({encoded:t,encoding:e});return he(n,Tr)}function Kh(t){if($n(t.type)===On)return he(Rt([t.type,t.sealed]),Ee);if($n(t.type)===Nt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return he(Rt([t.type,t.senderPublicKey,t.iv,t.sealed]),Ee)}return he(Rt([t.type,t.iv,t.sealed]),Ee)}function $r(t){const e=(t.encoding||Ee)===pt?qs(t.encoded):t.encoded,n=_e(e,Ee),r=n.slice(I2,jh),s=jh;if($n(r)===Nt){const c=s+ea,l=c+Or,u=n.slice(s,c),h=n.slice(c,l),f=n.slice(l);return{type:r,sealed:f,iv:h,senderPublicKey:u}}if($n(r)===On){const c=n.slice(s),l=Zt(Or);return{type:r,sealed:c,iv:l}}const i=s+Or,o=n.slice(s,i),a=n.slice(i);return{type:r,sealed:a,iv:o}}function R2(t,e){const n=$r({encoded:t,encoding:e?.encoding});return Hh({type:$n(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?he(n.senderPublicKey,$e):void 0,receiverPublicKey:e?.receiverPublicKey})}function Hh(t){const e=t?.type||qh;if(e===Nt){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 Wh(t){return t.type===Nt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Gh(t){return t.type===On}function B2(t){const e=_e(qs(t.x),Ee),n=_e(qs(t.y),Ee);return Rt([new Uint8Array([4]),e,n])}function P2(t,e){const[n,r,s]=t.split("."),i=_e(qs(s),Ee);if(i.length!==64)throw new Error("Invalid signature length");const o=i.slice(0,32),a=i.slice(32,64),c=`${n}.${r}`,l=hs(c),u=B2(e);if(!wE.verify(Rt([o,a]),l,u))throw new Error("Invalid signature");return Fi(t).payload}const C2="irn";function js(t){return t?.relay||{protocol:C2}}function Yn(t){const e=mE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function N2(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(r)){const i=s.replace(r,""),o=t[s];n[i]=o}}),n}function Yh(t){if(!t.includes("wc:")){const l=Th(t);l?.includes("wc:")&&(t=l)}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),s=t.substring(e+1,n).split("@"),i=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(i),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:U2(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:N2(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function U2(t){return t.startsWith("//")?t.substring(2):t}function k2(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(s=>{const i=s,o=n+e+i;t[i]&&(r[o]=t[i])}),r}function Zh(t){const e=new URLSearchParams,n={...k2(t.relay),symKey:t.symKey,...t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()},...t.methods&&{methods:t.methods.join(",")}};return Object.entries(n).sort(([r],[s])=>r.localeCompare(s)).forEach(([r,s])=>{s!==void 0&&e.append(r,String(s))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function zs(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}function Zn(t){const e=[];return t.forEach(n=>{const[r,s]=n.split(":");e.push(`${r}:${s}`)}),e}function Xh(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Zn(n.accounts))}),[...new Set(e)]}function L2(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.methods)}),[...new Set(e)]}function F2(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.events)}),[...new Set(e)]}function M2(t,e){const n=[];return Object.values(t).forEach(r=>{Zn(r.accounts).includes(e)&&n.push(...r.methods)}),n}function q2(t,e){const n=[];return Object.values(t).forEach(r=>{Zn(r.accounts).includes(e)&&n.push(...r.events)}),n}function Jh(t){return t.includes(":")}function j2(t){return Jh(t)?t.split(":")[0]:t}function Qh(t){const e={};if(!Rr(t))return e;for(const[n,r]of Object.entries(t)){const s=Jh(n)?[n]:r.chains,i=r.methods||[],o=r.events||[],a=j2(n);e[a]={...e[a],chains:Dn(s,e[a]?.chains),methods:Dn(i,e[a]?.methods),events:Dn(o,e[a]?.events)}}return e}function z2(t){const e={};return t?.forEach(n=>{const[r,s]=n.split(":");e[r]||(e[r]={accounts:[],chains:[],events:[],methods:[]}),e[r].accounts.push(n),e[r].chains?.push(`${r}:${s}`)}),e}function ef(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=z2(e);for(const[r,s]of Object.entries(n))s.methods?s.methods=Dn(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return n}function V2(t,e){const n=Qh(t),r=Qh(e),s={},i=Object.keys(n).concat(Object.keys(r));for(const o of i)s[o]={chains:Dn(n[o]?.chains,r[o]?.chains),methods:Dn(n[o]?.methods,r[o]?.methods),events:Dn(n[o]?.events,r[o]?.events)};return s}function Xn(t,e){return!!Array.isArray(t)}function Rr(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function de(t){return typeof t>"u"}function oe(t,e){return e&&de(t)?!0:typeof t=="string"&&!!t.trim().length}function na(t,e){return e&&de(t)?!0:typeof t=="number"&&!isNaN(t)}function K2(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),s=Object.keys(n);let i=!0;return In(s,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=Zn(a),h=n[o];(!In(Eh(o,h),u)||!In(h.methods,c)||!In(h.events,l))&&(i=!1)}),i):!1}function Br(t){return oe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function H2(t){if(oe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Br(n)}}return!1}function W2(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(oe(t,!1)){if(e(t))return!0;const n=Th(t);return e(n)}}catch{}return!1}function G2(t){return t?.proposer?.publicKey}function Y2(t){return t?.topic}function Z2(t,e){let n=null;return oe(t?.publicKey,!1)||(n=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function tf(t){let e=!0;return Xn(t)?t.length&&(e=t.every(n=>oe(n,!1))):e=!1,e}function X2(t,e,n){let r=null;return Xn(e)&&e.length?e.forEach(s=>{r||Br(s)||(r=te("UNSUPPORTED_CHAINS",`${n}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Br(t)||(r=te("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 J2(t,e,n){let r=null;return Object.entries(t).forEach(([s,i])=>{if(r)return;const o=X2(s,Eh(s,i),`${e} ${n}`);o&&(r=o)}),r}function Q2(t,e){let n=null;return Xn(t)?t.forEach(r=>{n||H2(r)||(n=te("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=te("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function ex(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=Q2(r?.accounts,`${e} namespace`);s&&(n=s)}),n}function tx(t,e){let n=null;return tf(t?.methods)?tf(t?.events)||(n=te("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=te("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function nf(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const s=tx(r,`${e}, namespace`);s&&(n=s)}),n}function nx(t,e,n){let r=null;if(t&&Rr(t)){const s=nf(t,e);s&&(r=s);const i=J2(t,e,n);i&&(r=i)}else r=M("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function ra(t,e){let n=null;if(t&&Rr(t)){const r=nf(t,e);r&&(n=r);const s=ex(t,e);s&&(n=s)}else n=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function rf(t){return oe(t.protocol,!0)}function rx(t,e){let n=!1;return t?t&&Xn(t)&&t.length&&t.forEach(r=>{n=rf(r)}):n=!0,n}function sx(t){return typeof t=="number"}function Le(t){return typeof t<"u"&&typeof t!==null}function ix(t){return!(!t||typeof t!="object"||!t.code||!na(t.code,!1)||!t.message||!oe(t.message,!1))}function ox(t){return!(de(t)||!oe(t.method,!1))}function ax(t){return!(de(t)||de(t.result)&&de(t.error)||!na(t.id,!1)||!oe(t.jsonrpc,!1))}function cx(t){return!(de(t)||!oe(t.name,!1))}function sf(t,e){return!(!Br(e)||!Xh(t).includes(e))}function lx(t,e,n){return oe(n,!1)?M2(t,e).includes(n):!1}function ux(t,e,n){return oe(n,!1)?q2(t,e).includes(n):!1}function of(t,e,n){let r=null;const s=hx(t),i=fx(e),o=Object.keys(s),a=Object.keys(i),c=af(Object.keys(t)),l=af(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
21
21
  Required: ${u.toString()}
22
22
  Received: ${Object.keys(e).toString()}`)),In(o,a)||(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
23
23
  Required: ${o.toString()}
24
24
  Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const f=Zn(e[h].accounts);f.includes(h)||(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${h}
25
25
  Required: ${h}
26
- Approved: ${f.toString()}`))}),o.forEach(h=>{r||(In(s[h].methods,i[h].methods)?In(s[h].events,i[h].events)||(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${h}`)):r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function hx(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:t[n].chains?.forEach(r=>{e[r]={methods:t[n].methods,events:t[n].events}})}),e}function af(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function fx(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:Zn(t[n].accounts)?.forEach(r=>{e[r]={accounts:t[n].accounts.filter(s=>s.includes(`${r}:`)),methods:t[n].methods,events:t[n].events}})}),e}function dx(t,e){return ta(t,!1)&&t<=e.max&&t>=e.min}function cf(){const t=Dr();return new Promise(e=>{switch(t){case ze.browser:e(px());break;case ze.reactNative:e(gx());break;case ze.node:e(yx());break;default:e(!0)}})}function px(){return Gn()&&navigator?.onLine}async function gx(){return an()&&typeof global<"u"&&global?.NetInfo?(await global?.NetInfo.fetch())?.isConnected:!0}function yx(){return!0}function wx(t){switch(Dr()){case ze.browser:mx(t);break;case ze.reactNative:bx(t);break}}function mx(t){!an()&&Gn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function bx(t){an()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function vx(){return Gn()&&xt.getDocument()?xt.getDocument()?.visibilityState==="visible":!0}const ra={};let Pr=class{static get(e){return ra[e]}static set(e,n){ra[e]=n}static delete(e){delete ra[e]}};function Ex(t){const e=vr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function xx({publicKey:t,signature:e,payload:n}){const r=js(n.method),s=128|parseInt(n.version?.toString()||"4"),i=Sx(n.address),o=n.era==="00"?new Uint8Array([0]):js(n.era);if(o.length!==1&&o.length!==2)throw new Error("Invalid era length");const a=parseInt(n.nonce,16),c=new Uint8Array([a&255,a>>8&255]),l=BigInt(`0x${Ix(n.tip)}`),u=Ax(l),h=new Uint8Array([0,...t,i,...e,...o,...c,...u,...r]),f=Dx(h.length+1);return new Uint8Array([...f,s,...h])}function _x(t){const e=js(t),n=xE.blake2b(e,void 0,32);return"0x"+he(n,"base16")}function js(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Ix(t){return t.startsWith("0x")?t.slice(2):t}function Sx(t){const e=vr.decode(t)[0];return e===42?0:e===60?2:1}function Dx(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 Ax(t){if(t<1n<<6n)return new Uint8Array([Number(t<<2n)]);if(t<1n<<14n){const e=t<<2n|0x01n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn)])}else if(t<1n<<30n){const e=t<<2n|0x02n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn),Number(e>>16n&0xffn),Number(e>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function Tx(t){const e=js(t.signature),n=Ex(t.transaction.address),r=xx({publicKey:n,signature:e,payload:t.transaction}),s=he(r,"base16");return _x(s)}const Ox=new Set(["TransferFactory_Transfer","DelegateProxy_TransferFactory_Transfer"]);function $x(t){const e=t?.commands;if(!Array.isArray(e))return[];const n=[];for(const r of e){const s=r?.ExerciseCommand;if(!s||!Ox.has(s.choice))continue;const i=s.choiceArgument?.transfer;!i?.amount||!i?.instrumentId?.id||n.push({amount:String(i.amount),instrumentId:String(i.instrumentId.id)})}return n}function Rx(t,e){const n=e?.payload?.updateId;if(!n)return[];const r=$x(t);return r.length===0?[String(n)]:r.map(s=>`${n}:${s.amount}:${s.instrumentId}`)}function lf({logger:t,name:e}){const n=typeof t=="string"?Qa({opts:{level:t,name:e}}).logger:t;return n.level=typeof t=="string"?t:t.level,n}const Bx="PARSE_ERROR",Px="INVALID_REQUEST",Cx="METHOD_NOT_FOUND",Nx="INVALID_PARAMS",uf="INTERNAL_ERROR",sa="SERVER_ERROR",Ux=[-32700,-32600,-32601,-32602,-32603],Cr={[Bx]:{code:-32700,message:"Parse error"},[Px]:{code:-32600,message:"Invalid Request"},[Cx]:{code:-32601,message:"Method not found"},[Nx]:{code:-32602,message:"Invalid params"},[uf]:{code:-32603,message:"Internal error"},[sa]:{code:-32e3,message:"Server error"}},hf=sa;function kx(t){return Ux.includes(t)}function ff(t){return Object.keys(Cr).includes(t)?Cr[t]:Cr[hf]}function Lx(t){const e=Object.values(Cr).find(n=>n.code===t);return e||Cr[hf]}function Fx(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var ia={};/*! *****************************************************************************
26
+ Approved: ${f.toString()}`))}),o.forEach(h=>{r||(In(s[h].methods,i[h].methods)?In(s[h].events,i[h].events)||(r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${h}`)):r=M("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function hx(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:t[n].chains?.forEach(r=>{e[r]={methods:t[n].methods,events:t[n].events}})}),e}function af(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function fx(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:Zn(t[n].accounts)?.forEach(r=>{e[r]={accounts:t[n].accounts.filter(s=>s.includes(`${r}:`)),methods:t[n].methods,events:t[n].events}})}),e}function dx(t,e){return na(t,!1)&&t<=e.max&&t>=e.min}function cf(){const t=Dr();return new Promise(e=>{switch(t){case je.browser:e(px());break;case je.reactNative:e(gx());break;case je.node:e(yx());break;default:e(!0)}})}function px(){return Gn()&&navigator?.onLine}async function gx(){return an()&&typeof global<"u"&&global?.NetInfo?(await global?.NetInfo.fetch())?.isConnected:!0}function yx(){return!0}function wx(t){switch(Dr()){case je.browser:mx(t);break;case je.reactNative:bx(t);break}}function mx(t){!an()&&Gn()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function bx(t){an()&&typeof global<"u"&&global?.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function vx(){return Gn()&&xt.getDocument()?xt.getDocument()?.visibilityState==="visible":!0}const sa={};class Pr{static get(e){return sa[e]}static set(e,n){sa[e]=n}static delete(e){delete sa[e]}}function Ex(t){const e=vr.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function xx({publicKey:t,signature:e,payload:n}){const r=Vs(n.method),s=128|parseInt(n.version?.toString()||"4"),i=Sx(n.address),o=n.era==="00"?new Uint8Array([0]):Vs(n.era);if(o.length!==1&&o.length!==2)throw new Error("Invalid era length");const a=parseInt(n.nonce,16),c=new Uint8Array([a&255,a>>8&255]),l=BigInt(`0x${Ix(n.tip)}`),u=Ax(l),h=new Uint8Array([0,...t,i,...e,...o,...c,...u,...r]),f=Dx(h.length+1);return new Uint8Array([...f,s,...h])}function _x(t){const e=Vs(t),n=xE.blake2b(e,void 0,32);return"0x"+he(n,"base16")}function Vs(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Ix(t){return t.startsWith("0x")?t.slice(2):t}function Sx(t){const e=vr.decode(t)[0];return e===42?0:e===60?2:1}function Dx(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 Ax(t){if(t<1n<<6n)return new Uint8Array([Number(t<<2n)]);if(t<1n<<14n){const e=t<<2n|0x01n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn)])}else if(t<1n<<30n){const e=t<<2n|0x02n;return new Uint8Array([Number(e&0xffn),Number(e>>8n&0xffn),Number(e>>16n&0xffn),Number(e>>24n&0xffn)])}else throw new Error("BigInt compact encoding not supported > 2^30")}function Tx(t){const e=Vs(t.signature),n=Ex(t.transaction.address),r=xx({publicKey:n,signature:e,payload:t.transaction}),s=he(r,"base16");return _x(s)}const Ox=new Set(["TransferFactory_Transfer","DelegateProxy_TransferFactory_Transfer"]);function $x(t){const e=t?.commands;if(!Array.isArray(e))return[];const n=[];for(const r of e){const s=r?.ExerciseCommand;if(!s||!Ox.has(s.choice))continue;const i=s.choiceArgument?.transfer;!i?.amount||!i?.instrumentId?.id||n.push({amount:String(i.amount),instrumentId:String(i.instrumentId.id)})}return n}function Rx(t,e){const n=e?.payload?.updateId;if(!n)return[];const r=$x(t);return r.length===0?[String(n)]:r.map(s=>`${n}:${s.amount}:${s.instrumentId}`)}function lf({logger:t,name:e}){const n=typeof t=="string"?ec({opts:{level:t,name:e}}).logger:t;return n.level=typeof t=="string"?t:t.level,n}const Bx="PARSE_ERROR",Px="INVALID_REQUEST",Cx="METHOD_NOT_FOUND",Nx="INVALID_PARAMS",uf="INTERNAL_ERROR",ia="SERVER_ERROR",Ux=[-32700,-32600,-32601,-32602,-32603],Cr={[Bx]:{code:-32700,message:"Parse error"},[Px]:{code:-32600,message:"Invalid Request"},[Cx]:{code:-32601,message:"Method not found"},[Nx]:{code:-32602,message:"Invalid params"},[uf]:{code:-32603,message:"Internal error"},[ia]:{code:-32e3,message:"Server error"}},hf=ia;function kx(t){return Ux.includes(t)}function ff(t){return Object.keys(Cr).includes(t)?Cr[t]:Cr[hf]}function Lx(t){const e=Object.values(Cr).find(n=>n.code===t);return e||Cr[hf]}function Fx(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var oa={};/*! *****************************************************************************
27
27
  Copyright (c) Microsoft Corporation.
28
28
 
29
29
  Permission to use, copy, modify, and/or distribute this software for any
@@ -36,5 +36,5 @@ ${e.length}`);return"0x"+he(_l(Rt([n,e])),"base16")}async function YE(t,e,n,r,s,
36
36
  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
37
37
  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
38
38
  PERFORMANCE OF THIS SOFTWARE.
39
- ***************************************************************************** */var oa=function(t,e){return oa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},oa(t,e)};function Mx(t,e){oa(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var aa=function(){return aa=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},aa.apply(this,arguments)};function qx(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 s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]]);return n}function zx(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function jx(t,e){return function(n,r){e(n,r,t)}}function Vx(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Kx(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function Hx(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Wx(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function Gx(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function ca(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 df(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function Yx(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(df(arguments[e]));return t}function Zx(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<n;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Nr(t){return this instanceof Nr?(this.v=t,this):new Nr(t)}function Xx(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(d,g){i.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(i[0][3],d)}}function c(f){f.value instanceof Nr?Promise.resolve(f.value.v).then(l,u):h(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function Jx(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:Nr(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function Qx(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 ca=="function"?ca(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function e_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function t_(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 n_(t){return t&&t.__esModule?t:{default:t}}function r_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function s_(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 i_=Object.freeze({__proto__:null,get __assign(){return aa},__asyncDelegator:Jx,__asyncGenerator:Xx,__asyncValues:Qx,__await:Nr,__awaiter:Kx,__classPrivateFieldGet:r_,__classPrivateFieldSet:s_,__createBinding:Wx,__decorate:zx,__exportStar:Gx,__extends:Mx,__generator:Hx,__importDefault:n_,__importStar:t_,__makeTemplateObject:e_,__metadata:Vx,__param:jx,__read:df,__rest:qx,__spread:Yx,__spreadArrays:Zx,__values:ca}),o_=ma(i_),Ut={},pf;function a_(){if(pf)return Ut;pf=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.isBrowserCryptoAvailable=Ut.getSubtleCrypto=Ut.getBrowerCrypto=void 0;function t(){return lt?.crypto||lt?.msCrypto||{}}Ut.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Ut.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Ut.isBrowserCryptoAvailable=n,Ut}var kt={},gf;function c_(){if(gf)return kt;gf=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.isBrowser=kt.isNode=kt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}kt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}kt.isNode=e;function n(){return!t()&&!e()}return kt.isBrowser=n,kt}var yf;function l_(){return yf||(yf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=o_;e.__exportStar(a_(),t),e.__exportStar(c_(),t)}(ia)),ia}var u_=l_();function je(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(je(t))}function Lt(t,e,n){return{id:n||je(),jsonrpc:"2.0",method:t,params:e}}function Vs(t,e){return{id:t,jsonrpc:"2.0",result:e}}function la(t,e,n){return{id:t,jsonrpc:"2.0",error:h_(e)}}function h_(t,e){return typeof t>"u"?ff(uf):(typeof t=="string"&&(t=Object.assign(Object.assign({},ff(sa)),{message:t})),kx(t.code)&&(t=Lx(t.code)),t)}class f_{}class d_ extends f_{constructor(){super()}}class p_ extends d_{constructor(e){super()}}const g_="^wss?:";function y_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function w_(t,e){const n=y_(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function wf(t){return w_(t,g_)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function mf(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ua(t){return mf(t)&&"method"in t}function Ks(t){return mf(t)&&(gt(t)||Ye(t))}function gt(t){return"result"in t}function Ye(t){return"error"in t}class b_ extends p_{constructor(e){super(e),this.events=new Je.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(Lt(e.method,e.params||[],e.id||ln().toString()),n)}async requestStrict(e,n){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(i){s(i)}this.events.on(`${e.id}`,i=>{Ye(i)?s(i.error):r(i.result)});try{await this.connection.send(e,n)}catch(i){s(i)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Ks(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 v_=()=>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"),E_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",bf=t=>t.split("?")[0],vf=10,x_=v_();let __=class{constructor(e){if(this.url=e,this.events=new Je.EventEmitter,this.registering=!1,!wf(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(rr(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!wf(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,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const s=u_.isReactNative()?void 0:{rejectUnauthorized:!m_(e)},i=new x_(e,[],s);E_()?i.onerror=o=>{const a=o;r(this.emitError(a.error))}:i.on("error",o=>{r(this.emitError(o))}),i.onopen=()=>{this.onOpen(i),n(i)}})}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"?Un(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),s=r.message||r.toString(),i=la(e,s);this.events.emit("payload",i)}parseError(e,n=this.url){return Fx(e,bf(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>vf&&this.events.setMaxListeners(vf)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${bf(this.url)}`));return this.events.emit("register_error",n),n}};function I_(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ef(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function xf(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const S_="[object RegExp]",D_="[object String]",A_="[object Number]",T_="[object Boolean]",_f="[object Arguments]",O_="[object Symbol]",$_="[object Date]",R_="[object Map]",B_="[object Set]",P_="[object Array]",C_="[object Function]",N_="[object ArrayBuffer]",ha="[object Object]",U_="[object Error]",k_="[object DataView]",L_="[object Uint8Array]",F_="[object Uint8ClampedArray]",M_="[object Uint16Array]",q_="[object Uint32Array]",z_="[object BigUint64Array]",j_="[object Int8Array]",V_="[object Int16Array]",K_="[object Int32Array]",H_="[object BigInt64Array]",W_="[object Float32Array]",G_="[object Float64Array]";function If(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 Y_(t,e,n){return Ur(t,e,void 0,void 0,void 0,void 0,n)}function Ur(t,e,n,r,s,i,o){const a=o(t,e,n,r,s,i);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 kr(t,e,i,o)}return kr(t,e,i,o)}function kr(t,e,n,r){if(Object.is(t,e))return!0;let s=xf(t),i=xf(e);if(s===_f&&(s=ha),i===_f&&(i=ha),s!==i)return!1;switch(s){case D_:return t.toString()===e.toString();case A_:{const c=t.valueOf(),l=e.valueOf();return I_(c,l)}case T_:case $_:case O_:return Object.is(t.valueOf(),e.valueOf());case S_:return t.source===e.source&&t.flags===e.flags;case C_: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(s){case R_:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ur(l,e.get(c),c,t,e,n,r))return!1;return!0}case B_:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(p=>Ur(h,p,void 0,t,e,n,r));if(f===-1)return!1;l.splice(f,1)}return!0}case P_:case L_:case F_:case M_:case q_:case z_:case j_:case V_:case K_:case H_:case W_:case G_:{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(!Ur(t[c],e[c],c,t,e,n,r))return!1;return!0}case N_:return t.byteLength!==e.byteLength?!1:kr(new Uint8Array(t),new Uint8Array(e),n,r);case k_:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:kr(new Uint8Array(t),new Uint8Array(e),n,r);case U_:return t.name===e.name&&t.message===e.message;case ha:{if(!(kr(t.constructor,e.constructor,n,r)||If(t)&&If(e)))return!1;const l=[...Object.keys(t),...Ef(t)],u=[...Object.keys(e),...Ef(e)];if(l.length!==u.length)return!1;for(let h=0;h<l.length;h++){const f=l[h],p=t[f];if(!Object.hasOwn(e,f))return!1;const d=e[f];if(!Ur(p,d,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function Z_(){}function X_(t,e){return Y_(t,e,Z_)}const Sf="wc",Df=2,fa="core",yt=`${Sf}@2:${fa}:`,J_={logger:"error"},Q_={database:":memory:"},eI="crypto",Af="client_ed25519_seed",tI=F.ONE_DAY,nI="keychain",rI="0.3",sI="messages",iI="0.3",oI=F.SIX_HOURS,aI="publisher",Tf="irn",cI="error",Of="wss://relay.walletconnect.org",lI="relayer",se={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},uI="_subscription",Ze={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},hI=.1,da="2.25.0",ee={link_mode:"link_mode",relay:"relay"},Hs={inbound:"inbound",outbound:"outbound"},fI="0.3",dI="WALLETCONNECT_CLIENT_ID",$f="WALLETCONNECT_LINK_MODE_APPS",Ve={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},pI="subscription",gI="0.3",yI="pairing",wI="0.3",Lr={wc_pairingDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:F.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:F.ONE_DAY,prompt:!1,tag:0},res:{ttl:F.ONE_DAY,prompt:!1,tag:0}}},Rn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},it={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},mI="history",bI="0.3",vI="expirer",Xe={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},EI="0.3",xI="verify-api",_I="https://verify.walletconnect.com",Rf="https://verify.walletconnect.org",Fr=Rf,II=`${Fr}/v3`,SI=[_I,Rf],DI="echo",AI="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"},Ft={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"},ot={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Bn={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Pn={authenticated_session_approve_started:"authenticated_session_approve_started",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"},Mr={no_internet_connection:"no_internet_connection",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"},TI=.1,OI="event-client",$I=86400,RI="https://pulse.walletconnect.org/batch";let BI=class{constructor(e,n){this.core=e,this.logger=n,this.keychain=new Map,this.name=nI,this.version=rI,this.initialized=!1,this.storagePrefix=yt,this.init=async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}},this.has=r=>(this.isInitialized(),this.keychain.has(r)),this.set=async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()},this.get=r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(i)}return s},this.del=async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()},this.core=e,this.logger=Fe(n,this.name)}get context(){return Be(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Wo(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Go(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}};class PI{constructor(e,n,r){this.core=e,this.logger=n,this.name=eI,this.randomSessionIdentifier=ea(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=s=>(this.isInitialized(),this.keychain.has(s)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),i=Wc(s),o=Hc(i.publicKey);return this.clientId=o,o},this.generateKeyPair=()=>{this.isInitialized();const s=S2();return this.setPrivateKey(s.publicKey,s.privateKey)},this.signJWT=async s=>{this.isInitialized();const i=await this.getClientSeed(),o=Wc(i),a=this.randomSessionIdentifier;return await sw(a,s,tI,o)},this.generateSharedKey=(s,i,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=D2(a,i);return this.setSymKey(c,o)},this.setSymKey=async(s,i)=>{this.isInitialized();const o=i||Fs(s);return await this.keychain.set(o,s),o},this.deleteKeyPair=async s=>{this.isInitialized(),await this.keychain.del(s)},this.deleteSymKey=async s=>{this.isInitialized(),await this.keychain.del(s)},this.encode=async(s,i,o)=>{this.isInitialized();const a=Hh(o),c=rr(i);if(Gh(a))return O2(c,o?.encoding);if(Wh(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const l=this.getSymKey(s),{type:u,senderPublicKey:h}=a;return A2({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})},this.decode=async(s,i,o)=>{this.isInitialized();const a=R2(i,o);if(Gh(a)){const c=$2(i,o?.encoding);return Un(c)}if(Wh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=T2({symKey:c,encoded:i,encoding:o?.encoding});return Un(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(s,i=Ee)=>{const o=$r({encoded:s,encoding:i});return $n(o.type)},this.getPayloadSenderPublicKey=(s,i=Ee)=>{const o=$r({encoded:s,encoding:i});return o.senderPublicKey?he(o.senderPublicKey,$e):void 0},this.core=e,this.logger=Fe(n,this.name),this.keychain=r||new BI(this.core,this.logger)}get context(){return Be(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(Af)}catch{e=ea(),await this.keychain.set(Af,e)}return _e(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class CI extends og{constructor(e,n){super(e,n),this.logger=e,this.core=n,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=sI,this.version=iI,this.initialized=!1,this.storagePrefix=yt,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}},this.set=async(r,s,i)=>{this.isInitialized();const o=Ge(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),i===Hs.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,{...c,[o]:s})}return await this.persist(),o},this.get=r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s},this.getWithoutAck=r=>{this.isInitialized();const s={};for(const i of r){const o=this.messagesWithoutClientAck.get(i)||{};s[i]=Object.values(o)}return s},this.has=(r,s)=>{this.isInitialized();const i=this.get(r),o=Ge(s);return typeof i[o]<"u"},this.ack=async(r,s)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(r);if(typeof i>"u")return;const o=Ge(s);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,i),await this.persist()},this.del=async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()},this.logger=Fe(e,this.name),this.core=n}get context(){return Be(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,Wo(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Wo(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Go(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Go(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class NI extends ag{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.events=new Je.EventEmitter,this.name=aI,this.queue=new Map,this.publishTimeout=F.toMiliseconds(F.ONE_MINUTE),this.initialPublishTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(r,s,i)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:i}});const o=i?.ttl||oI,a=i?.prompt||!1,c=i?.tag||0,l=i?.id||ln().toString(),u=Yn(qs().protocol),h={id:l,method:i?.publishMethod||u.publish,params:{topic:r,message:s,ttl:o,prompt:a,tag:c,attestation:i?.attestation,...i?.tvf}},f=`Failed to publish payload, please try again. id:${l} tag:${c}`;try{de(h.params?.prompt)&&delete h.params?.prompt,de(h.params?.tag)&&delete h.params?.tag;const p=new Promise(async d=>{const g=({id:v})=>{h.id?.toString()===v.toString()&&(this.removeRequestFromQueue(v),this.relayer.events.removeListener(se.publish,g),d())};this.relayer.events.on(se.publish,g);const y=st(new Promise((v,A)=>{this.rpcPublish(h,i).then(v).catch(w=>{this.logger.warn(w,w?.message),A(w)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${l} tag:${c}`);try{await y,this.events.removeListener(se.publish,g)}catch(v){this.queue.set(l,{request:h,opts:i,attempt:1}),this.logger.warn(v,v?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,topic:r,message:s,opts:i}}),await st(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),i?.internal?.throwOnFailedPublish)throw p}finally{this.queue.delete(l)}},this.publishCustom=async r=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:s,opts:i={}}=r,{attestation:o,tvf:a,publishMethod:c,prompt:l,tag:u,ttl:h=F.FIVE_MINUTES}=i,f=i.id||ln().toString(),p=Yn(qs().protocol),d=c||p.publish,g={id:f,method:d,params:{...s,ttl:h,prompt:l,tag:u,attestation:o,...a}},y=`Failed to publish custom payload, please try again. id:${f} tag:${u}`;try{de(g.params?.prompt)&&delete g.params?.prompt,de(g.params?.tag)&&delete g.params?.tag;const v=new Promise(async A=>{const w=({id:x})=>{g.id?.toString()===x.toString()&&(this.removeRequestFromQueue(x),this.relayer.events.removeListener(se.publish,w),A())};this.relayer.events.on(se.publish,w);const m=st(new Promise((x,_)=>{this.rpcPublish(g,i).then(x).catch(T=>{this.logger.warn(T,T?.message),_(T)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${d} id:${f} tag:${u}`);try{await m,this.events.removeListener(se.publish,w)}catch(x){this.queue.set(f,{request:g,opts:i,attempt:1}),this.logger.warn(x,x?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:f,payload:s,opts:i}}),await st(v,this.publishTimeout,y)}catch(v){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(v),i?.internal?.throwOnFailedPublish)throw v}finally{this.queue.delete(f)}},this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.relayer=e,this.logger=Fe(n,this.name),this.registerEventListeners()}get context(){return Be(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(se.publish,{...e,...n}),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{const r=e.attempt+1;this.queue.set(n,{...e,attempt:r}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(pn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(se.connection_stalled);return}this.checkQueue()}),this.relayer.on(se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class UI{constructor(){this.map=new Map,this.set=(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])},this.get=e=>this.map.get(e)||[],this.exists=(e,n)=>this.get(e).includes(n),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 s=r.filter(i=>i!==n);if(!s.length){this.map.delete(e);return}this.map.set(e,s)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}class kI extends ug{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.subscriptions=new Map,this.topicMap=new UI,this.events=new Je.EventEmitter,this.name=pI,this.version=gI,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=yt,this.subscribeTimeout=F.toMiliseconds(F.ONE_MINUTE),this.initialSubscribeTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(r,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const i=qs(s),o={topic:r,relay:i,transportType:s?.transportType};s?.internal?.skipSubscribe||this.pending.set(r,o);const a=await this.rpcSubscribe(r,i,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),a}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}},this.unsubscribe=async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)},this.isSubscribed=r=>new Promise(s=>{s(this.topicMap.topics.includes(r))}),this.isKnownTopic=r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(i=>i.topic===r))}),this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(pn.pulse,async()=>{await this.checkPending()}),this.events.on(Ve.created,async r=>{const s=Ve.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(Ve.deleted,async r=>{const s=Ve.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})},this.relayer=e,this.logger=Fe(n,this.name),this.clientId=""}get context(){return Be(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 s=>await this.unsubscribeById(e,s,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 s=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s);const i=qs(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,n,r){const s=await this.getSubscriptionId(e);if(r?.internal?.skipSubscribe)return s;(!r||r?.transportType===ee.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const i={method:Yn(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});const o=r?.internal?.throwOnFailedPublish;try{if(r?.transportType===ee.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(i).catch(l=>this.logger.warn(l))},F.toMiliseconds(F.ONE_SECOND)),s;const a=new Promise(async l=>{const u=h=>{h.topic===e&&(this.events.removeListener(Ve.created,u),l(h.id))};this.events.on(Ve.created,u);try{const h=await st(new Promise((f,p)=>{this.relayer.request(i).catch(d=>{this.logger.warn(d,d?.message),p(d)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ve.created,u),l(h)}catch{}}),c=await st(a,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?s:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(se.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const n=e[0].relay,r={method:Yn(n.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await st(new Promise((s,i)=>{this.relayer.request(r).then(s).catch(o=>{this.logger.warn(o),i(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(se.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Yn(n.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await st(new Promise((i,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(se.connection_stalled)}return s}rpcUnsubscribe(e,n,r){const s={method:Yn(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,n){this.setSubscription(e,{...n,id:e}),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,{...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,{...n}),this.topicMap.set(n.topic,e),this.events.emit(Ve.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}=M("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(Ve.deleted,{...r,reason:n})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ve.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 s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(Ve.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>n.topic===this.subscriptions.get(n.id)?.topic)){const{message:n}=M("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){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(e.map(async n=>({...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 VE(F.toMiliseconds(F.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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Ge(e+await this.getClientId())}}class LI extends cg{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Je.EventEmitter,this.name=lI,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=F.toMiliseconds(F.THIRTY_SECONDS+F.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=F.toMiliseconds(F.ONE_SECOND*2),this.stalledRestartMaxInterval=F.toMiliseconds(F.THIRTY_SECONDS),this.request=async n=>{this.logger.debug("Publishing Request Payload");const r=n.id||ln().toString();await this.toEstablishConnection();try{this.logger.trace({id:r,method:n.method,topic:n.params?.topic},"relayer.request - publishing...");const s=`${r}:${n.params?.tag||""}`;this.requestsInFlight.push(s);const i=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(o=>o!==s),i}catch(s){throw this.logger.debug(`Failed to Publish Request: ${r}`),s}},this.resetPingTimeout=()=>{Cs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(n){this.logger.warn(n,n?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=n=>{this.onProviderPayload(n),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(se.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(se.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(r=>this.logger.warn(r))},this.registerProviderListeners=()=>{this.provider.on(Ze.payload,this.onPayloadHandler),this.provider.on(Ze.connect,this.onConnectHandler),this.provider.on(Ze.disconnect,this.onDisconnectHandler),this.provider.on(Ze.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=lf({logger:e.logger??cI,name:this.name}),this.messages=new CI(this.logger,e.core),this.subscriber=new kI(this,this.logger),this.publisher=new NI(this,this.logger),this.projectId=e.projectId,this.relayUrl=e.relayUrl||Of,TE()?this.packageName=Eh():OE()&&(this.bundleId=Eh()),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 Be(this.logger)}get connected(){return this.provider?.connection?.socket?.readyState===1}get connecting(){return this.provider?.connection?.socket?.readyState===0||this.connectPromise!==void 0}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:ee.relay},Hs.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){this.isInitialized(),(!n?.transportType||n?.transportType==="relay")&&await this.toEstablishConnection();const r=n?.internal?.throwOnFailedPublish??!0;let s=this.subscriber.topicMap.get(e)?.[0]||"",i;const o=a=>{a.topic===e&&(this.subscriber.off(Ve.created,o),i())};return await Promise.all([new Promise(a=>{i=a,this.subscriber.on(Ve.created,o)}),new Promise((a,c)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:r},...n}).then(l=>{s=l||s,a()}).catch(l=>{r?c(l):a()})})]),s}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 st(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}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=this.connect(e).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.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await cf())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,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const s=fe(F.FIVE_MINUTES),i={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,i)}this.events.emit(se.message,e),await this.recordMessageEvent(e,Hs.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let n=1;try{for(;n<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise((r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ze.disconnect,i),st(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>r()).catch(s).finally(()=>{this.provider.off(Ze.disconnect,i),clearTimeout(this.reconnectTimeout)})}),await new Promise((r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ze.disconnect,i),this.subscriber.start().then(r).catch(s).finally(()=>{this.provider.off(Ze.disconnect,i)})}),this.hasExperiencedNetworkDisruption=!1}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,F.toMiliseconds(n*1))),n++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Cs())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await st(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new b_(new __(CE({sdkVersion:da,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:s}=e;await this.messages.set(r,s,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 s=this.messages.has(n,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ua(e)){if(!e.method.endsWith(uI))return;const n=e.params,{topic:r,message:s,publishedAt:i,attestation:o}=n.data,a={topic:r,message:s,publishedAt:i,transportType:ee.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:n.id,...a}),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ks(e)&&this.events.emit(se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Hs.inbound),this.events.emit(se.message,e))}async acknowledgePayload(e){const n=Vs(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(Ze.payload,this.onPayloadHandler),this.provider.off(Ze.connect,this.onConnectHandler),this.provider.off(Ze.disconnect,this.onDisconnectHandler),this.provider.off(Ze.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await cf();wx(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(pn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&vx())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(se.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(se.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},F.toMiliseconds(hI))}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}}class Cn extends lg{constructor(e,n,r,s=yt,i=void 0){super(e,n,r,s),this.core=e,this.logger=n,this.name=r,this.map=new Map,this.version=fI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!de(o)?this.map.set(this.getKey(o),o):G2(o)?this.map.set(o.id,o):Y2(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},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())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>X_(a[c],o[c]))):this.values),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={...this.getData(o),...a};this.map.set(o,c),await this.persist()},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=Fe(n,this.name),this.storagePrefix=s,this.getKey=i}get context(){return Be(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:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return 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}=M("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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class FI{constructor(e,n){this.core=e,this.logger=n,this.name=yI,this.version=wI,this.events=new Ys,this.initialized=!1,this.storagePrefix=yt,this.ignoredPayloadTypes=[Nt],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]},this.create=async r=>{this.isInitialized();const s=ea(),i=await this.core.crypto.setSymKey(s),o=fe(F.FIVE_MINUTES),a={protocol:Tf},c={topic:i,expiry:o,relay:a,active:!1,methods:r?.methods},l=Zh({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Rn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:r?.transportType,internal:r?.internal}),{topic:i,uri:l}},this.pair=async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[wt.pairing_started]}});this.isValidPair(r,s);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Yh(r.uri);s.props.properties.topic=i,s.addTrace(wt.pairing_uri_validation_success),s.addTrace(wt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),s.addTrace(wt.existing_pairing),u.active)throw s.setError(Ft.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);s.addTrace(wt.pairing_not_expired)}const h=c||fe(F.FIVE_MINUTES),f={topic:i,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(i,h),await this.pairings.set(i,f),s.addTrace(wt.store_new_pairing),r.activatePairing&&await this.activate({topic:i}),this.events.emit(Rn.create,f),s.addTrace(wt.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),s.addTrace(wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Ft.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw s.setError(Ft.subscribe_pairing_topic_failure),p}return s.addTrace(wt.subscribe_pairing_topic_success),f},this.activate=async({topic:r})=>{this.isInitialized();const s=fe(F.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const i=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Sn();this.events.once(J("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})},this.updateMetadata=async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))},this.formatUriFromPairing=r=>{this.isInitialized();const{topic:s,relay:i,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Zh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:i,expiryTimestamp:o,methods:a})},this.sendRequest=async(r,s,i)=>{const o=Lt(s,i),a=await this.core.crypto.encode(r,o),c=Lr[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,s,i)=>{const o=Vs(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Lr[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)},this.sendError=async(r,s,i)=>{const o=la(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Lr[c]?Lr[c].res:Lr.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)},this.deletePairing=async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])},this.cleanup=async()=>{const r=this.pairings.getAll().filter(s=>cn(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))},this.onRelayEventRequest=async r=>{const{topic:s,payload:i}=r;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,i);default:return await this.onUnknownRpcMethodRequest(s,i)}},this.onRelayEventResponse=async r=>{const{topic:s,payload:i}=r,o=(await this.core.history.get(s,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,i);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(r,s)=>{const{id:i}=s;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.events.emit(Rn.ping,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}},this.onPairingPingResponse=(r,s)=>{const{id:i}=s;setTimeout(()=>{gt(s)?this.events.emit(J("pairing_ping",i),{}):Ye(s)&&this.events.emit(J("pairing_ping",i),{error:s.error})},500)},this.onPairingDeleteRequest=async(r,s)=>{const{id:i}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Rn.delete,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(r,s)=>{const{id:i,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,r,a),this.logger.error(a)}catch(a){await this.sendError(i,r,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=r=>{this.registeredMethods.includes(r)||this.logger.error(te("WC_METHOD_UNSUPPORTED",r))},this.isValidPair=(r,s)=>{if(!Le(r)){const{message:o}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(!W2(r.uri)){const{message:o}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(Ft.malformed_pairing_uri),new Error(o)}const i=Yh(r?.uri);if(!i?.relay?.protocol){const{message:o}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(!i?.symKey){const{message:o}=M("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(i?.expiryTimestamp&&F.toMiliseconds(i?.expiryTimestamp)<Date.now()){s.setError(Ft.pairing_expired);const{message:o}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(o)}},this.isValidPing=async r=>{if(!Le(r)){const{message:i}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)},this.isValidDisconnect=async r=>{if(!Le(r)){const{message:i}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)},this.isValidPairingTopic=async r=>{if(!oe(r,!1)){const{message:s}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(cn(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}},this.core=e,this.logger=Fe(n,this.name),this.pairings=new Cn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Be(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(se.message,async e=>{const{topic:n,message:r,transportType:s}=e;if(this.pairings.keys.includes(n)&&s!==ee.link_mode){try{if(this.core.crypto.getPayloadType(r,pt)===On){this.logger.warn(`registerRelayerEvents() -> non-link mode TYPE_2 payload ignored: ${r}`);return}}catch{}if(!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const i=await this.core.crypto.decode(n,r);ua(i)?(this.core.history.set(n,i),await this.onRelayEventRequest({topic:n,payload:i})):Ks(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:n,payload:i}),this.core.history.delete(n,i.id)),await this.core.relayer.messages.ack(n,r)}catch(i){this.logger.error(i)}}})}registerExpirerEvents(){this.core.expirer.on(Xe.expired,async e=>{const{topic:n}=Sh(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Rn.expire,{topic:n}))})}}class MI extends ig{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.records=new Map,this.events=new Je.EventEmitter,this.name=mI,this.version=bI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,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)},this.set=(r,s,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:i}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:i,expiry:fe(F.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(it.created,o)},this.resolve=async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response<"u"||(s.response=Ye(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(it.updated,s))},this.get=async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s)),this.delete=(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(i=>{if(i.topic===r){if(typeof s<"u"&&i.id!==s)return;this.records.delete(i.id),this.events.emit(it.deleted,i)}}),this.persist()},this.exists=async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1),this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.logger=Fe(n,this.name)}get context(){return Be(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:Lt(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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(it.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=M("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(it.created,e=>{const n=it.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(it.updated,e=>{const n=it.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(it.deleted,e=>{const n=it.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(pn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{F.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(it.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class qI extends hg{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.expirations=new Map,this.events=new Je.EventEmitter,this.name=vI,this.version=EI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,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)},this.has=r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(r,s)=>{this.isInitialized();const i=this.formatTarget(r),o={target:i,expiry:s};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Xe.created,{target:i,expiration:o})},this.get=r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)},this.del=r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),i=this.getExpiration(s);this.expirations.delete(s),this.events.emit(Xe.deleted,{target:s,expiration:i})}},this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.logger=Fe(n,this.name)}get context(){return Be(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 NE(e);if(typeof e=="number")return UE(e);const{message:n}=M("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(Xe.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=M("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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;F.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Xe.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(pn.pulse,()=>this.checkExpirations()),this.events.on(Xe.created,e=>{const n=Xe.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Xe.expired,e=>{const n=Xe.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Xe.deleted,e=>{const n=Xe.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class zI extends fg{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,this.name=xI,this.verifyUrlV3=II,this.storagePrefix=yt,this.version=Df,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&F.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async s=>{if(!Gn()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=xt.getDocument(),u=this.startAbortTimer(F.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",y),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",d,{signal:this.abortController.signal});const y=v=>{if(v.data&&typeof v.data=="string")try{const A=JSON.parse(v.data);if(A.type==="verify_attestation"){if(Li(A.attestation).payload.id!==o)return;clearInterval(u),l.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)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""},this.resolve=async s=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=s;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(Li(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)},this.fetchAttestation=async(s,i)=>{this.logger.debug(`resolving attestation: ${s} from url: ${i}`);const o=this.startAbortTimer(F.ONE_SECOND*5),a=await fetch(`${i}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0},this.getVerifyUrl=s=>{let i=s||Fr;return SI.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Fr}`),i=Fr),i},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(F.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await i.json()}catch(s){this.logger.warn(s)}},this.persistPublicKey=async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async s=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(s,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s},this.validateAttestation=(s,i)=>{const o=P2(s,i.publicKey),a={hasExpired:F.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=Fe(n,this.name),this.abortController=new AbortController,this.isDevEnv=Yo(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Be(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),F.toMiliseconds(e))}}class jI extends dg{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,this.context=DI,this.registerDeviceToken=async r=>{const{clientId:s,token:i,notificationType:o,enableEncrypted:a=!1}=r,c=`${AI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:i,always_raw:a})})},this.logger=Fe(n,this.context)}}class VI extends pg{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,this.context=OI,this.storagePrefix=yt,this.storageVersion=TI,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!Yo())try{const s={eventId:Ah(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_h(this.core.relayer.protocol,this.core.relayer.version,da)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}},this.createEvent=s=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=Ah(),u=this.core.projectId||"",h=Date.now(),f={eventId:l,timestamp:h,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain(),...this.setMethods(l)};return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f},this.getEvent=s=>{const{eventId:i,topic:o}=s;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=s=>{const{eventId:i}=s;this.events.delete(i),this.shouldPersist=!0},this.setEventListeners=()=>{this.core.heartbeat.on(pn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{F.fromMiliseconds(Date.now())-F.fromMiliseconds(s.timestamp)>$I&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})},this.setMethods=s=>({addTrace:i=>this.addTrace(s,i),setError:i=>this.setError(s,i)}),this.addTrace=(s,i)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(i),this.events.set(s,o),this.shouldPersist=!0)},this.setError=(s,i)=>{const o=this.events.get(s);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(i=>{this.events.set(i.eventId,{...i,...this.setMethods(i.eventId)})})}catch(s){this.logger.warn(s)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[i,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const i of s)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}},this.sendEvent=async s=>{const i=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${RI}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${da}${i}`,{method:"POST",body:JSON.stringify(s)})},this.getAppDomain=()=>xh().url,this.logger=Fe(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}}const KI=class Yf extends sg{constructor(e){super(e),this.protocol=Sf,this.version=Df,this.name=fa,this.events=new Je.EventEmitter,this.initialized=!1,this.on=(o,a)=>this.events.on(o,a),this.once=(o,a)=>this.events.once(o,a),this.off=(o,a)=>this.events.off(o,a),this.removeListener=(o,a)=>this.events.removeListener(o,a),this.dispatchEnvelope=({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:ee.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})};const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(o){console.warn("Failed to copy global core",o)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Of,this.customStoragePrefix=e?.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Qp({level:typeof e?.logger=="string"&&e.logger?e.logger:J_.logger,name:fa}),{logger:s,chunkLoggerController:i}=Qa({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=i,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Fe(s,this.name),this.heartbeat=new ci,this.crypto=new PI(this,this.logger,e?.keychain),this.history=new MI(this,this.logger),this.expirer=new qI(this,this.logger),this.storage=e?.storage?e.storage:new dp({...Q_,...e?.storageOptions}),this.relayer=new LI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new FI(this,this.logger),this.verify=new zI(this,this.logger,this.storage),this.echoClient=new jI(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new VI(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new Yf(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(dI,r),n}get context(){return Be(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem($f,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($f)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),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){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},Bf="wc",Pf=2,Cf="client",pa=`${Bf}@${Pf}:${Cf}:`,ga={name:Cf,logger:"error"},Nf="WALLETCONNECT_DEEPLINK_CHOICE",HI="proposal",Uf="Proposal expired",WI="session",Jn=F.SEVEN_DAYS,GI="engine",xe={wc_sessionPropose:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1104},res:{ttl:F.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1106},res:{ttl:F.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:F.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:F.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1112},res:{ttl:F.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1114},res:{ttl:F.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:F.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:F.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1119}}},ya={min:F.FIVE_MINUTES,max:F.SEVEN_DAYS},mt={idle:"IDLE",active:"ACTIVE"},YI={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:""},canton_prepareSignExecute:{key:""},stellar_signXDR:{key:""},stellar_signAndSubmitXDR:{key:"tx_hash"}},ZI="request",XI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],JI="wc",QI="auth",eS="authKeys",tS="pairingTopics",nS="requests",Ws=`${JI}@${1.5}:${QI}:`,un=`${Ws}:PUB_KEY`;class rS extends yg{constructor(e){super(e),this.name=GI,this.events=new Ys,this.initialized=!1,this.requestQueue={state:mt.idle,queue:[]},this.sessionRequestQueue={state:mt.idle,queue:[]},this.emittedSessionRequests=new KE({limit:500}),this.requestQueueDelay=F.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(xe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay)))},this.connect=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r={...n,requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}};await this.isValidConnect(r),r.optionalNamespaces=V2(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l,authentication:u,walletPay:h}=r,f=u?.[0]?.ttl||xe.wc_sessionPropose.req.ttl||F.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,d,g=!1;try{if(p){const $=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),$}if(!p||!g){const{topic:$,uri:P}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=$,d=P}if(!p){const{message:$}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error($)}const y=await this.client.core.crypto.generateKeyPair(),v=fe(f),A={requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:Tf}],proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:v,pairingTopic:p,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:je(),...(u||h)&&{requests:{authentication:u?.map($=>{const{domain:P,chains:k,nonce:U,uri:N,exp:S,nbf:R,type:b,statement:E,requestId:D,resources:B,signatureTypes:I}=$;return{domain:P,chains:k,nonce:U,type:b??"caip122",aud:N,version:"1",iat:new Date().toISOString(),exp:S,nbf:R,statement:E,requestId:D,resources:B,signatureTypes:I}}),walletPay:h}}},w=J("session_connect",A.id),{reject:m,resolve:x,done:_}=Sn(f,Uf),T=({id:$})=>{if($===A.id){this.client.events.off("proposal_expire",T);const P=this.pendingSessions.get(A.id);if(P){const{sessionTopic:k,publicKey:U}=P;Promise.all([this.client.core.relayer.unsubscribe(k),this.client.core.crypto.keychain.has(k)?this.client.core.crypto.deleteSymKey(k):Promise.resolve(),this.client.core.crypto.keychain.has(U)?this.client.core.crypto.deleteKeyPair(U):Promise.resolve()]).catch(N=>this.client.logger.warn(N))}this.pendingSessions.delete(A.id),this.events.emit(w,{error:{message:Uf,code:0}})}};return this.client.events.on("proposal_expire",T),this.events.once(w,({error:$,session:P})=>{this.client.events.off("proposal_expire",T),$?m($):P&&x(P)}),await this.setProposal(A.id,A),await this.sendProposeSession({proposal:A,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:A.id}}}).catch($=>{throw this.deleteProposal(A.id),$}),{uri:d,approval:_}},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}},this.approve=async n=>{const r=this.client.core.eventClient.createEvent({properties:{topic:n?.id?.toString(),trace:[ot.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(T){throw r.setError(Bn.no_internet_connection),T}try{await this.isValidProposalId(n?.id)}catch(T){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),r.setError(Bn.proposal_not_found),T}try{await this.isValidApprove(n)}catch(T){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Bn.session_approve_namespace_validation_failure),T}const{id:s,relayProtocol:i,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l,proposalRequestsResponses:u}=n,h=this.client.proposal.get(s);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:f,proposer:p,requiredNamespaces:d,optionalNamespaces:g}=h;let y=this.client.core.eventClient?.getEvent({topic:f});y||(y=this.client.core.eventClient?.createEvent({type:ot.session_approve_started,properties:{topic:f,trace:[ot.session_approve_started,ot.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),A=p.publicKey,w=await this.client.core.crypto.generateSharedKey(v,A),m={relay:{protocol:i??"irn"},namespaces:o,controller:{publicKey:v,metadata:this.client.metadata},expiry:fe(Jn),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...l&&{sessionConfig:l},proposalRequestsResponses:u},x=ee.relay;y.addTrace(ot.subscribing_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:x,internal:{skipSubscribe:!0}})}catch(T){throw y.setError(Bn.subscribe_session_topic_failure),T}y.addTrace(ot.subscribe_session_topic_success);const _={...m,topic:w,requiredNamespaces:d,optionalNamespaces:g,pairingTopic:f,acknowledged:!1,self:m.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:v,transportType:ee.relay,authentication:u?.authentication,walletPayResult:u?.walletPay};await this.client.session.set(w,_),y.addTrace(ot.store_session);try{await this.sendApproveSession({sessionTopic:w,proposal:h,pairingProposalResponse:{relay:{protocol:i??"irn"},responderPublicKey:v},sessionSettleRequest:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:s,...this.getTVFApproveParams(_)}}}),y.addTrace(ot.session_approve_publish_success)}catch(T){throw this.client.logger.error(T),this.client.session.delete(w,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(w),T}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:p.metadata}),await this.deleteProposal(s),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(w,fe(Jn)),{topic:w,acknowledged:()=>Promise.resolve(this.client.session.get(w))}},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:s}=n;let i;try{i=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}i&&await this.sendError({id:r,topic:i,error:s,rpcOpts:xe.wc_sessionPropose.reject}),await this.deleteProposal(r)},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:s}=n,i=this.client.session.get(r);if(i.self.publicKey!==i.controller){const{message:f}=te("UNAUTHORIZED_UPDATE_REQUEST");throw new Error(f)}const{done:o,resolve:a,reject:c}=Sn(F.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),l=je(),u=ln().toString(),h=this.client.session.get(r).namespaces;return this.events.once(J("session_update",l),({error:f})=>{f?c(f):a()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:h}),c(f)}),{acknowledged:o}},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,s=je(),{done:i,resolve:o,reject:a}=Sn(F.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(J("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,fe(Jn)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}},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:s,topic:i,expiry:o=xe.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(i);a?.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const c=je(),l=ln().toString(),{done:u,resolve:h,reject:f}=Sn(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:y,result:v})=>{y?f(y):h(v)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:{...s,expiryTimestamp:fe(o)},chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(y=>f(y)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),await u();const g={request:{...s,expiryTimestamp:fe(o)},chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(v=>f(v)),this.client.events.emit("session_request_sent",{topic:i,request:s,chainId:r,id:c}),y()}),new Promise(async y=>{if(!a.sessionConfig?.disableDeepLink){const v=await ME(this.client.core.storage,Nf);await kE({id:c,topic:i,wcDeepLink:v})}y()}),u()]).then(y=>y[2])},this.respond=async n=>{this.isInitialized();const r=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||n?.response?.id?.toString(),trace:[ot.session_request_response_started]}});try{await this.isValidRespond(n)}catch(l){throw r.addTrace(l?.message),r.setError(Bn.session_request_response_validation_failure),l}r.addTrace(ot.session_request_response_validation_success);const{topic:s,response:i}=n,{id:o}=i,a=this.client.session.get(s);a.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{r.addTrace(ot.session_request_response_publish_started),gt(i)?await this.sendResult({id:o,topic:s,result:i.result,throwOnFailedPublish:!0,appLink:c}):Ye(i)&&await this.sendError({id:o,topic:s,error:i.error,appLink:c}),this.cleanupAfterResponse(n)}catch(l){throw r.addTrace(l?.message),r.setError(Bn.session_request_response_publish_failure),l}},this.ping=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=n;if(this.client.session.keys.includes(r)){const s=je(),i=ln().toString(),{done:o,resolve:a,reject:c}=Sn(F.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(J("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),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}))},this.emit=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:s,chainId:i}=n,o=ln().toString(),a=je();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})},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:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}},this.find=n=>(this.isInitialized(),this.client.session.getAll().filter(r=>K2(r,n))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(n,r)=>{this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&this.client.metadata.redirect?.linkMode,i=s?ee.link_mode:ee.relay;i===ee.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:a="",uri:c,domain:l,nonce:u,type:h,exp:f,nbf:p,methods:d=[],expiry:g}=n,y=[...n.resources||[]],{topic:v,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:v,uri:A}}),this.client.auth.authKeys.keys.includes(un)){const{responseTopic:I,publicKey:O}=this.client.auth.authKeys.get(un);I&&(await this.client.core.relayer.unsubscribe(I).catch(C=>this.client.logger.warn(C)),await this.client.auth.pairingTopics.delete(I,{message:"replaced",code:0}).catch(C=>this.client.logger.warn(C))),O&&this.client.core.crypto.keychain.has(O)&&await this.client.core.crypto.deleteKeyPair(O)}const w=await this.client.core.crypto.generateKeyPair(),m=Fs(w);if(await Promise.all([this.client.auth.authKeys.set(un,{responseTopic:m,publicKey:w}),this.client.auth.pairingTopics.set(m,{topic:m,pairingTopic:v})]),await this.client.core.relayer.subscribe(m,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${v}`),d.length>0){const{namespace:I}=Ct(o[0]);let O=b2(I,"request",d);Ls(y)&&(O=E2(O,y.pop())),y.push(O)}const x=g&&g>xe.wc_sessionAuthenticate.req.ttl?g:xe.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:h??"caip122",chains:o,statement:a,aud:c,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:f,nbf:p,resources:y},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:fe(x)},T={eip155:{chains:o,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:T,relays:[{protocol:"irn"}],pairingTopic:v,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:fe(xe.wc_sessionPropose.req.ttl),id:je()},{done:P,resolve:k,reject:U}=Sn(x,"Request expired"),N=je(),S=J("session_connect",$.id),R=J("session_request",N),b=async({error:I,session:O})=>{this.events.off(R,D),I?U(I):O&&k({session:O})},E=async I=>{if(await this.deletePendingAuthRequest(N,{message:"fulfilled",code:0}),I.error){const K=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return I.error.code===K.code?void 0:(this.events.off(S,b),U(I.error.message))}await this.deleteProposal($.id),this.events.off(S,b);const{cacaos:O,responder:C}=I.result,L=[],V=[];for(const K of O){if(!await Nh({cacao:K,projectId:this.client.core.projectId}))return this.client.logger.error(K,"Signature verification failed"),U(te("SESSION_SETTLEMENT_FAILED","Signature verification failed"));const W=p2({cacao:K,request:_.authPayload});if(!W.valid)return this.client.logger.error(K,`Cacao does not match the request: ${W.reason}`),U(te("SESSION_SETTLEMENT_FAILED",`Cacao does not match the request: ${W.reason}`));const{p:G}=K,H=Ls(G.resources),Z=[Us(G.iss)],ae=ks(G.iss);if(H){const ce=Lh(H),we=Fh(H);L.push(...ce),Z.push(...we)}for(const ce of Z)V.push(`${ce}:${ae}`)}const z=await this.client.core.crypto.generateSharedKey(w,C.publicKey);let q;L.length>0&&(q={topic:z,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:C,controller:C.publicKey,expiry:fe(Jn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:v,namespaces:ef([...new Set(L)],[...new Set(V)]),transportType:i},await this.client.core.relayer.subscribe(z,{transportType:i}),await this.client.session.set(z,q),v&&await this.client.core.pairing.updateMetadata({topic:v,metadata:C.metadata}),q=this.client.session.get(z)),this.client.metadata.redirect?.linkMode&&C.metadata.redirect?.linkMode&&C.metadata.redirect?.universal&&r&&(this.client.core.addLinkModeSupportedApp(C.metadata.redirect.universal),this.client.session.update(z,{transportType:ee.link_mode})),k({auths:O,session:q})},D=I=>E(I).catch(O=>{this.client.logger.error(O,"Failed to process authenticate response"),U(te("SESSION_SETTLEMENT_FAILED",O?.message||"Failed to process authenticate response"))});this.events.once(S,b),this.events.once(R,D);let B;try{if(s){const I=Lt("wc_sessionAuthenticate",_,N);this.client.core.history.set(v,I);const O=await this.client.core.crypto.encode("",I,{type:On,encoding:pt});B=zs(r,v,O)}else await Promise.all([this.sendRequest({topic:v,method:"wc_sessionAuthenticate",params:_,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:N}),this.sendRequest({topic:v,method:"wc_sessionPropose",params:$,expiry:xe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(I){throw this.events.off(S,b),this.events.off(R,D),I}return await this.setProposal($.id,$),await this.setAuthRequest(N,{request:{..._,verifyContext:{}},pairingTopic:v,transportType:i}),{uri:B??A,response:P}},this.approveSessionAuthenticate=async n=>{const{id:r,auths:s}=n,i=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Pn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Mr.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw i.setError(Mr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ee.relay;a===ee.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Fs(c),h={type:Nt,receiverPublicKey:c,senderPublicKey:l},f=[],p=[];for(const y of s){if(!await Nh({cacao:y,projectId:this.client.core.projectId})){i.setError(Mr.invalid_cacao);const x=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:x,encodeOpts:h}),new Error(x.message)}i.addTrace(Pn.cacaos_verified);const{p:v}=y,A=Ls(v.resources),w=[Us(v.iss)],m=ks(v.iss);if(A){const x=Lh(A),_=Fh(A);f.push(...x),w.push(..._)}for(const x of w)p.push(`${x}:${m}`)}const d=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(Pn.create_authenticated_session_topic);let g;if(f?.length>0){g={topic:d,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:fe(Jn),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ef([...new Set(f)],[...new Set(p)]),transportType:a},i.addTrace(Pn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw i.setError(Mr.subscribe_authenticated_session_topic_failure),y}i.addTrace(Pn.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),i.addTrace(Pn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(Pn.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw i.setError(Mr.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:i.eventId}),{session:g}},this.rejectSessionAuthenticate=async n=>{this.isInitialized();const{id:r,reason:s}=n,i=this.getPendingAuthRequest(r);if(!i)throw new Error(`Could not find pending auth request with id ${r}`);i.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Fs(o),l={type:Nt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:l,rpcOpts:xe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)},this.formatAuthMessage=n=>{this.isInitialized();const{request:r,iss:s}=n;return Uh(r,s)},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)},this.cleanupDuplicatePairings=async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>i.peerMetadata?.url&&i.peerMetadata?.url===n.peer.metadata.url&&i.topic&&i.topic!==r.topic);if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}},this.deleteSession=async n=>{const{topic:r,expirerHasDeleted:s=!1,emitEvent:i=!0,id:o=0}=n,{self:a}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),s||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Nf).catch(c=>this.client.logger.warn(c)),r===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=mt.idle),await Promise.all(this.getPendingSessionRequests().filter(c=>c.topic===r).map(c=>this.deletePendingSessionRequest(c.id,te("USER_DISCONNECTED")))),i&&this.client.events.emit("session_delete",{id:o,topic:r})},this.deleteProposal=async(n,r)=>{if(r)try{const s=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(Bn.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,te("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")},this.deletePendingSessionRequest=async(n,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==n),s&&(this.sessionRequestQueue.state=mt.idle,this.client.events.emit("session_request_expire",{id:n}))},this.deletePendingAuthRequest=async(n,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)])},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}))},this.setProposal=async(n,r)=>{this.client.core.expirer.set(n,fe(xe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)},this.setAuthRequest=async(n,r)=>{const{request:s,pairingTopic:i,transportType:o=ee.relay}=r;this.client.core.expirer.set(n,s.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:n,pairingTopic:i,verifyContext:s.verifyContext,transportType:o})},this.setPendingSessionRequest=async n=>{const{id:r,topic:s,params:i,verifyContext:o}=n,a=i.request.expiryTimestamp||fe(xe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:i,verifyContext:o})},this.sendRequest=async n=>{const{topic:r,method:s,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=n,p=Lt(s,i,c);let d;const g=!!u;try{const A=g?pt:Ee;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(XI.includes(s)){const A=Ge(JSON.stringify(p)),w=Ge(d);y=await this.client.core.verify.register({id:w,decryptedId:A})}const v={...xe[s].req,...f};if(v.attestation=y,o&&(v.ttl=o),a&&(v.id=a),this.client.core.history.set(r,p),g){const A=zs(u,r,d);await global.Linking.openURL(A,this.client.name)}else v.tvf={...h,correlationId:p.id},l?(v.internal={...v.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(r,d,v)):this.client.core.relayer.publish(r,d,v).catch(A=>this.client.logger.error(A));return p.id},this.sendProposeSession=async n=>{const{proposal:r,publishOpts:s}=n,i=Lt("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,i);const o=await this.client.core.crypto.encode(r.pairingTopic,i,{encoding:Ee}),a=Ge(JSON.stringify(i)),c=Ge(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:{...s,publishMethod:"wc_proposeSession",attestation:l}})},this.sendApproveSession=async n=>{const{sessionTopic:r,pairingProposalResponse:s,proposal:i,sessionSettleRequest:o,publishOpts:a}=n,c=Vs(i.id,s),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:Ee}),u=Lt("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(r,u,{encoding:Ee});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async n=>{const{id:r,topic:s,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Vs(r,i);let u;const h=c&&typeof global?.Linking<"u";try{const d=h?pt:Ee;u=await this.client.core.crypto.encode(s,l,{...a||{},encoding:d})}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),d}let f,p;try{f=await this.client.core.history.get(s,r);const d=f.request;try{p=this.getTVFParams(r,d.params,i)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),d}if(h){const d=zs(c,s,u);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=xe[d].res;g.tvf={...p,correlationId:r},o?(g.internal={...g.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)},this.sendError=async n=>{const{id:r,topic:s,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=la(r,i);let u;const h=c&&typeof global?.Linking<"u";try{const p=h?pt:Ee;u=await this.client.core.crypto.encode(s,l,{...o||{},encoding:p})}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),p}if(h){const p=zs(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||xe[p].res;this.client.core.relayer.publish(s,u,d)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const n=[],r=[];this.client.session.getAll().forEach(s=>{let i=!1;cn(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&n.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{cn(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...n.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])},this.onProviderMessageEvent=async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)},this.onRelayEventRequest=async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===mt.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=mt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=mt.idle},this.processRequest=async n=>{const{topic:r,payload:s,attestation:i,transportType:o,encryptedId:a}=n,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async n=>{const{topic:r,payload:s,transportType:i}=n,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=n=>{const{topic:r}=n,{message:s}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)},this.shouldIgnorePairingRequest=n=>{const{topic:r,requestMethod:s}=n,i=this.expectedPairingMethodMap.get(r);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o}=n,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Ft.proposal_listener_not_found)),this.isValidConnect({...s.params});const u=a.expiryTimestamp||fe(xe.wc_sessionPropose.req.ttl),h={id:c,pairingTopic:r,expiryTimestamp:u,attestation:i,encryptedId:o,...a};await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:xe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(n,r,s)=>{const{id:i}=r;if(gt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);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 l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:u,pairingTopic:n,proposalId:i,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:n})}else if(Ye(r)){await this.deleteProposal(i);const o=J("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}},this.onSessionSettleRequest=async(n,r)=>{const{id:s,params:i}=r;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=r.params,d=[...this.pendingSessions.values()].find(v=>v.sessionTopic===n);if(!d)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(d.proposalId),y={topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...u&&{sessionProperties:u},...h&&{scopedProperties:h},...f&&{sessionConfig:f},transportType:ee.relay,authentication:p?.authentication,walletPayResult:p?.walletPay};await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(J("session_connect",d.proposalId),{session:y})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(n,r)=>{const{id:s}=r;gt(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(J("session_approve",s),{})):Ye(r)&&(await this.deleteSession({topic:n,emitEvent:!1}),this.events.emit(J("session_approve",s),{error:r.error}))},this.onSessionUpdateRequest=async(n,r)=>{const{params:s,id:i}=r;try{const o=`${n}_session_update`,a=Pr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:n,error:te("INVALID_UPDATE_REQUEST")});return}await this.isValidUpdate({topic:n,...s});const c=this.client.session.get(n);if(c.peer.publicKey!==c.controller)throw te("UNAUTHORIZED_UPDATE_REQUEST");try{Pr.set(o,i),await this.client.session.update(n,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:n,result:!0})}catch(l){throw Pr.delete(o),l}this.client.events.emit("session_update",{id:i,topic:n,params:s})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3),this.onSessionUpdateResponse=(n,r)=>{const{id:s}=r,i=J("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_update",s),{}):Ye(r)&&this.events.emit(J("session_update",s),{error:r.error})},this.onSessionExtendRequest=async(n,r)=>{const{id:s}=r;try{await this.isValidExtend({topic:n}),await this.setExpiry(n,fe(Jn)),await this.sendResult({id:s,topic:n,result:!0}),this.client.events.emit("session_extend",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}},this.onSessionExtendResponse=(n,r)=>{const{id:s}=r,i=J("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_extend",s),{}):Ye(r)&&this.events.emit(J("session_extend",s),{error:r.error})},this.onSessionPingRequest=async(n,r)=>{const{id:s}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:s,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}},this.onSessionPingResponse=(n,r)=>{const{id:s}=r,i=J("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);gt(r)?this.events.emit(J("session_ping",s),{}):Ye(r)&&this.events.emit(J("session_ping",s),{error:r.error})},500)},this.onSessionDeleteRequest=async(n,r)=>{const{id:s}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:te("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:s})}catch(i){this.client.logger.error(i)}},this.onSessionRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o,transportType:a}=n,{id:c,params:l}=s;try{await this.isValidRequest({topic:r,...l});const u=this.client.session.get(r),h=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(Lt("wc_sessionRequest",l,c))),encryptedId:o,metadata:u.peer.metadata,transportType:a}),f={id:c,topic:r,params:l,verifyContext:h};await this.setPendingSessionRequest(f),a===ee.link_mode&&u.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(u.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(u){await this.sendError({id:c,topic:r,error:u}),this.client.logger.error(u)}},this.onSessionRequestResponse=(n,r)=>{const{id:s}=r,i=J("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_request",s),{result:r.result}):Ye(r)&&this.events.emit(J("session_request",s),{error:r.error})},this.onSessionEventRequest=async(n,r)=>{const{id:s,params:i}=r;try{const o=`${n}_session_event_${i.event.name}`,a=Pr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit({topic:n,...i}),this.client.events.emit("session_event",{id:s,topic:n,params:i}),Pr.set(o,s)}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(n,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),gt(r)?this.events.emit(J("session_request",s),{result:r.result}):Ye(r)&&this.events.emit(J("session_request",s),{error:r.error})},this.onSessionAuthenticateRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o,transportType:a}=n;try{const{requester:c,authPayload:l,expiryTimestamp:u}=s.params,h=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(s)),encryptedId:o,metadata:c.metadata,transportType:a}),f={requester:c,pairingTopic:r,id:s.id,authPayload:l,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(s.id,{request:f,pairingTopic:r,transportType:a}),a===ee.link_mode&&c.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:s.params,id:s.id,verifyContext:h})}catch(c){this.client.logger.error(c);const l=s.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,a),f={type:Nt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:s.id,topic:r,error:c,encodeOpts:f,rpcOpts:xe.wc_sessionAuthenticate.autoReject,appLink:h})}},this.addSessionRequestToSessionRequestQueue=n=>{this.sessionRequestQueue.queue.push(n)},this.cleanupAfterResponse=n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=mt.idle,this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:n,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===n&&i.request.method==="wc_sessionRequest").forEach(i=>{this.events.emit(J("session_request",i.request.id),{error:r})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===mt.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)}},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=mt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const n=this.client.core.relayer.subscriber.topics;if(n.length===0)return;const r=new Set(this.client.session.keys),s=new Set(this.client.core.pairing.pairings.keys),i=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic));let o;if(this.client.auth.authKeys.keys.includes(un)){const{responseTopic:a}=this.client.auth.authKeys.get(un);o=a}for(const a of n)if(!r.has(a)&&!s.has(a)&&!i.has(a)&&a!==o){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:Lt("wc_sessionPropose",{...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})},this.isValidConnect=async n=>{if(!Le(n)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=n;if(de(r)||await this.isValidPairingTopic(r),!rx(c)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!de(s)&&Rr(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(i&&!de(i)&&Rr(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!de(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!de(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}},this.validateNamespaces=(n,r)=>{const s=nx(n,"connect()",r);if(s)throw new Error(s.message)},this.isValidApprove=async n=>{if(!Le(n))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:s,relayProtocol:i,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=na(s,"approve()");if(l)throw new Error(l.message);const u=of(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!oe(i,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(h)}if(o&&!de(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!de(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));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(", ")}`)}},this.isValidReject=async n=>{if(!Le(n)){const{message:i}=M("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(i)}const{id:r,reason:s}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!ix(s)){const{message:i}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}},this.isValidSessionSettleRequest=n=>{if(!Le(n)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:s,namespaces:i,expiry:o}=n;if(!rf(r)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Z2(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=na(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(cn(o)){const{message:l}=M("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async n=>{if(!Le(n)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:s}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const i=this.client.session.get(r),o=na(s,"update()");if(o)throw new Error(o.message);const a=of(i.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(s)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)},this.isValidRequest=async n=>{if(!Le(n)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:s,chainId:i,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!sf(a,i)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!ox(s)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!lx(a,i,s.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)},this.isValidRespond=async n=>{if(!Le(n)){const{message:o}=M("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:r,response:s}=n;try{await this.isValidSessionTopic(r)}catch(o){throw n?.response?.id&&this.cleanupAfterResponse(n),o}if(!ax(s)){const{message:o}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}const i=this.client.pendingRequest.get(s.id);if(i.topic!==r){const{message:o}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${i.topic}, received topic: ${r}`);throw new Error(o)}},this.isValidPing=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidEmit=async n=>{if(!Le(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:s,chainId:i}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!sf(o,i)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!cx(s)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!ux(o,i,s.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidDisconnect=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidAuthenticate=n=>{const{chains:r,uri:s,domain:i,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!oe(s,!1))throw new Error("uri is required parameter");if(!oe(i,!1))throw new Error("domain is required parameter");if(!oe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ct(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ct(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async n=>{const{attestationId:r,hash:s,encryptedId:i,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Fr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ee.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(n,r)=>{Object.values(n).forEach((s,i)=>{if(s==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(n)[i]}`);throw new Error(o)}})},this.getPendingAuthRequest=n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0},this.addToRecentlyDeleted=(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(s)}},this.isLinkModeEnabled=(n,r)=>!n||r!==ee.link_mode?!1:this.client.metadata?.redirect?.linkMode===!0&&this.client.metadata?.redirect?.universal!==void 0&&this.client.metadata?.redirect?.universal!==""&&n?.redirect?.universal!==void 0&&n?.redirect?.universal!==""&&n?.redirect?.linkMode===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof global?.Linking<"u",this.getAppLinkIfEnabled=(n,r)=>this.isLinkModeEnabled(n,r)?n?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=Dh(n,"topic")||"",s=decodeURIComponent(Dh(n,"wc_ev")||""),i=this.client.session.keys.includes(r);i&&this.client.session.update(r,{transportType:ee.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:i})},this.registerLinkModeListeners=async()=>{if(Yo()||an()&&this.client.metadata.redirect?.linkMode){const n=global?.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}},this.getTVFApproveParams=n=>{try{const r=Xh(n.namespaces),s=L2(n.namespaces),i=F2(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:s,approvedEvents:i,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}},this.getTVFParams=(n,r,s)=>{if(!r.request?.method)return{};const i={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const o=this.extractTxHashesFromResult(r.request,s);i.txHashes=o,i.contractAddresses=this.isValidContractData(r.request.params)?[r.request.params?.[0]?.to]:[]}catch(o){this.client.logger.warn(o,"Error getting TVF params")}return i},this.isValidContractData=n=>{if(!n)return!1;try{const r=n?.data||n?.[0]?.data;if(!r.startsWith("0x"))return!1;const s=r.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(n,r)=>{try{if(!r)return[];const s=n.method,i=YI[s];if(s==="sui_signTransaction")return[e2(r.transactionBytes)];if(s==="near_signTransaction")return[$h(r)];if(s==="near_signTransactions")return r.map(a=>$h(a));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[r.tx_json?.hash];if(s==="polkadot_signTransaction")return[Tx({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Xn(r)?r.map(a=>Rh(a)):[Rh(r)];if(s==="cosmos_signDirect")return[n2(r)];if(s==="stellar_signXDR")return[c2(r.signedXDR,n.params?.chain)];if(s==="wallet_sendCalls")return l2(r);if(s==="canton_prepareSignExecute")return Rx(n.params,r);if(typeof r=="string")return[r];const o=r[i.key];if(Xn(o))return s==="solana_signAllTransactions"?o.map(a=>QE(a)):o;if(typeof o=="string")return[o]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,s]of Object.entries(n))for(const i of s)try{await this.onProviderMessageEvent({topic:r,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(se.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:s,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(un)?this.client.auth.authKeys.get(un):{publicKey:void 0};try{try{if(i!==ee.link_mode&&this.client.core.crypto.getPayloadType(r,pt)===On){this.client.logger.warn(`onRelayMessage() -> non-link mode TYPE_2 payload ignored: ${r}`);return}}catch{}const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:i===ee.link_mode?pt:Ee});ua(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:s,transportType:i,encryptedId:Ge(r)})):Ks(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:i}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:i})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a?.message)}}registerExpirerEvents(){this.client.core.expirer.on(Xe.expired,async e=>{const{topic:n,id:r}=Sh(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);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}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Rn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Rn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!oe(e,!1)){const{message:n}=M("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}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!oe(e,!1)){const{message:n}=M("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}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=M("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=M("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(oe(e,!1)){const{message:n}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!sx(e)){const{message:n}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=M("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!dx(e,ya)){const{message:n}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${ya.min} and ${ya.max}`);throw new Error(n)}}}class sS extends Cn{constructor(e,n){super(e,n,HI,pa),this.core=e,this.logger=n}}class iS extends Cn{constructor(e,n){super(e,n,WI,pa),this.core=e,this.logger=n}}class oS extends Cn{constructor(e,n){super(e,n,ZI,pa,r=>r.id),this.core=e,this.logger=n}}class aS extends Cn{constructor(e,n){super(e,n,eS,Ws,()=>un),this.core=e,this.logger=n}}class cS extends Cn{constructor(e,n){super(e,n,tS,Ws),this.core=e,this.logger=n}}class lS extends Cn{constructor(e,n){super(e,n,nS,Ws,r=>r.id),this.core=e,this.logger=n}}class uS{constructor(e,n){this.core=e,this.logger=n,this.authKeys=new aS(this.core,this.logger),this.pairingTopics=new cS(this.core,this.logger),this.requests=new lS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}const hS=class Zf extends gg{constructor(e){super(e),this.protocol=Bf,this.version=Pf,this.name=ga.name,this.events=new Je.EventEmitter,this.on=(r,s)=>this.events.on(r,s),this.once=(r,s)=>this.events.once(r,s),this.off=(r,s)=>this.events.off(r,s),this.removeListener=(r,s)=>this.events.removeListener(r,s),this.removeAllListeners=r=>this.events.removeAllListeners(r),this.connect=async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}},this.pair=async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}},this.approve=async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}},this.reject=async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}},this.update=async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}},this.extend=async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}},this.request=async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}},this.respond=async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}},this.ping=async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}},this.emit=async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}},this.find=r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}},this.authenticate=async(r,s)=>{try{return console.warn("[WalletConnect] `authenticate` is deprecated and will be removed in a future release. Use `connect()`'s `authentication` instead to establish an authenticated session."),await this.engine.authenticate(r,s)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}},this.approveSessionAuthenticate=async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}},this.rejectSessionAuthenticate=async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}},this.name=e?.name||ga.name,this.metadata=RE(e?.metadata),this.signConfig=e?.signConfig;const n=lf({logger:e?.logger||ga.logger,name:this.name});this.logger=n,this.core=e?.core||new KI(e),this.session=new iS(this.core,this.logger),this.proposal=new sS(this.core,this.logger),this.pendingRequest=new oS(this.core,this.logger),this.engine=new rS(this),this.auth=new uS(this.core,this.logger)}static async init(e){const n=new Zf(e);return await n.initialize(),n}get context(){return Be(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}}};class kf{constructor(e){this.opts=e}}class Lf{constructor(e){this.client=e}}const Ff=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:s,standard:i,address:o}=n;if(!r||!s||!i||!o||!Br(r?.chainId))return!1;const{namespace:a}=Ct(r.chainId),c=e.find(l=>l.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(l=>l.toLowerCase()).includes(i?.toLowerCase()))throw new Error(`Unsupported token standard: ${i} for namespace: ${a}`);return!0},fS=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:s,recipient:i}=n;return!(!r||!s||!i||!Ff({supportedNamespaces:e,token:r}))},Mf=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};class dS extends Lf{constructor(e){super(e),this.tokens=[],this.supportedNamespaces=_a,this.paymentIntents={},this.transactions={},this.paymentsSendingInProgress={},this.manualControl={},this.init=async()=>{this.signClient=await hS.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:this.client.opts.storageOptions?.databaseName||Xs.database},customStoragePrefix:Xs.customStoragePrefix,logger:this.client.opts.loggerOptions?.signLevel||Js}),this.signClient.events.on("session_delete",({topic:n})=>{this.cleanup({sessionTopic:n}),this.emit("disconnected",{sessionTopic:n})});try{this.logger.debug("Fetching supported namespaces/networks");const n=await this.fetchRpcRequest({payload:JSON.stringify({id:je(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:n.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=n.result.namespaces}catch(n){this.logger.error(n,"Failed to fetch supported namespaces/networks")}},this.setTokens=async n=>{const{tokens:r}=n;this.logger.debug({tokens:r},"Setting tokens"),r.forEach(s=>{if(!Ff({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=r,s()}),this.logger.debug({tokens:r},"Tokens set")},this.createPaymentIntent=async n=>{const{paymentIntents:r,sessionTopic:s,userId:i}=n;this.logger.debug({paymentIntents:r,userId:i},"Creating payment intent");const o=n.manualControl||!1;if(r.length===0)throw new Error("No payment intents provided");for(const h of r)if(!fS({paymentIntent:h,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(h)}`);if(this.logger.debug({paymentIntents:r,userId:i},"Payment intent validation success"),s){this.manualControl[s]=o;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:r,userId:i}),this.validateApprovedNamespacesWithPaymentIntents(s),o||await this.sendPaymentsToWallet({sessionTopic:s,userId:i});return}catch(h){this.logger.error(h),await this.disconnect({sessionTopic:s})}}const a=this.composeNamespacesFromPaymentIntents(r),{uri:c,approval:l}=await this.signClient.connect({optionalNamespaces:a});if(this.logger.debug({uri:c,userId:i},"Connected to the WalletConnect network"),!c)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=Mf(l);if(this.emit("await_approval",{approval:u,paymentIntents:r,userId:i,manualControl:o}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:c,userId:i}),this.logger.debug({uri:c,userId:i},"Emitted qr_ready event"),o){const h=await u();this.manualControl[h.topic]=o}},this.restart=async n=>{this.logger.debug({params:n},"Restarting");const{reinit:r,sessionTopic:s,userId:i}=n||{};if(r){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const o=this.getSessionTopic(s),a=this.manualControl[o],c=this.paymentIntents[o];if(!c||!c?.length)throw new Error("No payment intents found for session topic: "+o);await this.createPaymentIntent({paymentIntents:c,manualControl:a,userId:i,sessionTopic:o}),this.logger.debug({paymentIntents:c,userId:i},"Restarted: Created payment intent flow from the beginning")},this.connect=async n=>{const{userId:r}=n,s=!0,i=this.composeNamespacesFromTokens(),{uri:o,approval:a}=await this.signClient.connect({optionalNamespaces:i});if(this.logger.debug({uri:o},"Connected to the WalletConnect network"),!o)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:r}),new Error("Failed to connect to the WalletConnect network");const c=Mf(a);this.emit("await_approval",{approval:c,manualControl:s,paymentIntents:[],userId:r}),this.logger.debug({userId:r},"Emitted await_approval event"),this.emit("qr_ready",{uri:o,userId:r}),this.logger.debug({uri:o,userId:r},"Emitted qr_ready event");const l=await c();return this.manualControl[l.topic]=s,l},this.emit=(n,r)=>(this.logger.debug({event:n,args:r},"Emit"),this.client.events.emit(n,r)),this.on=(n,r)=>(this.logger.debug({event:n,listener:r},"On"),this.client.events.on(n,r)),this.once=(n,r)=>(this.logger.debug({event:n,listener:r},"Once"),this.client.events.once(n,r)),this.off=(n,r)=>(this.logger.debug({event:n,listener:r},"Off"),this.client.events.off(n,r)),this.removeListener=(n,r)=>(this.logger.debug({event:n,listener:r},"Remove listener"),this.client.events.removeListener(n,r)),this.prepareTransactionsFromPaymentIntents=async n=>{const{sessionTopic:r,userId:s}=n,i=this.getSessionTopic(r),o=this.paymentIntents[i];if(!o)throw new Error("No payment intents found for session topic: "+i);const a=this.signClient.session.get(i);this.logger.debug({sessionTopic:i,userId:s},"Preparing transactions from payment intents");const c=[];for(const h of o){const{token:f,amount:p,recipient:d}=h,{namespace:g}=Ct(f.network.chainId),y=a.namespaces?.[g]?.accounts?.find(v=>v.includes(`${f.network.chainId}:`));if(!y)throw new Error(`Address not found in session for chain id: ${f.network.chainId}, approved addresses: ${a.namespaces?.[g]?.accounts?.join(", ")}`);c.push({asset:`${f.network.chainId}/${f.standard.toLowerCase()}:${f.address}`,recipient:d,amount:p,sender:y})}this.logger.debug({sessionTopic:a.topic,transactions:c,userId:s},"Prepared transactions from payment intents");const l={id:je(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:c}};this.logger.debug({payload:l,userId:s},"Fetching wc_pos_buildTransactions");const u=await this.fetchRpcRequest({payload:JSON.stringify(l),userId:s});this.logger.debug({response:u,userId:s},"Received wc_pos_buildTransactions"),this.transactions[a.topic]=u.result.transactions,this.logger.debug({transactions:this.transactions[a.topic],userId:s},"Payment intent to transactions map set")},this.sendPaymentsToWallet=async(n={})=>{const{sessionTopic:r,userId:s}=n,i=this.getSessionTopic(r);if(!i)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[i])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[i]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:i,userId:s}),await this.sendTransactionsToWallet({sessionTopic:i,userId:s})}catch(o){throw this.logger.error(o,"Error while sending payments to wallet"),this.paymentsSendingInProgress[i]=!1,o}this.paymentsSendingInProgress[i]=!1},this.sendTransactionsToWallet=async n=>{const{sessionTopic:r,userId:s}=n,i=this.transactions[r],o=this.paymentIntents[r];if(!i||!o)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(i.length!==o.length)throw new Error(`Mismatch between transactions (${i.length}) and payment intents (${o.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:i,sessionTopic:r,userId:s},"Sending transactions to wallet");for(let a=0;a<i.length;a++){const c=i[a],l=o[a];try{this.emit("payment_requested",{paymentIntent:l,transaction:c,sessionTopic:r,userId:s}),this.logger.debug({transactionId:c.id,userId:s},"Emitted payment_requested event");let u;try{u=await this.signClient.request({topic:r,request:{method:c.method,params:c.params},chainId:c.chainId}),this.logger.debug({transactionId:c.id,result:u,userId:s},"Wallet responded to payment request")}catch(h){throw this.logger.error(h,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:h?.message,code:4001},paymentIntent:l,sessionTopic:r,userId:s}),h}this.emit("payment_broadcasted",{paymentIntent:l,transaction:c,result:u,sessionTopic:r,userId:s}),this.logger.debug({transactionId:c.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:c,result:u,sessionTopic:r,userId:s}),await new Promise(h=>setTimeout(h,1e3))}catch(u){this.logger.error(u,"Error while awaiting payment confirmed")}}this.manualControl[r]!==!0&&await this.disconnect({sessionTopic:r})},this.awaitPaymentConfirmed=async n=>{const{transaction:r,result:s,sessionTopic:i,userId:o}=n;try{this.logger.debug({transactionId:r.id,result:s},"Awaiting payment confirmed");const a={id:je(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:r.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let c=0,l;for(;!l;){if(c>=xa)throw new Error(`Transaction status not found for id: ${r.id}`);c++;const u=await this.fetchRpcRequest({payload:JSON.stringify(a),userId:o});if(this.logger.debug({transactionId:r.id,response:u},"Received wc_pos_checkTransaction"),u.result.status==="CONFIRMED"){this.logger.debug({response:u,userId:o},"Transaction status confirmed"),this.emit("payment_successful",{transaction:r,result:s,sessionTopic:i,userId:o}),l=u.result;break}else if(u.result.status==="FAILED"){this.logger.debug({response:u},"Transaction failed"),this.emit("payment_failed",{error:{message:u.result.error,code:4001},transaction:s,sessionTopic:i,userId:o}),l=u.result;break}else u.result.status==="PENDING"&&(this.logger.debug({response:u,userId:o},"Transaction pending"),await new Promise(h=>setTimeout(h,u.result.checkIn||1e3)))}}catch(a){this.logger.error(a,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:a?.message,code:4001},transaction:r,sessionTopic:i,userId:o})}},this.setupEventHandlers=()=>{this.on("await_approval",async({approval:n,paymentIntents:r,userId:s,manualControl:i})=>{try{this.logger.debug("On await_approval");const o=await n();this.setPaymentIntents({sessionTopic:o.topic,paymentIntents:r}),await this.onSessionConnected({session:o,userId:s,manualControl:i})}catch(o){this.logger.error(o,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:o?.message,code:4001},userId:s})}})},this.onSessionConnected=async n=>{const{session:r,userId:s,manualControl:i}=n;this.logger.debug({sessionTopic:r.topic,userId:s},"On session connected"),this.emit("connected",{session:r,userId:s}),await this.signClient.session.update(r.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:r.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:r.topic,userId:s},"Emitted connected event"),i!==!0&&await this.sendPaymentsToWallet({sessionTopic:r.topic,userId:s})},this.disconnect=async(n={})=>{try{const{sessionTopic:r}=n,s=this.getSessionTopic(r);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(r){this.logger.error(r,"Error while disconnecting")}},this.fetchRpcRequest=async n=>{const{payload:r,userId:s}=n;this.logger.debug({url:this.getRpcUrl(),payload:r,userId:s},"Fetching RPC request");const i=await fetch(this.getRpcUrl(),{method:"POST",body:r});let o;try{o=await i.json()}catch(a){this.logger.error(a,"Error while getting json data from RPC response")}if(this.logger.debug({data:o},"Received RPC request response"),!i.ok||!o||o?.error){const a=o?.error?.code||-18900,c=Qs?.[a]?`${Qs?.[a]}: ${o?.error?.message}`:o?.error?.message||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:c,code:a},transaction:"",sessionTopic:this.client.session?.topic||"",userId:s}),new Error(c)}return o},this.validateApprovedNamespacesWithPaymentIntents=n=>{this.validateSessionTopic(n);const r=this.signClient.session.get(n),s=this.paymentIntents?.[n];if(!r||!s)throw new Error("No session or payment intents found");for(const i of s){const{token:o}=i,{namespace:a}=Ct(o.network.chainId);if(!r.namespaces?.[a]?.accounts?.find(c=>c.includes(`${o.network.chainId}:`)))throw new Error(`Address not found in session for chain id: ${o.network.chainId}, approved addresses: ${r.namespaces?.[a]?.accounts?.join(", ")}`)}},this.setPaymentIntents=n=>{const{sessionTopic:r,paymentIntents:s,userId:i}=n;this.paymentIntents[r]=s,this.logger.debug({paymentIntents:s,userId:i},"Payment intents set")},this.cleanup=(n={})=>{const{sessionTopic:r}=n;r&&(delete this.paymentIntents[r],delete this.transactions[r],delete this.manualControl[r],delete this.paymentsSendingInProgress[r],this.logger.debug({sessionTopic:r},"Cleaned up payment intents and transactions"))},this.getRpcUrl=()=>Ia({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId}),this.validateSessionTopic=n=>{if(n)try{this.signClient.session.get(n)}catch(r){throw this.logger.error(r,`No session found for topic: ${n}`),new Error(`No session found for topic: ${n}`)}},this.getSessionTopic=n=>{if(!n&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const r=n||this.client.session?.topic;if(!r)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(r),r},this.signClient={},this.logger=Bp({name:this.client.name,level:this.client.opts.loggerOptions?.posLevel||Js}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{const{network:s}=r,{namespace:i}=Ct(s.chainId),o=this.supportedNamespaces.find(a=>a.name===i);if(!o)throw new Error(`Namespace not supported: ${i}`);n[i]={methods:o.methods,chains:[...n[i]?.chains||[],s.chainId],events:o.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{const{token:{network:s}}=r,{namespace:i}=Ct(s.chainId),o=this.supportedNamespaces.find(a=>a.name===i);if(!o)throw new Error(`Namespace not supported: ${i}`);n[i]={methods:o.methods,chains:[...n[i]?.chains||[],s.chainId],events:o.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}}let qf=class Xf extends kf{constructor(e){super(e),this.events=new Ys,this.on=(n,r)=>this.engine.on(n,r),this.once=(n,r)=>this.engine.once(n,r),this.off=(n,r)=>this.engine.off(n,r),this.removeListener=(n,r)=>this.engine.removeListener(n,r),this.setTokens=async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.createPaymentIntent=async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.restart=async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.sendPaymentsToWallet=async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.connect=async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.metadata=e.metadata,this.name=Zs,this.engine=new dS(this)}static async init(e){const n=new Xf(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}};const pS=qf;ie.CLIENT_CONTEXT=Zs,ie.CLIENT_STORAGE_OPTIONS=Xs,ie.CLIENT_STORAGE_PREFIX=td,ie.DEFAULT_LOGGER_LEVEL=Js,ie.DEFAULT_NAMESPACES=_a,ie.IPOSClient=kf,ie.IPOSClientEngine=Lf,ie.MAX_TRANSACTION_STATUS_CHECKS=xa,ie.POSClient=pS,ie.POS_CLIENT_VERSION=Ea,ie.PROTOCOL=va,ie.PROTOCOL_VERSION=ed,ie.RPC_ERROR_CODES=Qs,ie.RPC_URL=Ia,ie.default=qf,Object.defineProperty(ie,"__esModule",{value:!0})});
39
+ ***************************************************************************** */var aa=function(t,e){return aa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var s in r)r.hasOwnProperty(s)&&(n[s]=r[s])},aa(t,e)};function Mx(t,e){aa(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var ca=function(){return ca=Object.assign||function(e){for(var n,r=1,s=arguments.length;r<s;r++){n=arguments[r];for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])}return e},ca.apply(this,arguments)};function qx(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 s=0,r=Object.getOwnPropertySymbols(t);s<r.length;s++)e.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(t,r[s])&&(n[r[s]]=t[r[s]]);return n}function jx(t,e,n,r){var s=arguments.length,i=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")i=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(i=(s<3?o(i):s>3?o(e,n,i):o(e,n))||i);return s>3&&i&&Object.defineProperty(e,n,i),i}function zx(t,e){return function(n,r){e(n,r,t)}}function Vx(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function Kx(t,e,n,r){function s(i){return i instanceof n?i:new n(function(o){o(i)})}return new(n||(n=Promise))(function(i,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?i(u.value):s(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function Hx(t,e){var n={label:0,sent:function(){if(i[0]&1)throw i[1];return i[1]},trys:[],ops:[]},r,s,i,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,s&&(i=l[0]&2?s.return:l[0]?s.throw||((i=s.return)&&i.call(s),0):s.next)&&!(i=i.call(s,l[1])).done)return i;switch(s=0,i&&(l=[l[0]&2,i.value]),l[0]){case 0:case 1:i=l;break;case 4:return n.label++,{value:l[1],done:!1};case 5:n.label++,s=l[1],l=[0];continue;case 7:l=n.ops.pop(),n.trys.pop();continue;default:if(i=n.trys,!(i=i.length>0&&i[i.length-1])&&(l[0]===6||l[0]===2)){n=0;continue}if(l[0]===3&&(!i||l[1]>i[0]&&l[1]<i[3])){n.label=l[1];break}if(l[0]===6&&n.label<i[1]){n.label=i[1],i=l;break}if(i&&n.label<i[2]){n.label=i[2],n.ops.push(l);break}i[2]&&n.ops.pop(),n.trys.pop();continue}l=e.call(t,n)}catch(u){l=[6,u],s=0}finally{r=i=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Wx(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function Gx(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function la(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 df(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),s,i=[],o;try{for(;(e===void 0||e-- >0)&&!(s=r.next()).done;)i.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return i}function Yx(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(df(arguments[e]));return t}function Zx(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),s=0,e=0;e<n;e++)for(var i=arguments[e],o=0,a=i.length;o<a;o++,s++)r[s]=i[o];return r}function Nr(t){return this instanceof Nr?(this.v=t,this):new Nr(t)}function Xx(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),s,i=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(d,g){i.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(i[0][3],d)}}function c(f){f.value instanceof Nr?Promise.resolve(f.value.v).then(l,u):h(i[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,p){f(p),i.shift(),i.length&&a(i[0][0],i[0][1])}}function Jx(t){var e,n;return e={},r("next"),r("throw",function(s){throw s}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(s,i){e[s]=t[s]?function(o){return(n=!n)?{value:Nr(t[s](o)),done:s==="return"}:i?i(o):o}:i}}function Qx(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 la=="function"?la(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(i){n[i]=t[i]&&function(o){return new Promise(function(a,c){o=t[i](o),s(a,c,o.done,o.value)})}}function s(i,o,a,c){Promise.resolve(c).then(function(l){i({value:l,done:a})},o)}}function e_(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function t_(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 n_(t){return t&&t.__esModule?t:{default:t}}function r_(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function s_(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 i_=Object.freeze({__proto__:null,get __assign(){return ca},__asyncDelegator:Jx,__asyncGenerator:Xx,__asyncValues:Qx,__await:Nr,__awaiter:Kx,__classPrivateFieldGet:r_,__classPrivateFieldSet:s_,__createBinding:Wx,__decorate:jx,__exportStar:Gx,__extends:Mx,__generator:Hx,__importDefault:n_,__importStar:t_,__makeTemplateObject:e_,__metadata:Vx,__param:zx,__read:df,__rest:qx,__spread:Yx,__spreadArrays:Zx,__values:la}),o_=ba(i_),Ut={},pf;function a_(){if(pf)return Ut;pf=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.isBrowserCryptoAvailable=Ut.getSubtleCrypto=Ut.getBrowerCrypto=void 0;function t(){return lt?.crypto||lt?.msCrypto||{}}Ut.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Ut.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Ut.isBrowserCryptoAvailable=n,Ut}var kt={},gf;function c_(){if(gf)return kt;gf=1,Object.defineProperty(kt,"__esModule",{value:!0}),kt.isBrowser=kt.isNode=kt.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}kt.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}kt.isNode=e;function n(){return!t()&&!e()}return kt.isBrowser=n,kt}var yf;function l_(){return yf||(yf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=o_;e.__exportStar(a_(),t),e.__exportStar(c_(),t)}(oa)),oa}var u_=l_();function ze(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(ze(t))}function Lt(t,e,n){return{id:n||ze(),jsonrpc:"2.0",method:t,params:e}}function Ks(t,e){return{id:t,jsonrpc:"2.0",result:e}}function ua(t,e,n){return{id:t,jsonrpc:"2.0",error:h_(e)}}function h_(t,e){return typeof t>"u"?ff(uf):(typeof t=="string"&&(t=Object.assign(Object.assign({},ff(ia)),{message:t})),kx(t.code)&&(t=Lx(t.code)),t)}class f_{}class d_ extends f_{constructor(){super()}}class p_ extends d_{constructor(e){super()}}const g_="^wss?:";function y_(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function w_(t,e){const n=y_(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function wf(t){return w_(t,g_)}function m_(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function mf(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function ha(t){return mf(t)&&"method"in t}function Hs(t){return mf(t)&&(gt(t)||Ye(t))}function gt(t){return"result"in t}function Ye(t){return"error"in t}class b_ extends p_{constructor(e){super(e),this.events=new Je.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(Lt(e.method,e.params||[],e.id||ln().toString()),n)}async requestStrict(e,n){return new Promise(async(r,s)=>{if(!this.connection.connected)try{await this.open()}catch(i){s(i)}this.events.on(`${e.id}`,i=>{Ye(i)?s(i.error):r(i.result)});try{await this.connection.send(e,n)}catch(i){s(i)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),Hs(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 v_=()=>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"),E_=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",bf=t=>t.split("?")[0],vf=10,x_=v_();let __=class{constructor(e){if(this.url=e,this.events=new Je.EventEmitter,this.registering=!1,!wf(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(rr(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!wf(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,s)=>{this.events.once("register_error",i=>{this.resetMaxListeners(),s(i)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const s=u_.isReactNative()?void 0:{rejectUnauthorized:!m_(e)},i=new x_(e,[],s);E_()?i.onerror=o=>{const a=o;r(this.emitError(a.error))}:i.on("error",o=>{r(this.emitError(o))}),i.onopen=()=>{this.onOpen(i),n(i)}})}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"?Un(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),s=r.message||r.toString(),i=ua(e,s);this.events.emit("payload",i)}parseError(e,n=this.url){return Fx(e,bf(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>vf&&this.events.setMaxListeners(vf)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${bf(this.url)}`));return this.events.emit("register_error",n),n}};function I_(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ef(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function xf(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const S_="[object RegExp]",D_="[object String]",A_="[object Number]",T_="[object Boolean]",_f="[object Arguments]",O_="[object Symbol]",$_="[object Date]",R_="[object Map]",B_="[object Set]",P_="[object Array]",C_="[object Function]",N_="[object ArrayBuffer]",fa="[object Object]",U_="[object Error]",k_="[object DataView]",L_="[object Uint8Array]",F_="[object Uint8ClampedArray]",M_="[object Uint16Array]",q_="[object Uint32Array]",j_="[object BigUint64Array]",z_="[object Int8Array]",V_="[object Int16Array]",K_="[object Int32Array]",H_="[object BigInt64Array]",W_="[object Float32Array]",G_="[object Float64Array]";function If(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 Y_(t,e,n){return Ur(t,e,void 0,void 0,void 0,void 0,n)}function Ur(t,e,n,r,s,i,o){const a=o(t,e,n,r,s,i);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 kr(t,e,i,o)}return kr(t,e,i,o)}function kr(t,e,n,r){if(Object.is(t,e))return!0;let s=xf(t),i=xf(e);if(s===_f&&(s=fa),i===_f&&(i=fa),s!==i)return!1;switch(s){case D_:return t.toString()===e.toString();case A_:{const c=t.valueOf(),l=e.valueOf();return I_(c,l)}case T_:case $_:case O_:return Object.is(t.valueOf(),e.valueOf());case S_:return t.source===e.source&&t.flags===e.flags;case C_: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(s){case R_:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!Ur(l,e.get(c),c,t,e,n,r))return!1;return!0}case B_:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(p=>Ur(h,p,void 0,t,e,n,r));if(f===-1)return!1;l.splice(f,1)}return!0}case P_:case L_:case F_:case M_:case q_:case j_:case z_:case V_:case K_:case H_:case W_:case G_:{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(!Ur(t[c],e[c],c,t,e,n,r))return!1;return!0}case N_:return t.byteLength!==e.byteLength?!1:kr(new Uint8Array(t),new Uint8Array(e),n,r);case k_:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:kr(new Uint8Array(t),new Uint8Array(e),n,r);case U_:return t.name===e.name&&t.message===e.message;case fa:{if(!(kr(t.constructor,e.constructor,n,r)||If(t)&&If(e)))return!1;const l=[...Object.keys(t),...Ef(t)],u=[...Object.keys(e),...Ef(e)];if(l.length!==u.length)return!1;for(let h=0;h<l.length;h++){const f=l[h],p=t[f];if(!Object.hasOwn(e,f))return!1;const d=e[f];if(!Ur(p,d,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function Z_(){}function X_(t,e){return Y_(t,e,Z_)}const Sf="wc",Df=2,da="core",yt=`${Sf}@2:${da}:`,J_={logger:"error"},Q_={database:":memory:"},eI="crypto",Af="client_ed25519_seed",tI=F.ONE_DAY,nI="keychain",rI="0.3",sI="messages",iI="0.3",oI=F.SIX_HOURS,aI="publisher",Tf="irn",cI="error",Of="wss://relay.walletconnect.org",lI="relayer",se={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},uI="_subscription",Ze={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},hI=.1,pa="2.25.0",ee={link_mode:"link_mode",relay:"relay"},Ws={inbound:"inbound",outbound:"outbound"},fI="0.3",dI="WALLETCONNECT_CLIENT_ID",$f="WALLETCONNECT_LINK_MODE_APPS",Ve={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},pI="subscription",gI="0.3",yI="pairing",wI="0.3",Lr={wc_pairingDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:F.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:F.ONE_DAY,prompt:!1,tag:0},res:{ttl:F.ONE_DAY,prompt:!1,tag:0}}},Rn={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},it={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},mI="history",bI="0.3",vI="expirer",Xe={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},EI="0.3",xI="verify-api",_I="https://verify.walletconnect.com",Rf="https://verify.walletconnect.org",Fr=Rf,II=`${Fr}/v3`,SI=[_I,Rf],DI="echo",AI="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"},Ft={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"},ot={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",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Bn={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",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Pn={authenticated_session_approve_started:"authenticated_session_approve_started",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"},Mr={no_internet_connection:"no_internet_connection",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"},TI=.1,OI="event-client",$I=86400,RI="https://pulse.walletconnect.org/batch";class BI{constructor(e,n){this.core=e,this.logger=n,this.keychain=new Map,this.name=nI,this.version=rI,this.initialized=!1,this.storagePrefix=yt,this.init=async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}},this.has=r=>(this.isInitialized(),this.keychain.has(r)),this.set=async(r,s)=>{this.isInitialized(),this.keychain.set(r,s),await this.persist()},this.get=r=>{this.isInitialized();const s=this.keychain.get(r);if(typeof s>"u"){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(i)}return s},this.del=async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()},this.core=e,this.logger=Fe(n,this.name)}get context(){return Be(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Go(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Yo(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class PI{constructor(e,n,r){this.core=e,this.logger=n,this.name=eI,this.randomSessionIdentifier=ta(),this.initialized=!1,this.init=async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)},this.hasKeys=s=>(this.isInitialized(),this.keychain.has(s)),this.getClientId=async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),i=Gc(s),o=Wc(i.publicKey);return this.clientId=o,o},this.generateKeyPair=()=>{this.isInitialized();const s=S2();return this.setPrivateKey(s.publicKey,s.privateKey)},this.signJWT=async s=>{this.isInitialized();const i=await this.getClientSeed(),o=Gc(i),a=this.randomSessionIdentifier;return await sw(a,s,tI,o)},this.generateSharedKey=(s,i,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=D2(a,i);return this.setSymKey(c,o)},this.setSymKey=async(s,i)=>{this.isInitialized();const o=i||Ms(s);return await this.keychain.set(o,s),o},this.deleteKeyPair=async s=>{this.isInitialized(),await this.keychain.del(s)},this.deleteSymKey=async s=>{this.isInitialized(),await this.keychain.del(s)},this.encode=async(s,i,o)=>{this.isInitialized();const a=Hh(o),c=rr(i);if(Gh(a))return O2(c,o?.encoding);if(Wh(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const l=this.getSymKey(s),{type:u,senderPublicKey:h}=a;return A2({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o?.encoding})},this.decode=async(s,i,o)=>{this.isInitialized();const a=R2(i,o);if(Gh(a)){const c=$2(i,o?.encoding);return Un(c)}if(Wh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;s=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(s),l=T2({symKey:c,encoded:i,encoding:o?.encoding});return Un(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}},this.getPayloadType=(s,i=Ee)=>{const o=$r({encoded:s,encoding:i});return $n(o.type)},this.getPayloadSenderPublicKey=(s,i=Ee)=>{const o=$r({encoded:s,encoding:i});return o.senderPublicKey?he(o.senderPublicKey,$e):void 0},this.core=e,this.logger=Fe(n,this.name),this.keychain=r||new BI(this.core,this.logger)}get context(){return Be(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(Af)}catch{e=ta(),await this.keychain.set(Af,e)}return _e(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}let CI=class extends og{constructor(e,n){super(e,n),this.logger=e,this.core=n,this.messages=new Map,this.messagesWithoutClientAck=new Map,this.name=sI,this.version=iI,this.initialized=!1,this.storagePrefix=yt,this.init=async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}},this.set=async(r,s,i)=>{this.isInitialized();const o=Ge(s);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(r,a),i===Ws.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,{...c,[o]:s})}return await this.persist(),o},this.get=r=>{this.isInitialized();let s=this.messages.get(r);return typeof s>"u"&&(s={}),s},this.getWithoutAck=r=>{this.isInitialized();const s={};for(const i of r){const o=this.messagesWithoutClientAck.get(i)||{};s[i]=Object.values(o)}return s},this.has=(r,s)=>{this.isInitialized();const i=this.get(r),o=Ge(s);return typeof i[o]<"u"},this.ack=async(r,s)=>{this.isInitialized();const i=this.messagesWithoutClientAck.get(r);if(typeof i>"u")return;const o=Ge(s);delete i[o],Object.keys(i).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,i),await this.persist()},this.del=async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()},this.logger=Fe(e,this.name),this.core=n}get context(){return Be(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,Go(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Go(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Yo(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Yo(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}};class NI extends ag{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.events=new Je.EventEmitter,this.name=aI,this.queue=new Map,this.publishTimeout=F.toMiliseconds(F.ONE_MINUTE),this.initialPublishTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.needsTransportRestart=!1,this.publish=async(r,s,i)=>{this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:s,opts:i}});const o=i?.ttl||oI,a=i?.prompt||!1,c=i?.tag||0,l=i?.id||ln().toString(),u=Yn(js().protocol),h={id:l,method:i?.publishMethod||u.publish,params:{topic:r,message:s,ttl:o,prompt:a,tag:c,attestation:i?.attestation,...i?.tvf}},f=`Failed to publish payload, please try again. id:${l} tag:${c}`;try{de(h.params?.prompt)&&delete h.params?.prompt,de(h.params?.tag)&&delete h.params?.tag;const p=new Promise(async d=>{const g=({id:b})=>{h.id?.toString()===b.toString()&&(this.removeRequestFromQueue(b),this.relayer.events.removeListener(se.publish,g),d())};this.relayer.events.on(se.publish,g);const y=st(new Promise((b,A)=>{this.rpcPublish(h,i).then(b).catch(w=>{this.logger.warn(w,w?.message),A(w)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${l} tag:${c}`);try{await y,this.events.removeListener(se.publish,g)}catch(b){this.queue.set(l,{request:h,opts:i,attempt:1}),this.logger.warn(b,b?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:l,topic:r,message:s,opts:i}}),await st(p,this.publishTimeout,f)}catch(p){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(p),i?.internal?.throwOnFailedPublish)throw p}finally{this.queue.delete(l)}},this.publishCustom=async r=>{this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:s,opts:i={}}=r,{attestation:o,tvf:a,publishMethod:c,prompt:l,tag:u,ttl:h=F.FIVE_MINUTES}=i,f=i.id||ln().toString(),p=Yn(js().protocol),d=c||p.publish,g={id:f,method:d,params:{...s,ttl:h,prompt:l,tag:u,attestation:o,...a}},y=`Failed to publish custom payload, please try again. id:${f} tag:${u}`;try{de(g.params?.prompt)&&delete g.params?.prompt,de(g.params?.tag)&&delete g.params?.tag;const b=new Promise(async A=>{const w=({id:x})=>{g.id?.toString()===x.toString()&&(this.removeRequestFromQueue(x),this.relayer.events.removeListener(se.publish,w),A())};this.relayer.events.on(se.publish,w);const m=st(new Promise((x,_)=>{this.rpcPublish(g,i).then(x).catch(T=>{this.logger.warn(T,T?.message),_(T)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${d} id:${f} tag:${u}`);try{await m,this.events.removeListener(se.publish,w)}catch(x){this.queue.set(f,{request:g,opts:i,attempt:1}),this.logger.warn(x,x?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:f,payload:s,opts:i}}),await st(b,this.publishTimeout,y)}catch(b){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(b),i?.internal?.throwOnFailedPublish)throw b}finally{this.queue.delete(f)}},this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.relayer=e,this.logger=Fe(n,this.name),this.registerEventListeners()}get context(){return Be(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(se.publish,{...e,...n}),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{const r=e.attempt+1;this.queue.set(n,{...e,attempt:r}),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${e.request.params?.tag}, attempt: ${r}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(pn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(se.connection_stalled);return}this.checkQueue()}),this.relayer.on(se.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}class UI{constructor(){this.map=new Map,this.set=(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])},this.get=e=>this.map.get(e)||[],this.exists=(e,n)=>this.get(e).includes(n),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 s=r.filter(i=>i!==n);if(!s.length){this.map.delete(e);return}this.map.set(e,s)},this.clear=()=>{this.map.clear()}}get topics(){return Array.from(this.map.keys())}}class kI extends ug{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,this.subscriptions=new Map,this.topicMap=new UI,this.events=new Je.EventEmitter,this.name=pI,this.version=gI,this.pending=new Map,this.cached=[],this.initialized=!1,this.storagePrefix=yt,this.subscribeTimeout=F.toMiliseconds(F.ONE_MINUTE),this.initialSubscribeTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.batchSubscribeTopicsLimit=500,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0},this.subscribe=async(r,s)=>{this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}});try{const i=js(s),o={topic:r,relay:i,transportType:s?.transportType};s?.internal?.skipSubscribe||this.pending.set(r,o);const a=await this.rpcSubscribe(r,i,s);return typeof a=="string"&&(this.onSubscribe(a,o),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:s}})),a}catch(i){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(i),i}},this.unsubscribe=async(r,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(r,s.id,s):await this.unsubscribeByTopic(r,s)},this.isSubscribed=r=>new Promise(s=>{s(this.topicMap.topics.includes(r))}),this.isKnownTopic=r=>new Promise(s=>{s(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(i=>i.topic===r))}),this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.start=async()=>{await this.onConnect()},this.stop=async()=>{await this.onDisconnect()},this.restart=async()=>{await this.restore(),await this.onRestart()},this.checkPending=async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(s=>{r.push(s)}),await this.batchSubscribe(r)},this.registerEventListeners=()=>{this.relayer.core.heartbeat.on(pn.pulse,async()=>{await this.checkPending()}),this.events.on(Ve.created,async r=>{const s=Ve.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()}),this.events.on(Ve.deleted,async r=>{const s=Ve.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:r}),await this.persist()})},this.relayer=e,this.logger=Fe(n,this.name),this.clientId=""}get context(){return Be(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 s=>await this.unsubscribeById(e,s,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 s=te("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s);const i=js(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,n,r){const s=await this.getSubscriptionId(e);if(r?.internal?.skipSubscribe)return s;(!r||r?.transportType===ee.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const i={method:Yn(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});const o=r?.internal?.throwOnFailedPublish;try{if(r?.transportType===ee.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(i).catch(l=>this.logger.warn(l))},F.toMiliseconds(F.ONE_SECOND)),s;const a=new Promise(async l=>{const u=h=>{h.topic===e&&(this.events.removeListener(Ve.created,u),l(h.id))};this.events.on(Ve.created,u);try{const h=await st(new Promise((f,p)=>{this.relayer.request(i).catch(d=>{this.logger.warn(d,d?.message),p(d)}).then(f)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ve.created,u),l(h)}catch{}}),c=await st(a,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!c&&o)throw new Error(`Subscribing to ${e} failed, please try again`);return c?s:null}catch(a){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(se.connection_stalled),o)throw a}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const n=e[0].relay,r={method:Yn(n.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{return await st(new Promise((s,i)=>{this.relayer.request(r).then(s).catch(o=>{this.logger.warn(o),i(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(se.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Yn(n.protocol).batchFetchMessages,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let s;try{s=await await st(new Promise((i,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(i)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(se.connection_stalled)}return s}rpcUnsubscribe(e,n,r){const s={method:Yn(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,n){this.setSubscription(e,{...n,id:e}),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,{...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,{...n}),this.topicMap.set(n.topic,e),this.events.emit(Ve.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}=M("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(Ve.deleted,{...r,reason:n})}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ve.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 s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(Ve.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>n.topic===this.subscriptions.get(n.id)?.topic)){const{message:n}=M("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){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(n=>{this.pending.set(n.topic,n)});return}this.onBatchSubscribe(await Promise.all(e.map(async n=>({...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 VE(F.toMiliseconds(F.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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return Ge(e+await this.getClientId())}}let LI=class extends cg{constructor(e){super(e),this.protocol="wc",this.version=2,this.events=new Je.EventEmitter,this.name=lI,this.transportExplicitlyClosed=!1,this.initialized=!1,this.connectionAttemptInProgress=!1,this.hasExperiencedNetworkDisruption=!1,this.heartBeatTimeout=F.toMiliseconds(F.THIRTY_SECONDS+F.FIVE_SECONDS),this.reconnectInProgress=!1,this.requestsInFlight=[],this.connectTimeout=F.toMiliseconds(F.ONE_SECOND*15),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,this.stalledRestartBaseInterval=F.toMiliseconds(F.ONE_SECOND*2),this.stalledRestartMaxInterval=F.toMiliseconds(F.THIRTY_SECONDS),this.request=async n=>{this.logger.debug("Publishing Request Payload");const r=n.id||ln().toString();await this.toEstablishConnection();try{this.logger.trace({id:r,method:n.method,topic:n.params?.topic},"relayer.request - publishing...");const s=`${r}:${n.params?.tag||""}`;this.requestsInFlight.push(s);const i=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(o=>o!==s),i}catch(s){throw this.logger.debug(`Failed to Publish Request: ${r}`),s}},this.resetPingTimeout=()=>{Cs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),this.provider?.connection?.socket?.terminate?.()}catch(n){this.logger.warn(n,n?.message)}},this.heartBeatTimeout))},this.onPayloadHandler=n=>{this.onProviderPayload(n),this.resetPingTimeout()},this.onConnectHandler=()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.stalledRestartBackoff=0,this.events.emit(se.connect)},this.onDisconnectHandler=()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()},this.onProviderErrorHandler=n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(se.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(r=>this.logger.warn(r))},this.registerProviderListeners=()=>{this.provider.on(Ze.payload,this.onPayloadHandler),this.provider.on(Ze.connect,this.onConnectHandler),this.provider.on(Ze.disconnect,this.onDisconnectHandler),this.provider.on(Ze.error,this.onProviderErrorHandler)},this.core=e.core,this.logger=lf({logger:e.logger??cI,name:this.name}),this.messages=new CI(this.logger,e.core),this.subscriber=new kI(this,this.logger),this.publisher=new NI(this,this.logger),this.projectId=e.projectId,this.relayUrl=e.relayUrl||Of,TE()?this.packageName=xh():OE()&&(this.bundleId=xh()),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 Be(this.logger)}get connected(){return this.provider?.connection?.socket?.readyState===1}get connecting(){return this.provider?.connection?.socket?.readyState===0||this.connectPromise!==void 0}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:ee.relay},Ws.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){this.isInitialized(),(!n?.transportType||n?.transportType==="relay")&&await this.toEstablishConnection();const r=n?.internal?.throwOnFailedPublish??!0;let s=this.subscriber.topicMap.get(e)?.[0]||"",i;const o=a=>{a.topic===e&&(this.subscriber.off(Ve.created,o),i())};return await Promise.all([new Promise(a=>{i=a,this.subscriber.on(Ve.created,o)}),new Promise((a,c)=>{this.subscriber.subscribe(e,{internal:{throwOnFailedPublish:r},...n}).then(l=>{s=l||s,a()}).catch(l=>{r?c(l):a()})})]),s}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 st(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}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=this.connect(e).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.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await cf())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,s)=>r.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const s=fe(F.FIVE_MINUTES),i={topic:r,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,i)}this.events.emit(se.message,e),await this.recordMessageEvent(e,Ws.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.transportExplicitlyClosed=!1;let n=1;try{for(;n<6;){this.connectionAttemptInProgress=!0;try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise((r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(Ze.disconnect,i),st(this.provider.connect(),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).then(()=>r()).catch(s).finally(()=>{this.provider.off(Ze.disconnect,i),clearTimeout(this.reconnectTimeout)})}),await new Promise((r,s)=>{const i=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(Ze.disconnect,i),this.subscriber.start().then(r).catch(s).finally(()=>{this.provider.off(Ze.disconnect,i)})}),this.hasExperiencedNetworkDisruption=!1}catch(r){await this.subscriber.stop();const s=r;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,F.toMiliseconds(n*1))),n++}}finally{this.connectionAttemptInProgress=!1,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1}}startPingTimeout(){if(Cs())try{this.provider?.connection?.socket?.on("ping",()=>{this.resetPingTimeout()}),this.resetPingTimeout()}catch(e){this.logger.warn(e,e?.message)}}async createProvider(){if(this.provider.connection&&(this.unregisterProviderListeners(),this.connected))try{await st(this.provider.disconnect(),1e3,"Closing previous provider")}catch{}const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new b_(new __(CE({sdkVersion:pa,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:s}=e;await this.messages.set(r,s,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 s=this.messages.has(n,r);return s&&this.logger.warn(`Ignoring duplicate message: ${r}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),ha(e)){if(!e.method.endsWith(uI))return;const n=e.params,{topic:r,message:s,publishedAt:i,attestation:o}=n.data,a={topic:r,message:s,publishedAt:i,transportType:ee.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace({type:"event",event:n.id,...a}),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Hs(e)&&this.events.emit(se.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,Ws.inbound),this.events.emit(se.message,e))}async acknowledgePayload(e){const n=Ks(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(Ze.payload,this.onPayloadHandler),this.provider.off(Ze.connect,this.onConnectHandler),this.provider.off(Ze.disconnect,this.onDisconnectHandler),this.provider.off(Ze.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await cf();wx(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(pn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&vx())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}}),this.events.on(se.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const n=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${n?` in ${n}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(r){this.logger.error(r,r?.message)}finally{this.stalledRestartInProgress=!1}},n)})}async onProviderDisconnect(){if(clearTimeout(this.pingTimeout),this.events.emit(se.disconnect),!this.reconnectInProgress){this.reconnectInProgress=!0;try{await this.subscriber.stop()}catch(e){this.logger.warn(e,"subscriber.stop() failed during disconnect")}if(!this.subscriber.hasAnyTopics||this.transportExplicitlyClosed){this.reconnectInProgress=!1;return}this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},F.toMiliseconds(hI))}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}this.connectPromise=this.connect().finally(()=>{this.connectPromise=void 0}),await this.connectPromise}}};class Cn extends lg{constructor(e,n,r,s=yt,i=void 0){super(e,n,r,s),this.core=e,this.logger=n,this.name=r,this.map=new Map,this.version=fI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,this.recentlyDeleted=[],this.recentlyDeletedLimit=200,this.init=async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!de(o)?this.map.set(this.getKey(o),o):G2(o)?this.map.set(o.id,o):Y2(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)},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())},this.get=o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o)),this.getAll=o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>X_(a[c],o[c]))):this.values),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={...this.getData(o),...a};this.map.set(o,c),await this.persist()},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=Fe(n,this.name),this.storagePrefix=s,this.getKey=i}get context(){return Be(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:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return 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}=M("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}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class FI{constructor(e,n){this.core=e,this.logger=n,this.name=yI,this.version=wI,this.events=new Zs,this.initialized=!1,this.storagePrefix=yt,this.ignoredPayloadTypes=[Nt],this.registeredMethods=[],this.init=async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))},this.register=({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]},this.create=async r=>{this.isInitialized();const s=ta(),i=await this.core.crypto.setSymKey(s),o=fe(F.FIVE_MINUTES),a={protocol:Tf},c={topic:i,expiry:o,relay:a,active:!1,methods:r?.methods},l=Zh({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:s,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Rn.create,c),this.core.expirer.set(i,o),await this.pairings.set(i,c),await this.core.relayer.subscribe(i,{transportType:r?.transportType,internal:r?.internal}),{topic:i,uri:l}},this.pair=async r=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[wt.pairing_started]}});this.isValidPair(r,s);const{topic:i,symKey:o,relay:a,expiryTimestamp:c,methods:l}=Yh(r.uri);s.props.properties.topic=i,s.addTrace(wt.pairing_uri_validation_success),s.addTrace(wt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(i)){if(u=this.pairings.get(i),s.addTrace(wt.existing_pairing),u.active)throw s.setError(Ft.active_pairing_already_exists),new Error(`Pairing already exists: ${i}. Please try again with a new connection URI.`);s.addTrace(wt.pairing_not_expired)}const h=c||fe(F.FIVE_MINUTES),f={topic:i,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(i,h),await this.pairings.set(i,f),s.addTrace(wt.store_new_pairing),r.activatePairing&&await this.activate({topic:i}),this.events.emit(Rn.create,f),s.addTrace(wt.emit_inactive_pairing),this.core.crypto.keychain.has(i)||await this.core.crypto.setSymKey(o,i),s.addTrace(wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(Ft.no_internet_connection)}try{await this.core.relayer.subscribe(i,{relay:a})}catch(p){throw s.setError(Ft.subscribe_pairing_topic_failure),p}return s.addTrace(wt.subscribe_pairing_topic_success),f},this.activate=async({topic:r})=>{this.isInitialized();const s=fe(F.FIVE_MINUTES);this.core.expirer.set(r,s),await this.pairings.update(r,{active:!0,expiry:s})},this.ping=async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=r;if(this.pairings.keys.includes(s)){const i=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Sn();this.events.once(J("pairing_ping",i),({error:l})=>{l?c(l):a()}),await o()}},this.updateExpiry=async({topic:r,expiry:s})=>{this.isInitialized(),await this.pairings.update(r,{expiry:s})},this.updateMetadata=async({topic:r,metadata:s})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:s})},this.getPairings=()=>(this.isInitialized(),this.pairings.values),this.disconnect=async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:s}=r;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",te("USER_DISCONNECTED")),await this.deletePairing(s))},this.formatUriFromPairing=r=>{this.isInitialized();const{topic:s,relay:i,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(s);return Zh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:i,expiryTimestamp:o,methods:a})},this.sendRequest=async(r,s,i)=>{const o=Lt(s,i),a=await this.core.crypto.encode(r,o),c=Lr[s].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id},this.sendResult=async(r,s,i)=>{const o=Ks(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Lr[c].res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)},this.sendError=async(r,s,i)=>{const o=ua(r,i),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,r)).request.method,l=Lr[c]?Lr[c].res:Lr.unregistered_method.res;await this.core.relayer.publish(s,a,l),await this.core.history.resolve(o)},this.deletePairing=async(r,s)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,te("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),s?Promise.resolve():this.core.expirer.del(r)])},this.cleanup=async()=>{const r=this.pairings.getAll().filter(s=>cn(s.expiry));await Promise.all(r.map(s=>this.deletePairing(s.topic)))},this.onRelayEventRequest=async r=>{const{topic:s,payload:i}=r;switch(i.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,i);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,i);default:return await this.onUnknownRpcMethodRequest(s,i)}},this.onRelayEventResponse=async r=>{const{topic:s,payload:i}=r,o=(await this.core.history.get(s,i.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,i);default:return this.onUnknownRpcMethodResponse(o)}},this.onPairingPingRequest=async(r,s)=>{const{id:i}=s;try{this.isValidPing({topic:r}),await this.sendResult(i,r,!0),this.events.emit(Rn.ping,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}},this.onPairingPingResponse=(r,s)=>{const{id:i}=s;setTimeout(()=>{gt(s)?this.events.emit(J("pairing_ping",i),{}):Ye(s)&&this.events.emit(J("pairing_ping",i),{error:s.error})},500)},this.onPairingDeleteRequest=async(r,s)=>{const{id:i}=s;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Rn.delete,{id:i,topic:r})}catch(o){await this.sendError(i,r,o),this.logger.error(o)}},this.onUnknownRpcMethodRequest=async(r,s)=>{const{id:i,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=te("WC_METHOD_UNSUPPORTED",o);await this.sendError(i,r,a),this.logger.error(a)}catch(a){await this.sendError(i,r,a),this.logger.error(a)}},this.onUnknownRpcMethodResponse=r=>{this.registeredMethods.includes(r)||this.logger.error(te("WC_METHOD_UNSUPPORTED",r))},this.isValidPair=(r,s)=>{if(!Le(r)){const{message:o}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(!W2(r.uri)){const{message:o}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw s.setError(Ft.malformed_pairing_uri),new Error(o)}const i=Yh(r?.uri);if(!i?.relay?.protocol){const{message:o}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(!i?.symKey){const{message:o}=M("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(Ft.malformed_pairing_uri),new Error(o)}if(i?.expiryTimestamp&&F.toMiliseconds(i?.expiryTimestamp)<Date.now()){s.setError(Ft.pairing_expired);const{message:o}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(o)}},this.isValidPing=async r=>{if(!Le(r)){const{message:i}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)},this.isValidDisconnect=async r=>{if(!Le(r)){const{message:i}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(i)}const{topic:s}=r;await this.isValidPairingTopic(s)},this.isValidPairingTopic=async r=>{if(!oe(r,!1)){const{message:s}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(s)}if(!this.pairings.keys.includes(r)){const{message:s}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(s)}if(cn(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:s}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(s)}},this.core=e,this.logger=Fe(n,this.name),this.pairings=new Cn(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Be(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(se.message,async e=>{const{topic:n,message:r,transportType:s}=e;if(this.pairings.keys.includes(n)&&s!==ee.link_mode){try{if(this.core.crypto.getPayloadType(r,pt)===On){this.logger.warn(`registerRelayerEvents() -> non-link mode TYPE_2 payload ignored: ${r}`);return}}catch{}if(!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const i=await this.core.crypto.decode(n,r);ha(i)?(this.core.history.set(n,i),await this.onRelayEventRequest({topic:n,payload:i})):Hs(i)&&(await this.core.history.resolve(i),await this.onRelayEventResponse({topic:n,payload:i}),this.core.history.delete(n,i.id)),await this.core.relayer.messages.ack(n,r)}catch(i){this.logger.error(i)}}})}registerExpirerEvents(){this.core.expirer.on(Xe.expired,async e=>{const{topic:n}=Dh(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Rn.expire,{topic:n}))})}}class MI extends ig{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.records=new Map,this.events=new Je.EventEmitter,this.name=mI,this.version=bI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,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)},this.set=(r,s,i)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:s,chainId:i}),this.records.has(s.id))return;const o={id:s.id,topic:r,request:{method:s.method,params:s.params||null},chainId:i,expiry:fe(F.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(it.created,o)},this.resolve=async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const s=await this.getRecord(r.id);typeof s.response<"u"||(s.response=Ye(r)?{error:r.error}:{result:r.result},this.records.set(s.id,s),this.persist(),this.events.emit(it.updated,s))},this.get=async(r,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:s}),await this.getRecord(s)),this.delete=(r,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(i=>{if(i.topic===r){if(typeof s<"u"&&i.id!==s)return;this.records.delete(i.id),this.events.emit(it.deleted,i)}}),this.persist()},this.exists=async(r,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===r:!1),this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.logger=Fe(n,this.name)}get context(){return Be(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:Lt(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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(it.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=M("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(it.created,e=>{const n=it.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(it.updated,e=>{const n=it.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(it.deleted,e=>{const n=it.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(pn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{F.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(it.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class qI extends hg{constructor(e,n){super(e,n),this.core=e,this.logger=n,this.expirations=new Map,this.events=new Je.EventEmitter,this.name=vI,this.version=EI,this.cached=[],this.initialized=!1,this.storagePrefix=yt,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)},this.has=r=>{try{const s=this.formatTarget(r);return typeof this.getExpiration(s)<"u"}catch{return!1}},this.set=(r,s)=>{this.isInitialized();const i=this.formatTarget(r),o={target:i,expiry:s};this.expirations.set(i,o),this.checkExpiry(i,o),this.events.emit(Xe.created,{target:i,expiration:o})},this.get=r=>{this.isInitialized();const s=this.formatTarget(r);return this.getExpiration(s)},this.del=r=>{if(this.isInitialized(),this.has(r)){const s=this.formatTarget(r),i=this.getExpiration(s);this.expirations.delete(s),this.events.emit(Xe.deleted,{target:s,expiration:i})}},this.on=(r,s)=>{this.events.on(r,s)},this.once=(r,s)=>{this.events.once(r,s)},this.off=(r,s)=>{this.events.off(r,s)},this.removeListener=(r,s)=>{this.events.removeListener(r,s)},this.logger=Fe(n,this.name)}get context(){return Be(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 NE(e);if(typeof e=="number")return UE(e);const{message:n}=M("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(Xe.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=M("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}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;F.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Xe.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(pn.pulse,()=>this.checkExpirations()),this.events.on(Xe.created,e=>{const n=Xe.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Xe.expired,e=>{const n=Xe.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Xe.deleted,e=>{const n=Xe.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}class jI extends fg{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,this.name=xI,this.verifyUrlV3=II,this.storagePrefix=yt,this.version=Df,this.init=async()=>{this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&F.toMiliseconds(this.publicKey?.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))},this.register=async s=>{if(!Gn()||this.isDevEnv)return;const i=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${i}&id=${o}&decryptedId=${a}`;try{const l=xt.getDocument(),u=this.startAbortTimer(F.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",y),l.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",d,{signal:this.abortController.signal});const y=b=>{if(b.data&&typeof b.data=="string")try{const A=JSON.parse(b.data);if(A.type==="verify_attestation"){if(Fi(A.attestation).payload.id!==o)return;clearInterval(u),l.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)}};l.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""},this.resolve=async s=>{if(this.isDevEnv)return"";const{attestationId:i,hash:o,encryptedId:a}=s;if(i===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(i){if(Fi(i).payload.id!==a)return;const l=await this.isValidJwtAttestation(i);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(s?.verifyUrl);return this.fetchAttestation(o,c)},this.fetchAttestation=async(s,i)=>{this.logger.debug(`resolving attestation: ${s} from url: ${i}`);const o=this.startAbortTimer(F.ONE_SECOND*5),a=await fetch(`${i}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0},this.getVerifyUrl=s=>{let i=s||Fr;return SI.includes(i)||(this.logger.info(`verify url: ${i}, not included in trusted list, assigning default: ${Fr}`),i=Fr),i},this.fetchPublicKey=async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(F.FIVE_SECONDS),i=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await i.json()}catch(s){this.logger.warn(s)}},this.persistPublicKey=async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s},this.removePublicKey=async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0},this.isValidJwtAttestation=async s=>{const i=await this.getPublicKey();try{if(i)return this.validateAttestation(s,i)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}},this.getPublicKey=async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey(),this.fetchAndPersistPublicKey=async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async i=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),i(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s},this.validateAttestation=(s,i)=>{const o=P2(s,i.publicKey),a={hasExpired:F.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=Fe(n,this.name),this.abortController=new AbortController,this.isDevEnv=Ns(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Be(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),F.toMiliseconds(e))}}let zI=class extends dg{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,this.context=DI,this.registerDeviceToken=async r=>{const{clientId:s,token:i,notificationType:o,enableEncrypted:a=!1}=r,c=`${AI}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:i,always_raw:a})})},this.logger=Fe(n,this.context)}};class VI extends pg{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,this.context=OI,this.storagePrefix=yt,this.storageVersion=TI,this.events=new Map,this.shouldPersist=!1,this.init=async()=>{if(!Ns())try{const s={eventId:Zo(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Ih(this.core.relayer.protocol,this.core.relayer.version,pa)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}},this.createEvent=s=>{const{event:i="ERROR",type:o="",properties:{topic:a,trace:c}}=s,l=Zo(),u=this.core.projectId||"",h=Date.now(),f={eventId:l,timestamp:h,props:{event:i,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain(),...this.setMethods(l)};return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f},this.getEvent=s=>{const{eventId:i,topic:o}=s;if(i)return this.events.get(i);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return{...a,...this.setMethods(a.eventId)}},this.deleteEvent=s=>{const{eventId:i}=s;this.events.delete(i),this.shouldPersist=!0},this.sendFunnelEvent=async({sdkType:s,event:i,properties:o})=>{if(!(!this.telemetryEnabled||Ns()))try{const a={eventId:Zo(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:i,properties:{...o,projectId:this.core.projectId,clientId:await this.core.crypto.getClientId()}}},c=await this.sendEvent([a],s);c.ok||this.logger.warn(`Failed to send ${i}: status ${c.status}`)}catch(a){this.logger.warn(a,`Failed to send ${i}`)}},this.setEventListeners=()=>{this.core.heartbeat.on(pn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{F.fromMiliseconds(Date.now())-F.fromMiliseconds(s.timestamp)>$I&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})},this.setMethods=s=>({addTrace:i=>this.addTrace(s,i),setError:i=>this.setError(s,i)}),this.addTrace=(s,i)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(i),this.events.set(s,o),this.shouldPersist=!0)},this.setError=(s,i)=>{const o=this.events.get(s);o&&(o.props.type=i,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)},this.persist=async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1},this.restore=async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(i=>{this.events.set(i.eventId,{...i,...this.setMethods(i.eventId)})})}catch(s){this.logger.warn(s)}},this.submit=async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[i,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const i of s)this.events.delete(i.eventId),this.shouldPersist=!0}catch(i){this.logger.warn(i)}},this.sendEvent=async(s,i="events_sdk")=>{const o=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${RI}?projectId=${this.core.projectId}&st=${i}&sv=js-${pa}${o}`,{method:"POST",body:JSON.stringify(s)})},this.getAppDomain=()=>_h().url,this.logger=Fe(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}}const KI=class Yf extends sg{constructor(e){super(e),this.protocol=Sf,this.version=Df,this.name=da,this.events=new Je.EventEmitter,this.initialized=!1,this.on=(o,a)=>this.events.on(o,a),this.once=(o,a)=>this.events.once(o,a),this.off=(o,a)=>this.events.off(o,a),this.removeListener=(o,a)=>this.events.removeListener(o,a),this.dispatchEnvelope=({topic:o,message:a,sessionExists:c})=>{if(!o||!a)return;const l={topic:o,message:a,publishedAt:Date.now(),transportType:ee.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:c})};const n=this.getGlobalCore(e?.customStoragePrefix);if(n)try{return this.customStoragePrefix=n.customStoragePrefix,this.logger=n.logger,this.heartbeat=n.heartbeat,this.crypto=n.crypto,this.history=n.history,this.expirer=n.expirer,this.storage=n.storage,this.relayer=n.relayer,this.pairing=n.pairing,this.verify=n.verify,this.echoClient=n.echoClient,this.linkModeSupportedApps=n.linkModeSupportedApps,this.eventClient=n.eventClient,this.initialized=n.initialized,this.logChunkController=n.logChunkController,n}catch(o){console.warn("Failed to copy global core",o)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Of,this.customStoragePrefix=e?.customStoragePrefix?`:${e.customStoragePrefix}`:"";const r=Qp({level:typeof e?.logger=="string"&&e.logger?e.logger:J_.logger,name:da}),{logger:s,chunkLoggerController:i}=ec({opts:r,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=i,this.logChunkController?.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{this.logChunkController?.downloadLogsBlobInBrowser&&this.logChunkController?.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()})}),this.logger=Fe(s,this.name),this.heartbeat=new li,this.crypto=new PI(this,this.logger,e?.keychain),this.history=new MI(this,this.logger),this.expirer=new qI(this,this.logger),this.storage=e?.storage?e.storage:new dp({...Q_,...e?.storageOptions}),this.relayer=new LI({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new FI(this,this.logger),this.verify=new jI(this,this.logger,this.storage),this.echoClient=new zI(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new VI(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new Yf(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(dI,r),n}get context(){return Be(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){return this.logChunkController?.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem($f,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($f)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),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){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e.opts?.customStoragePrefix||""}`;globalThis[n]=e}catch(n){console.warn("Failed to set global WalletConnect core",n)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}},Bf="wc",Pf=2,Cf="client",ga=`${Bf}@${Pf}:${Cf}:`,ya={name:Cf,logger:"error"},Nf="WALLETCONNECT_DEEPLINK_CHOICE",HI="proposal",Uf="Proposal expired",WI="session",Jn=F.SEVEN_DAYS,GI="engine",xe={wc_sessionPropose:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1104},res:{ttl:F.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1106},res:{ttl:F.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:F.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:F.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1112},res:{ttl:F.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1114},res:{ttl:F.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:F.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:F.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1119}}},wa={min:F.FIVE_MINUTES,max:F.SEVEN_DAYS},mt={idle:"IDLE",active:"ACTIVE"},YI={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:""},canton_prepareSignExecute:{key:""},stellar_signXDR:{key:""},stellar_signAndSubmitXDR:{key:"tx_hash"}},ZI="request",XI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],JI="wc",QI="auth",eS="authKeys",tS="pairingTopics",nS="requests",Gs=`${JI}@${1.5}:${QI}:`,un=`${Gs}:PUB_KEY`;class rS extends yg{constructor(e){super(e),this.name=GI,this.events=new Zs,this.initialized=!1,this.requestQueue={state:mt.idle,queue:[]},this.sessionRequestQueue={state:mt.idle,queue:[]},this.emittedSessionRequests=new KE({limit:500}),this.requestQueueDelay=F.ONE_SECOND,this.expectedPairingMethodMap=new Map,this.recentlyDeletedMap=new Map,this.recentlyDeletedLimit=200,this.relayMessageCache=[],this.pendingSessions=new Map,this.init=async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),this.registerSubscriptionCleanup(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(xe)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay)))},this.connect=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r={...n,requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}};await this.isValidConnect(r),r.optionalNamespaces=V2(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:i,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:l,authentication:u,walletPay:h}=r,f=u?.[0]?.ttl||xe.wc_sessionPropose.req.ttl||F.FIVE_MINUTES;this.validateRequestExpiry(f);let p=s,d,g=!1;try{if(p){const $=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),$}if(!p||!g){const{topic:$,uri:P}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=$,d=P}if(!p){const{message:$}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error($)}const y=await this.client.core.crypto.generateKeyPair(),b=fe(f),A={requiredNamespaces:i,optionalNamespaces:o,relays:l??[{protocol:Tf}],proposer:{publicKey:y,metadata:this.client.metadata},expiryTimestamp:b,pairingTopic:p,...a&&{sessionProperties:a},...c&&{scopedProperties:c},id:ze(),...(u||h)&&{requests:{authentication:u?.map($=>{const{domain:P,chains:k,nonce:U,uri:N,exp:S,nbf:R,type:v,statement:E,requestId:D,resources:B,signatureTypes:I}=$;return{domain:P,chains:k,nonce:U,type:v??"caip122",aud:N,version:"1",iat:new Date().toISOString(),exp:S,nbf:R,statement:E,requestId:D,resources:B,signatureTypes:I}}),walletPay:h}}},w=J("session_connect",A.id),{reject:m,resolve:x,done:_}=Sn(f,Uf),T=({id:$})=>{if($===A.id){this.client.events.off("proposal_expire",T);const P=this.pendingSessions.get(A.id);if(P){const{sessionTopic:k,publicKey:U}=P;Promise.all([this.client.core.relayer.unsubscribe(k),this.client.core.crypto.keychain.has(k)?this.client.core.crypto.deleteSymKey(k):Promise.resolve(),this.client.core.crypto.keychain.has(U)?this.client.core.crypto.deleteKeyPair(U):Promise.resolve()]).catch(N=>this.client.logger.warn(N))}this.pendingSessions.delete(A.id),this.events.emit(w,{error:{message:Uf,code:0}})}};return this.client.events.on("proposal_expire",T),this.events.once(w,({error:$,session:P})=>{this.client.events.off("proposal_expire",T),$?m($):P&&x(P)}),await this.setProposal(A.id,A),await this.sendProposeSession({proposal:A,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:A.id}}}).catch($=>{throw this.deleteProposal(A.id),$}),{uri:d,approval:_}},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}},this.approve=async n=>{const r=this.client.core.eventClient.createEvent({properties:{topic:n?.id?.toString(),trace:[ot.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(T){throw r.setError(Bn.no_internet_connection),T}try{await this.isValidProposalId(n?.id)}catch(T){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),r.setError(Bn.proposal_not_found),T}try{await this.isValidApprove(n)}catch(T){throw this.client.logger.error("approve() -> isValidApprove() failed"),r.setError(Bn.session_approve_namespace_validation_failure),T}const{id:s,relayProtocol:i,namespaces:o,sessionProperties:a,scopedProperties:c,sessionConfig:l,proposalRequestsResponses:u}=n,h=this.client.proposal.get(s);this.client.core.eventClient.deleteEvent({eventId:r.eventId});const{pairingTopic:f,proposer:p,requiredNamespaces:d,optionalNamespaces:g}=h;let y=this.client.core.eventClient?.getEvent({topic:f});y||(y=this.client.core.eventClient?.createEvent({type:ot.session_approve_started,properties:{topic:f,trace:[ot.session_approve_started,ot.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),A=p.publicKey,w=await this.client.core.crypto.generateSharedKey(b,A),m={relay:{protocol:i??"irn"},namespaces:o,controller:{publicKey:b,metadata:this.client.metadata},expiry:fe(Jn),...a&&{sessionProperties:a},...c&&{scopedProperties:c},...l&&{sessionConfig:l},proposalRequestsResponses:u},x=ee.relay;y.addTrace(ot.subscribing_session_topic);try{await this.client.core.relayer.subscribe(w,{transportType:x,internal:{skipSubscribe:!0}})}catch(T){throw y.setError(Bn.subscribe_session_topic_failure),T}y.addTrace(ot.subscribe_session_topic_success);const _={...m,topic:w,requiredNamespaces:d,optionalNamespaces:g,pairingTopic:f,acknowledged:!1,self:m.controller,peer:{publicKey:p.publicKey,metadata:p.metadata},controller:b,transportType:ee.relay,authentication:u?.authentication,walletPayResult:u?.walletPay};await this.client.session.set(w,_),y.addTrace(ot.store_session);try{await this.sendApproveSession({sessionTopic:w,proposal:h,pairingProposalResponse:{relay:{protocol:i??"irn"},responderPublicKey:b},sessionSettleRequest:m,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:s,...this.getTVFApproveParams(_)}}}),y.addTrace(ot.session_approve_publish_success)}catch(T){throw this.client.logger.error(T),this.client.session.delete(w,te("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(w),T}return this.client.core.eventClient.deleteEvent({eventId:y.eventId}),await this.client.core.pairing.updateMetadata({topic:f,metadata:p.metadata}),await this.deleteProposal(s),await this.client.core.pairing.activate({topic:f}),await this.setExpiry(w,fe(Jn)),{topic:w,acknowledged:()=>Promise.resolve(this.client.session.get(w))}},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:s}=n;let i;try{i=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}i&&await this.sendError({id:r,topic:i,error:s,rpcOpts:xe.wc_sessionPropose.reject}),await this.deleteProposal(r)},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:s}=n,i=this.client.session.get(r);if(i.self.publicKey!==i.controller){const{message:f}=te("UNAUTHORIZED_UPDATE_REQUEST");throw new Error(f)}const{done:o,resolve:a,reject:c}=Sn(F.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),l=ze(),u=ln().toString(),h=this.client.session.get(r).namespaces;return this.events.once(J("session_update",l),({error:f})=>{f?c(f):a()}),await this.client.session.update(r,{namespaces:s}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:l,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:h}),c(f)}),{acknowledged:o}},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,s=ze(),{done:i,resolve:o,reject:a}=Sn(F.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(J("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,fe(Jn)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:i}},this.request=async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(b){throw this.client.logger.error("request() -> isValidRequest() failed"),b}const{chainId:r,request:s,topic:i,expiry:o=xe.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(i);a?.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const c=ze(),l=ln().toString(),{done:u,resolve:h,reject:f}=Sn(o,"Request expired. Please try again.");this.events.once(J("session_request",c),({error:b,result:A})=>{b?f(b):h(A)});const p="wc_sessionRequest",d={topic:i,request:s,chainId:r,id:c},g=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(g){await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:{request:{...s,expiryTimestamp:fe(o)},chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:g}).catch(A=>f(A)),this.client.events.emit("session_request_sent",d);const b=await u();return this.client.events.emit("session_request_success",d),b}const y={request:{...s,expiryTimestamp:fe(o)},chainId:r};return await Promise.all([new Promise(async b=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:i,method:p,params:y,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,y)}).catch(A=>f(A)),this.client.events.emit("session_request_sent",d),b()}),new Promise(async b=>{if(!a.sessionConfig?.disableDeepLink){const A=await ME(this.client.core.storage,Nf);await kE({id:c,topic:i,wcDeepLink:A})}b()}),u()]).then(b=>(this.client.events.emit("session_request_success",d),b[2]))},this.respond=async n=>{this.isInitialized();const r=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||n?.response?.id?.toString(),trace:[ot.session_request_response_started]}});try{await this.isValidRespond(n)}catch(l){throw r.addTrace(l?.message),r.setError(Bn.session_request_response_validation_failure),l}r.addTrace(ot.session_request_response_validation_success);const{topic:s,response:i}=n,{id:o}=i,a=this.client.session.get(s);a.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const c=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);try{r.addTrace(ot.session_request_response_publish_started),gt(i)?await this.sendResult({id:o,topic:s,result:i.result,throwOnFailedPublish:!0,appLink:c}):Ye(i)&&await this.sendError({id:o,topic:s,error:i.error,appLink:c}),this.cleanupAfterResponse(n)}catch(l){throw r.addTrace(l?.message),r.setError(Bn.session_request_response_publish_failure),l}},this.ping=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:r}=n;if(this.client.session.keys.includes(r)){const s=ze(),i=ln().toString(),{done:o,resolve:a,reject:c}=Sn(F.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(J("session_ping",s),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:i}),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}))},this.emit=async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:s,chainId:i}=n,o=ln().toString(),a=ze();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:s,chainId:i},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})},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:te("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:s}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(s)}},this.find=n=>(this.isInitialized(),this.client.session.getAll().filter(r=>K2(r,n))),this.getPendingSessionRequests=()=>this.client.pendingRequest.getAll(),this.authenticate=async(n,r)=>{this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&this.client.metadata.redirect?.linkMode,i=s?ee.link_mode:ee.relay;i===ee.relay&&await this.confirmOnlineStateOrThrow();const{chains:o,statement:a="",uri:c,domain:l,nonce:u,type:h,exp:f,nbf:p,methods:d=[],expiry:g}=n,y=[...n.resources||[]],{topic:b,uri:A}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:i});if(this.client.logger.info({message:"Generated new pairing",pairing:{topic:b,uri:A}}),this.client.auth.authKeys.keys.includes(un)){const{responseTopic:I,publicKey:O}=this.client.auth.authKeys.get(un);I&&(await this.client.core.relayer.unsubscribe(I).catch(C=>this.client.logger.warn(C)),await this.client.auth.pairingTopics.delete(I,{message:"replaced",code:0}).catch(C=>this.client.logger.warn(C))),O&&this.client.core.crypto.keychain.has(O)&&await this.client.core.crypto.deleteKeyPair(O)}const w=await this.client.core.crypto.generateKeyPair(),m=Ms(w);if(await Promise.all([this.client.auth.authKeys.set(un,{responseTopic:m,publicKey:w}),this.client.auth.pairingTopics.set(m,{topic:m,pairingTopic:b})]),await this.client.core.relayer.subscribe(m,{transportType:i}),this.client.logger.info(`sending request to new pairing topic: ${b}`),d.length>0){const{namespace:I}=Ct(o[0]);let O=b2(I,"request",d);Fs(y)&&(O=E2(O,y.pop())),y.push(O)}const x=g&&g>xe.wc_sessionAuthenticate.req.ttl?g:xe.wc_sessionAuthenticate.req.ttl,_={authPayload:{type:h??"caip122",chains:o,statement:a,aud:c,domain:l,version:"1",nonce:u,iat:new Date().toISOString(),exp:f,nbf:p,resources:y},requester:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:fe(x)},T={eip155:{chains:o,methods:[...new Set(["personal_sign",...d])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:T,relays:[{protocol:"irn"}],pairingTopic:b,proposer:{publicKey:w,metadata:this.client.metadata},expiryTimestamp:fe(xe.wc_sessionPropose.req.ttl),id:ze()},{done:P,resolve:k,reject:U}=Sn(x,"Request expired"),N=ze(),S=J("session_connect",$.id),R=J("session_request",N),v=async({error:I,session:O})=>{this.events.off(R,D),I?U(I):O&&k({session:O})},E=async I=>{if(await this.deletePendingAuthRequest(N,{message:"fulfilled",code:0}),I.error){const K=te("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return I.error.code===K.code?void 0:(this.events.off(S,v),U(I.error.message))}await this.deleteProposal($.id),this.events.off(S,v);const{cacaos:O,responder:C}=I.result,L=[],V=[];for(const K of O){if(!await Nh({cacao:K,projectId:this.client.core.projectId}))return this.client.logger.error(K,"Signature verification failed"),U(te("SESSION_SETTLEMENT_FAILED","Signature verification failed"));const W=p2({cacao:K,request:_.authPayload});if(!W.valid)return this.client.logger.error(K,`Cacao does not match the request: ${W.reason}`),U(te("SESSION_SETTLEMENT_FAILED",`Cacao does not match the request: ${W.reason}`));const{p:G}=K,H=Fs(G.resources),Z=[ks(G.iss)],ae=Ls(G.iss);if(H){const ce=Lh(H),we=Fh(H);L.push(...ce),Z.push(...we)}for(const ce of Z)V.push(`${ce}:${ae}`)}const j=await this.client.core.crypto.generateSharedKey(w,C.publicKey);let q;L.length>0&&(q={topic:j,acknowledged:!0,self:{publicKey:w,metadata:this.client.metadata},peer:C,controller:C.publicKey,expiry:fe(Jn),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:b,namespaces:ef([...new Set(L)],[...new Set(V)]),transportType:i},await this.client.core.relayer.subscribe(j,{transportType:i}),await this.client.session.set(j,q),b&&await this.client.core.pairing.updateMetadata({topic:b,metadata:C.metadata}),q=this.client.session.get(j)),this.client.metadata.redirect?.linkMode&&C.metadata.redirect?.linkMode&&C.metadata.redirect?.universal&&r&&(this.client.core.addLinkModeSupportedApp(C.metadata.redirect.universal),this.client.session.update(j,{transportType:ee.link_mode})),k({auths:O,session:q})},D=I=>E(I).catch(O=>{this.client.logger.error(O,"Failed to process authenticate response"),U(te("SESSION_SETTLEMENT_FAILED",O?.message||"Failed to process authenticate response"))});this.events.once(S,v),this.events.once(R,D);let B;try{if(s){const I=Lt("wc_sessionAuthenticate",_,N);this.client.core.history.set(b,I);const O=await this.client.core.crypto.encode("",I,{type:On,encoding:pt});B=zs(r,b,O)}else await Promise.all([this.sendRequest({topic:b,method:"wc_sessionAuthenticate",params:_,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:N}),this.sendRequest({topic:b,method:"wc_sessionPropose",params:$,expiry:xe.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(I){throw this.events.off(S,v),this.events.off(R,D),I}return await this.setProposal($.id,$),await this.setAuthRequest(N,{request:{..._,verifyContext:{}},pairingTopic:b,transportType:i}),{uri:B??A,response:P}},this.approveSessionAuthenticate=async n=>{const{id:r,auths:s}=n,i=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Pn.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw i.setError(Mr.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw i.setError(Mr.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ee.relay;a===ee.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=Ms(c),h={type:Nt,receiverPublicKey:c,senderPublicKey:l},f=[],p=[];for(const y of s){if(!await Nh({cacao:y,projectId:this.client.core.projectId})){i.setError(Mr.invalid_cacao);const x=te("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:x,encodeOpts:h}),new Error(x.message)}i.addTrace(Pn.cacaos_verified);const{p:b}=y,A=Fs(b.resources),w=[ks(b.iss)],m=Ls(b.iss);if(A){const x=Lh(A),_=Fh(A);f.push(...x),w.push(..._)}for(const x of w)p.push(`${x}:${m}`)}const d=await this.client.core.crypto.generateSharedKey(l,c);i.addTrace(Pn.create_authenticated_session_topic);let g;if(f?.length>0){g={topic:d,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:fe(Jn),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ef([...new Set(f)],[...new Set(p)]),transportType:a},i.addTrace(Pn.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw i.setError(Mr.subscribe_authenticated_session_topic_failure),y}i.addTrace(Pn.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),i.addTrace(Pn.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}i.addTrace(Pn.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:s,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw i.setError(Mr.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:i.eventId}),{session:g}},this.rejectSessionAuthenticate=async n=>{this.isInitialized();const{id:r,reason:s}=n,i=this.getPendingAuthRequest(r);if(!i)throw new Error(`Could not find pending auth request with id ${r}`);i.transportType===ee.relay&&await this.confirmOnlineStateOrThrow();const o=i.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=Ms(o),l={type:Nt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:s,encodeOpts:l,rpcOpts:xe.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(i.requester.metadata,i.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)},this.formatAuthMessage=n=>{this.isInitialized();const{request:r,iss:s}=n;return Uh(r,s)},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)},this.cleanupDuplicatePairings=async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(i=>i.peerMetadata?.url&&i.peerMetadata?.url===n.peer.metadata.url&&i.topic&&i.topic!==r.topic);if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(i=>this.client.core.pairing.disconnect({topic:i.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}},this.deleteSession=async n=>{const{topic:r,expirerHasDeleted:s=!1,emitEvent:i=!0,id:o=0}=n,{self:a}=this.client.session.get(r);await this.client.core.relayer.unsubscribe(r),await this.client.session.delete(r,te("USER_DISCONNECTED")),this.addToRecentlyDeleted(r,"session"),this.client.core.crypto.keychain.has(a.publicKey)&&await this.client.core.crypto.deleteKeyPair(a.publicKey),this.client.core.crypto.keychain.has(r)&&await this.client.core.crypto.deleteSymKey(r),s||this.client.core.expirer.del(r),this.client.core.storage.removeItem(Nf).catch(c=>this.client.logger.warn(c)),r===this.sessionRequestQueue.queue[0]?.topic&&(this.sessionRequestQueue.state=mt.idle),await Promise.all(this.getPendingSessionRequests().filter(c=>c.topic===r).map(c=>this.deletePendingSessionRequest(c.id,te("USER_DISCONNECTED")))),i&&this.client.events.emit("session_delete",{id:o,topic:r})},this.deleteProposal=async(n,r)=>{if(r)try{const s=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(Bn.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,te("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")},this.deletePendingSessionRequest=async(n,r,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(i=>i.id!==n),s&&(this.sessionRequestQueue.state=mt.idle,this.client.events.emit("session_request_expire",{id:n}))},this.deletePendingAuthRequest=async(n,r,s=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),s?Promise.resolve():this.client.core.expirer.del(n)])},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}))},this.setProposal=async(n,r)=>{this.client.core.expirer.set(n,fe(xe.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)},this.setAuthRequest=async(n,r)=>{const{request:s,pairingTopic:i,transportType:o=ee.relay}=r;this.client.core.expirer.set(n,s.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:n,pairingTopic:i,verifyContext:s.verifyContext,transportType:o})},this.setPendingSessionRequest=async n=>{const{id:r,topic:s,params:i,verifyContext:o}=n,a=i.request.expiryTimestamp||fe(xe.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:s,params:i,verifyContext:o})},this.sendRequest=async n=>{const{topic:r,method:s,params:i,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=n,p=Lt(s,i,c);let d;const g=!!u;try{const A=g?pt:Ee;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(XI.includes(s)){const A=Ge(JSON.stringify(p)),w=Ge(d);y=await this.client.core.verify.register({id:w,decryptedId:A})}const b={...xe[s].req,...f};if(b.attestation=y,o&&(b.ttl=o),a&&(b.id=a),this.client.core.history.set(r,p),g){const A=zs(u,r,d);await global.Linking.openURL(A,this.client.name)}else b.tvf={...h,correlationId:p.id},l?(b.internal={...b.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(r,d,b)):this.client.core.relayer.publish(r,d,b).catch(A=>this.client.logger.error(A));return p.id},this.sendProposeSession=async n=>{const{proposal:r,publishOpts:s}=n,i=Lt("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,i);const o=await this.client.core.crypto.encode(r.pairingTopic,i,{encoding:Ee}),a=Ge(JSON.stringify(i)),c=Ge(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:{...s,publishMethod:"wc_proposeSession",attestation:l}})},this.sendApproveSession=async n=>{const{sessionTopic:r,pairingProposalResponse:s,proposal:i,sessionSettleRequest:o,publishOpts:a}=n,c=Ks(i.id,s),l=await this.client.core.crypto.encode(i.pairingTopic,c,{encoding:Ee}),u=Lt("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(r,u,{encoding:Ee});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:i.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:{...a,publishMethod:"wc_approveSession"}})},this.sendResult=async n=>{const{id:r,topic:s,result:i,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,l=Ks(r,i);let u;const h=c&&typeof global?.Linking<"u";try{const d=h?pt:Ee;u=await this.client.core.crypto.encode(s,l,{...a||{},encoding:d})}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),d}let f,p;try{f=await this.client.core.history.get(s,r);const d=f.request;try{p=this.getTVFParams(r,d.params,i)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${r}) failed`),d}if(h){const d=zs(c,s,u);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=xe[d].res;g.tvf={...p,correlationId:r},o?(g.internal={...g.internal,throwOnFailedPublish:!0},await this.client.core.relayer.publish(s,u,g)):this.client.core.relayer.publish(s,u,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(l)},this.sendError=async n=>{const{id:r,topic:s,error:i,encodeOpts:o,rpcOpts:a,appLink:c}=n,l=ua(r,i);let u;const h=c&&typeof global?.Linking<"u";try{const p=h?pt:Ee;u=await this.client.core.crypto.encode(s,l,{...o||{},encoding:p})}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${r}) failed`),p}if(h){const p=zs(c,s,u);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||xe[p].res;this.client.core.relayer.publish(s,u,d)}await this.client.core.history.resolve(l)},this.cleanup=async()=>{const n=[],r=[];this.client.session.getAll().forEach(s=>{let i=!1;cn(s.expiry)&&(i=!0),this.client.core.crypto.keychain.has(s.topic)||(i=!0),i&&n.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{cn(s.expiryTimestamp)&&r.push(s.id)}),await Promise.all([...n.map(s=>this.deleteSession({topic:s})),...r.map(s=>this.deleteProposal(s))])},this.onProviderMessageEvent=async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)},this.onRelayEventRequest=async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()},this.processRequestsQueue=async()=>{if(this.requestQueue.state===mt.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=mt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=mt.idle},this.processRequest=async n=>{const{topic:r,payload:s,attestation:i,transportType:o,encryptedId:a}=n,c=s.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:s,attestation:i,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,s);case"wc_sessionPing":return await this.onSessionPingRequest(r,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:s,attestation:i,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}},this.onRelayEventResponse=async n=>{const{topic:r,payload:s,transportType:i}=n,o=(await this.client.core.history.get(r,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,s,i);case"wc_sessionSettle":return this.onSessionSettleResponse(r,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,s);case"wc_sessionExtend":return this.onSessionExtendResponse(r,s);case"wc_sessionPing":return this.onSessionPingResponse(r,s);case"wc_sessionRequest":return this.onSessionRequestResponse(r,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}},this.onRelayEventUnknownPayload=n=>{const{topic:r}=n,{message:s}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)},this.shouldIgnorePairingRequest=n=>{const{topic:r,requestMethod:s}=n,i=this.expectedPairingMethodMap.get(r);return!i||i.includes(s)?!1:!!(i.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)},this.onSessionProposeRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o}=n,{params:a,id:c}=s;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l?.setError(Ft.proposal_listener_not_found)),this.isValidConnect({...s.params});const u=a.expiryTimestamp||fe(xe.wc_sessionPropose.req.ttl),h={id:c,pairingTopic:r,expiryTimestamp:u,attestation:i,encryptedId:o,...a};await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});l?.addTrace(wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:xe.wc_sessionPropose.autoReject}),this.client.logger.error(l)}},this.onSessionProposeResponse=async(n,r,s)=>{const{id:i}=r;if(gt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(i);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 l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(i,{sessionTopic:u,pairingTopic:n,proposalId:i,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:n})}else if(Ye(r)){await this.deleteProposal(i);const o=J("session_connect",i);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}},this.onSessionSettleRequest=async(n,r)=>{const{id:s,params:i}=r;try{this.isValidSessionSettleRequest(i);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=r.params,d=[...this.pendingSessions.values()].find(b=>b.sessionTopic===n);if(!d)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(d.proposalId),y={topic:n,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata},...u&&{sessionProperties:u},...h&&{scopedProperties:h},...f&&{sessionConfig:f},transportType:ee.relay,authentication:p?.authentication,walletPayResult:p?.walletPay};await this.client.session.set(y.topic,y),await this.setExpiry(y.topic,y.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:y.peer.metadata}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(y),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:y}),this.events.emit(J("session_connect",d.proposalId),{session:y})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}},this.onSessionSettleResponse=async(n,r)=>{const{id:s}=r;gt(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(J("session_approve",s),{})):Ye(r)&&(await this.deleteSession({topic:n,emitEvent:!1}),this.events.emit(J("session_approve",s),{error:r.error}))},this.onSessionUpdateRequest=async(n,r)=>{const{params:s,id:i}=r;try{const o=`${n}_session_update`,a=Pr.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.warn(`Discarding out of sync request - ${i}`),this.sendError({id:i,topic:n,error:te("INVALID_UPDATE_REQUEST")});return}await this.isValidUpdate({topic:n,...s});const c=this.client.session.get(n);if(c.peer.publicKey!==c.controller)throw te("UNAUTHORIZED_UPDATE_REQUEST");try{Pr.set(o,i),await this.client.session.update(n,{namespaces:s.namespaces}),await this.sendResult({id:i,topic:n,result:!0})}catch(l){throw Pr.delete(o),l}this.client.events.emit("session_update",{id:i,topic:n,params:s})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}},this.isRequestOutOfSync=(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3),this.onSessionUpdateResponse=(n,r)=>{const{id:s}=r,i=J("session_update",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_update",s),{}):Ye(r)&&this.events.emit(J("session_update",s),{error:r.error})},this.onSessionExtendRequest=async(n,r)=>{const{id:s}=r;try{await this.isValidExtend({topic:n}),await this.setExpiry(n,fe(Jn)),await this.sendResult({id:s,topic:n,result:!0}),this.client.events.emit("session_extend",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}},this.onSessionExtendResponse=(n,r)=>{const{id:s}=r,i=J("session_extend",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_extend",s),{}):Ye(r)&&this.events.emit(J("session_extend",s),{error:r.error})},this.onSessionPingRequest=async(n,r)=>{const{id:s}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:s,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:n})}catch(i){await this.sendError({id:s,topic:n,error:i}),this.client.logger.error(i)}},this.onSessionPingResponse=(n,r)=>{const{id:s}=r,i=J("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners 2176`);gt(r)?this.events.emit(J("session_ping",s),{}):Ye(r)&&this.events.emit(J("session_ping",s),{error:r.error})},500)},this.onSessionDeleteRequest=async(n,r)=>{const{id:s}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:te("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:s})}catch(i){this.client.logger.error(i)}},this.onSessionRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o,transportType:a}=n,{id:c,params:l}=s;try{await this.isValidRequest({topic:r,...l});const u=this.client.session.get(r),h=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(Lt("wc_sessionRequest",l,c))),encryptedId:o,metadata:u.peer.metadata,transportType:a}),f={id:c,topic:r,params:l,verifyContext:h};await this.setPendingSessionRequest(f),a===ee.link_mode&&u.peer.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(u.peer.metadata.redirect?.universal),this.client.signConfig?.disableRequestQueue?this.emitSessionRequest(f):(this.addSessionRequestToSessionRequestQueue(f),this.processSessionRequestQueue())}catch(u){await this.sendError({id:c,topic:r,error:u}),this.client.logger.error(u)}},this.onSessionRequestResponse=(n,r)=>{const{id:s}=r,i=J("session_request",s);if(this.events.listenerCount(i)===0)throw new Error(`emitting ${i} without any listeners`);gt(r)?this.events.emit(J("session_request",s),{result:r.result}):Ye(r)&&this.events.emit(J("session_request",s),{error:r.error})},this.onSessionEventRequest=async(n,r)=>{const{id:s,params:i}=r;try{const o=`${n}_session_event_${i.event.name}`,a=Pr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit({topic:n,...i}),this.client.events.emit("session_event",{id:s,topic:n,params:i}),Pr.set(o,s)}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}},this.onSessionAuthenticateResponse=(n,r)=>{const{id:s}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),gt(r)?this.events.emit(J("session_request",s),{result:r.result}):Ye(r)&&this.events.emit(J("session_request",s),{error:r.error})},this.onSessionAuthenticateRequest=async n=>{const{topic:r,payload:s,attestation:i,encryptedId:o,transportType:a}=n;try{const{requester:c,authPayload:l,expiryTimestamp:u}=s.params,h=await this.getVerifyContext({attestationId:i,hash:Ge(JSON.stringify(s)),encryptedId:o,metadata:c.metadata,transportType:a}),f={requester:c,pairingTopic:r,id:s.id,authPayload:l,verifyContext:h,expiryTimestamp:u};await this.setAuthRequest(s.id,{request:f,pairingTopic:r,transportType:a}),a===ee.link_mode&&c.metadata.redirect?.universal&&this.client.core.addLinkModeSupportedApp(c.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:r,params:s.params,id:s.id,verifyContext:h})}catch(c){this.client.logger.error(c);const l=s.params.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,a),f={type:Nt,receiverPublicKey:l,senderPublicKey:u};await this.sendError({id:s.id,topic:r,error:c,encodeOpts:f,rpcOpts:xe.wc_sessionAuthenticate.autoReject,appLink:h})}},this.addSessionRequestToSessionRequestQueue=n=>{this.sessionRequestQueue.queue.push(n)},this.cleanupAfterResponse=n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=mt.idle,this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay))},this.cleanupPendingSentRequestsForTopic=({topic:n,error:r})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(i=>i.topic===n&&i.request.method==="wc_sessionRequest").forEach(i=>{this.events.emit(J("session_request",i.request.id),{error:r})})},this.processSessionRequestQueue=()=>{if(this.sessionRequestQueue.state===mt.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)}},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=mt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)},this.cleanupInProgress=!1,this.cleanupOrphanedSubscriptions=async()=>{const n=this.client.core.relayer.subscriber.topics;if(n.length===0)return;const r=new Set(this.client.session.keys),s=new Set(this.client.core.pairing.pairings.keys),i=new Set([...this.pendingSessions.values()].map(a=>a.sessionTopic));let o;if(this.client.auth.authKeys.keys.includes(un)){const{responseTopic:a}=this.client.auth.authKeys.get(un);o=a}for(const a of n)if(!r.has(a)&&!s.has(a)&&!i.has(a)&&a!==o){this.client.logger.info(`Cleaning up orphaned subscriber topic: ${a}`);try{await this.client.core.relayer.subscriber.unsubscribe(a)}catch(c){this.client.logger.warn(c,`Failed to clean up orphaned subscription: ${a}`)}}},this.onPairingCreated=n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(s=>s.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:Lt("wc_sessionPropose",{...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})},this.isValidConnect=async n=>{if(!Le(n)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:s,optionalNamespaces:i,sessionProperties:o,scopedProperties:a,relays:c}=n;if(de(r)||await this.isValidPairingTopic(r),!rx(c)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(s&&!de(s)&&Rr(s)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(s,"requiredNamespaces")}if(i&&!de(i)&&Rr(i)!==0&&this.validateNamespaces(i,"optionalNamespaces"),o&&!de(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!de(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(s||{}).concat(Object.keys(i||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}},this.validateNamespaces=(n,r)=>{const s=nx(n,"connect()",r);if(s)throw new Error(s.message)},this.isValidApprove=async n=>{if(!Le(n))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:s,relayProtocol:i,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=ra(s,"approve()");if(l)throw new Error(l.message);const u=of(c.requiredNamespaces,s,"approve()");if(u)throw new Error(u.message);if(!oe(i,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${i}`);throw new Error(h)}if(o&&!de(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!de(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));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(", ")}`)}},this.isValidReject=async n=>{if(!Le(n)){const{message:i}=M("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(i)}const{id:r,reason:s}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!ix(s)){const{message:i}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(i)}},this.isValidSessionSettleRequest=n=>{if(!Le(n)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(l)}const{relay:r,controller:s,namespaces:i,expiry:o}=n;if(!rf(r)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=Z2(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=ra(i,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(cn(o)){const{message:l}=M("EXPIRED","onSessionSettleRequest()");throw new Error(l)}},this.isValidUpdate=async n=>{if(!Le(n)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:s}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const i=this.client.session.get(r),o=ra(s,"update()");if(o)throw new Error(o.message);const a=of(i.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)},this.isValidExtend=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(s)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)},this.isValidRequest=async n=>{if(!Le(n)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:s,chainId:i,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!sf(a,i)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${i}`);throw new Error(c)}if(!ox(s)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!lx(a,i,s.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)},this.isValidRespond=async n=>{if(!Le(n)){const{message:o}=M("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:r,response:s}=n;try{await this.isValidSessionTopic(r)}catch(o){throw n?.response?.id&&this.cleanupAfterResponse(n),o}if(!ax(s)){const{message:o}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}const i=this.client.pendingRequest.get(s.id);if(i.topic!==r){const{message:o}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${i.topic}, received topic: ${r}`);throw new Error(o)}},this.isValidPing=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidEmit=async n=>{if(!Le(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:s,chainId:i}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!sf(o,i)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${i}`);throw new Error(a)}if(!cx(s)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!ux(o,i,s.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}},this.isValidDisconnect=async n=>{if(!Le(n)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(s)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)},this.isValidAuthenticate=n=>{const{chains:r,uri:s,domain:i,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!oe(s,!1))throw new Error("uri is required parameter");if(!oe(i,!1))throw new Error("domain is required parameter");if(!oe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Ct(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Ct(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")},this.getVerifyContext=async n=>{const{attestationId:r,hash:s,encryptedId:i,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Fr,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ee.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:s,encryptedId:i,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c},this.validateSessionProps=(n,r)=>{Object.values(n).forEach((s,i)=>{if(s==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${s} for key ${Object.keys(n)[i]}`);throw new Error(o)}})},this.getPendingAuthRequest=n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0},this.addToRecentlyDeleted=(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const i=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=i)break;this.recentlyDeletedMap.delete(o)}}},this.checkRecentlyDeleted=n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:s}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(s)}},this.isLinkModeEnabled=(n,r)=>!n||r!==ee.link_mode?!1:this.client.metadata?.redirect?.linkMode===!0&&this.client.metadata?.redirect?.universal!==void 0&&this.client.metadata?.redirect?.universal!==""&&n?.redirect?.universal!==void 0&&n?.redirect?.universal!==""&&n?.redirect?.linkMode===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof global?.Linking<"u",this.getAppLinkIfEnabled=(n,r)=>this.isLinkModeEnabled(n,r)?n?.redirect?.universal:void 0,this.handleLinkModeMessage=({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=Ah(n,"topic")||"",s=decodeURIComponent(Ah(n,"wc_ev")||""),i=this.client.session.keys.includes(r);i&&this.client.session.update(r,{transportType:ee.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:s,sessionExists:i})},this.registerLinkModeListeners=async()=>{if(Ns()||an()&&this.client.metadata.redirect?.linkMode){const n=global?.Linking;if(typeof n<"u"){n.addEventListener("url",this.handleLinkModeMessage,this.client.name);const r=await n.getInitialURL();r&&setTimeout(()=>{this.handleLinkModeMessage({url:r})},50)}}},this.getTVFApproveParams=n=>{try{const r=Xh(n.namespaces),s=L2(n.namespaces),i=F2(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:s,approvedEvents:i,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}},this.getTVFParams=(n,r,s)=>{if(!r.request?.method)return{};const i={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const o=this.extractTxHashesFromResult(r.request,s);i.txHashes=o,i.contractAddresses=this.isValidContractData(r.request.params)?[r.request.params?.[0]?.to]:[]}catch(o){this.client.logger.warn(o,"Error getting TVF params")}return i},this.isValidContractData=n=>{if(!n)return!1;try{const r=n?.data||n?.[0]?.data;if(!r.startsWith("0x"))return!1;const s=r.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1},this.extractTxHashesFromResult=(n,r)=>{try{if(!r)return[];const s=n.method,i=YI[s];if(s==="sui_signTransaction")return[e2(r.transactionBytes)];if(s==="near_signTransaction")return[$h(r)];if(s==="near_signTransactions")return r.map(a=>$h(a));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[r.tx_json?.hash];if(s==="polkadot_signTransaction")return[Tx({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Xn(r)?r.map(a=>Rh(a)):[Rh(r)];if(s==="cosmos_signDirect")return[n2(r)];if(s==="stellar_signXDR")return[c2(r.signedXDR,n.params?.chain)];if(s==="wallet_sendCalls")return l2(r);if(s==="canton_prepareSignExecute")return Rx(n.params,r);if(typeof r=="string")return[r];const o=r[i.key];if(Xn(o))return s==="solana_signAllTransactions"?o.map(a=>QE(a)):o;if(typeof o=="string")return[o]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]}}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,s]of Object.entries(n))for(const i of s)try{await this.onProviderMessageEvent({topic:r,message:i,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${i}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(se.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:s,transportType:i}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(un)?this.client.auth.authKeys.get(un):{publicKey:void 0};try{try{if(i!==ee.link_mode&&this.client.core.crypto.getPayloadType(r,pt)===On){this.client.logger.warn(`onRelayMessage() -> non-link mode TYPE_2 payload ignored: ${r}`);return}}catch{}const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:i===ee.link_mode?pt:Ee});ha(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:s,transportType:i,encryptedId:Ge(r)})):Hs(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:i}),this.client.core.history.delete(n,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:i})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a?.message)}}registerExpirerEvents(){this.client.core.expirer.on(Xe.expired,async e=>{const{topic:n,id:r}=Dh(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);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}))})}registerSubscriptionCleanup(){this.client.core.heartbeat.on("heartbeat_pulse",async()=>{if(!this.cleanupInProgress){this.cleanupInProgress=!0;try{await this.cleanupOrphanedSubscriptions()}catch(e){this.client.logger.warn(e)}finally{this.cleanupInProgress=!1}}})}registerPairingEvents(){this.client.core.pairing.events.on(Rn.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Rn.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!oe(e,!1)){const{message:n}=M("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}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!oe(e,!1)){const{message:n}=M("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}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=M("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=M("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(oe(e,!1)){const{message:n}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!sx(e)){const{message:n}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(cn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=M("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!dx(e,wa)){const{message:n}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${wa.min} and ${wa.max}`);throw new Error(n)}}}class sS extends Cn{constructor(e,n){super(e,n,HI,ga),this.core=e,this.logger=n}}class iS extends Cn{constructor(e,n){super(e,n,WI,ga),this.core=e,this.logger=n}}class oS extends Cn{constructor(e,n){super(e,n,ZI,ga,r=>r.id),this.core=e,this.logger=n}}class aS extends Cn{constructor(e,n){super(e,n,eS,Gs,()=>un),this.core=e,this.logger=n}}class cS extends Cn{constructor(e,n){super(e,n,tS,Gs),this.core=e,this.logger=n}}class lS extends Cn{constructor(e,n){super(e,n,nS,Gs,r=>r.id),this.core=e,this.logger=n}}class uS{constructor(e,n){this.core=e,this.logger=n,this.authKeys=new aS(this.core,this.logger),this.pairingTopics=new cS(this.core,this.logger),this.requests=new lS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}const hS=class Zf extends gg{constructor(e){super(e),this.protocol=Bf,this.version=Pf,this.name=ya.name,this.events=new Je.EventEmitter,this.on=(r,s)=>this.events.on(r,s),this.once=(r,s)=>this.events.once(r,s),this.off=(r,s)=>this.events.off(r,s),this.removeListener=(r,s)=>this.events.removeListener(r,s),this.removeAllListeners=r=>this.events.removeAllListeners(r),this.connect=async r=>{try{return await this.engine.connect(r)}catch(s){throw this.logger.error(s.message),s}},this.pair=async r=>{try{return await this.engine.pair(r)}catch(s){throw this.logger.error(s.message),s}},this.approve=async r=>{try{return await this.engine.approve(r)}catch(s){throw this.logger.error(s.message),s}},this.reject=async r=>{try{return await this.engine.reject(r)}catch(s){throw this.logger.error(s.message),s}},this.update=async r=>{try{return await this.engine.update(r)}catch(s){throw this.logger.error(s.message),s}},this.extend=async r=>{try{return await this.engine.extend(r)}catch(s){throw this.logger.error(s.message),s}},this.request=async r=>{try{return await this.engine.request(r)}catch(s){throw this.logger.error(s.message),s}},this.respond=async r=>{try{return await this.engine.respond(r)}catch(s){throw this.logger.error(s.message),s}},this.ping=async r=>{try{return await this.engine.ping(r)}catch(s){throw this.logger.error(s.message),s}},this.emit=async r=>{try{return await this.engine.emit(r)}catch(s){throw this.logger.error(s.message),s}},this.disconnect=async r=>{try{return await this.engine.disconnect(r)}catch(s){throw this.logger.error(s.message),s}},this.find=r=>{try{return this.engine.find(r)}catch(s){throw this.logger.error(s.message),s}},this.getPendingSessionRequests=()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}},this.authenticate=async(r,s)=>{try{return console.warn("[WalletConnect] `authenticate` is deprecated and will be removed in a future release. Use `connect()`'s `authentication` instead to establish an authenticated session."),await this.engine.authenticate(r,s)}catch(i){throw this.logger.error(i.message),i}},this.formatAuthMessage=r=>{try{return this.engine.formatAuthMessage(r)}catch(s){throw this.logger.error(s.message),s}},this.approveSessionAuthenticate=async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}},this.rejectSessionAuthenticate=async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(s){throw this.logger.error(s.message),s}},this.name=e?.name||ya.name,this.metadata=RE(e?.metadata),this.signConfig=e?.signConfig;const n=lf({logger:e?.logger||ya.logger,name:this.name});this.logger=n,this.core=e?.core||new KI(e),this.session=new iS(this.core,this.logger),this.proposal=new sS(this.core,this.logger),this.pendingRequest=new oS(this.core,this.logger),this.engine=new rS(this),this.auth=new uS(this.core,this.logger)}static async init(e){const n=new Zf(e);return await n.initialize(),n}get context(){return Be(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}}};class kf{constructor(e){this.opts=e}}class Lf{constructor(e){this.client=e}}const Ff=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:s,standard:i,address:o}=n;if(!r||!s||!i||!o||!Br(r?.chainId))return!1;const{namespace:a}=Ct(r.chainId),c=e.find(l=>l.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(l=>l.toLowerCase()).includes(i?.toLowerCase()))throw new Error(`Unsupported token standard: ${i} for namespace: ${a}`);return!0},fS=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:s,recipient:i}=n;return!(!r||!s||!i||!Ff({supportedNamespaces:e,token:r}))},Mf=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};class dS extends Lf{constructor(e){super(e),this.tokens=[],this.supportedNamespaces=Ia,this.paymentIntents={},this.transactions={},this.paymentsSendingInProgress={},this.manualControl={},this.init=async()=>{this.signClient=await hS.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:this.client.opts.storageOptions?.databaseName||Js.database},customStoragePrefix:Js.customStoragePrefix,logger:this.client.opts.loggerOptions?.signLevel||Qs}),this.signClient.events.on("session_delete",({topic:n})=>{this.cleanup({sessionTopic:n}),this.emit("disconnected",{sessionTopic:n})});try{this.logger.debug("Fetching supported namespaces/networks");const n=await this.fetchRpcRequest({payload:JSON.stringify({id:ze(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:n.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=n.result.namespaces}catch(n){this.logger.error(n,"Failed to fetch supported namespaces/networks")}},this.setTokens=async n=>{const{tokens:r}=n;this.logger.debug({tokens:r},"Setting tokens"),r.forEach(s=>{if(!Ff({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=r,s()}),this.logger.debug({tokens:r},"Tokens set")},this.createPaymentIntent=async n=>{const{paymentIntents:r,sessionTopic:s,userId:i}=n;this.logger.debug({paymentIntents:r,userId:i},"Creating payment intent");const o=n.manualControl||!1;if(r.length===0)throw new Error("No payment intents provided");for(const h of r)if(!fS({paymentIntent:h,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(h)}`);if(this.logger.debug({paymentIntents:r,userId:i},"Payment intent validation success"),s){this.manualControl[s]=o;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:r,userId:i}),this.validateApprovedNamespacesWithPaymentIntents(s),o||await this.sendPaymentsToWallet({sessionTopic:s,userId:i});return}catch(h){this.logger.error(h),await this.disconnect({sessionTopic:s})}}const a=this.composeNamespacesFromPaymentIntents(r),{uri:c,approval:l}=await this.signClient.connect({optionalNamespaces:a});if(this.logger.debug({uri:c,userId:i},"Connected to the WalletConnect network"),!c)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=Mf(l);if(this.emit("await_approval",{approval:u,paymentIntents:r,userId:i,manualControl:o}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:c,userId:i}),this.logger.debug({uri:c,userId:i},"Emitted qr_ready event"),o){const h=await u();this.manualControl[h.topic]=o}},this.restart=async n=>{this.logger.debug({params:n},"Restarting");const{reinit:r,sessionTopic:s,userId:i}=n||{};if(r){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const o=this.getSessionTopic(s),a=this.manualControl[o],c=this.paymentIntents[o];if(!c||!c?.length)throw new Error("No payment intents found for session topic: "+o);await this.createPaymentIntent({paymentIntents:c,manualControl:a,userId:i,sessionTopic:o}),this.logger.debug({paymentIntents:c,userId:i},"Restarted: Created payment intent flow from the beginning")},this.connect=async n=>{const{userId:r}=n,s=!0,i=this.composeNamespacesFromTokens(),{uri:o,approval:a}=await this.signClient.connect({optionalNamespaces:i});if(this.logger.debug({uri:o},"Connected to the WalletConnect network"),!o)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:r}),new Error("Failed to connect to the WalletConnect network");const c=Mf(a);this.emit("await_approval",{approval:c,manualControl:s,paymentIntents:[],userId:r}),this.logger.debug({userId:r},"Emitted await_approval event"),this.emit("qr_ready",{uri:o,userId:r}),this.logger.debug({uri:o,userId:r},"Emitted qr_ready event");const l=await c();return this.manualControl[l.topic]=s,l},this.emit=(n,r)=>(this.logger.debug({event:n,args:r},"Emit"),this.client.events.emit(n,r)),this.on=(n,r)=>(this.logger.debug({event:n,listener:r},"On"),this.client.events.on(n,r)),this.once=(n,r)=>(this.logger.debug({event:n,listener:r},"Once"),this.client.events.once(n,r)),this.off=(n,r)=>(this.logger.debug({event:n,listener:r},"Off"),this.client.events.off(n,r)),this.removeListener=(n,r)=>(this.logger.debug({event:n,listener:r},"Remove listener"),this.client.events.removeListener(n,r)),this.prepareTransactionsFromPaymentIntents=async n=>{const{sessionTopic:r,userId:s}=n,i=this.getSessionTopic(r),o=this.paymentIntents[i];if(!o)throw new Error("No payment intents found for session topic: "+i);const a=this.signClient.session.get(i);this.logger.debug({sessionTopic:i,userId:s},"Preparing transactions from payment intents");const c=[];for(const h of o){const{token:f,amount:p,recipient:d}=h,{namespace:g}=Ct(f.network.chainId),y=a.namespaces?.[g]?.accounts?.find(b=>b.includes(`${f.network.chainId}:`));if(!y)throw new Error(`Address not found in session for chain id: ${f.network.chainId}, approved addresses: ${a.namespaces?.[g]?.accounts?.join(", ")}`);c.push({asset:`${f.network.chainId}/${f.standard.toLowerCase()}:${f.address}`,recipient:d,amount:p,sender:y})}this.logger.debug({sessionTopic:a.topic,transactions:c,userId:s},"Prepared transactions from payment intents");const l={id:ze(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:c}};this.logger.debug({payload:l,userId:s},"Fetching wc_pos_buildTransactions");const u=await this.fetchRpcRequest({payload:JSON.stringify(l),userId:s});this.logger.debug({response:u,userId:s},"Received wc_pos_buildTransactions"),this.transactions[a.topic]=u.result.transactions,this.logger.debug({transactions:this.transactions[a.topic],userId:s},"Payment intent to transactions map set")},this.sendPaymentsToWallet=async(n={})=>{const{sessionTopic:r,userId:s}=n,i=this.getSessionTopic(r);if(!i)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[i])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[i]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:i,userId:s}),await this.sendTransactionsToWallet({sessionTopic:i,userId:s})}catch(o){throw this.logger.error(o,"Error while sending payments to wallet"),this.paymentsSendingInProgress[i]=!1,o}this.paymentsSendingInProgress[i]=!1},this.sendTransactionsToWallet=async n=>{const{sessionTopic:r,userId:s}=n,i=this.transactions[r],o=this.paymentIntents[r];if(!i||!o)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(i.length!==o.length)throw new Error(`Mismatch between transactions (${i.length}) and payment intents (${o.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:i,sessionTopic:r,userId:s},"Sending transactions to wallet");for(let a=0;a<i.length;a++){const c=i[a],l=o[a];try{this.emit("payment_requested",{paymentIntent:l,transaction:c,sessionTopic:r,userId:s}),this.logger.debug({transactionId:c.id,userId:s},"Emitted payment_requested event");let u;try{u=await this.signClient.request({topic:r,request:{method:c.method,params:c.params},chainId:c.chainId}),this.logger.debug({transactionId:c.id,result:u,userId:s},"Wallet responded to payment request")}catch(h){throw this.logger.error(h,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:h?.message,code:4001},paymentIntent:l,sessionTopic:r,userId:s}),h}this.emit("payment_broadcasted",{paymentIntent:l,transaction:c,result:u,sessionTopic:r,userId:s}),this.logger.debug({transactionId:c.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:c,result:u,sessionTopic:r,userId:s}),await new Promise(h=>setTimeout(h,1e3))}catch(u){this.logger.error(u,"Error while awaiting payment confirmed")}}this.manualControl[r]!==!0&&await this.disconnect({sessionTopic:r})},this.awaitPaymentConfirmed=async n=>{const{transaction:r,result:s,sessionTopic:i,userId:o}=n;try{this.logger.debug({transactionId:r.id,result:s},"Awaiting payment confirmed");const a={id:ze(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:r.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let c=0,l;for(;!l;){if(c>=_a)throw new Error(`Transaction status not found for id: ${r.id}`);c++;const u=await this.fetchRpcRequest({payload:JSON.stringify(a),userId:o});if(this.logger.debug({transactionId:r.id,response:u},"Received wc_pos_checkTransaction"),u.result.status==="CONFIRMED"){this.logger.debug({response:u,userId:o},"Transaction status confirmed"),this.emit("payment_successful",{transaction:r,result:s,sessionTopic:i,userId:o}),l=u.result;break}else if(u.result.status==="FAILED"){this.logger.debug({response:u},"Transaction failed"),this.emit("payment_failed",{error:{message:u.result.error,code:4001},transaction:s,sessionTopic:i,userId:o}),l=u.result;break}else u.result.status==="PENDING"&&(this.logger.debug({response:u,userId:o},"Transaction pending"),await new Promise(h=>setTimeout(h,u.result.checkIn||1e3)))}}catch(a){this.logger.error(a,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:a?.message,code:4001},transaction:r,sessionTopic:i,userId:o})}},this.setupEventHandlers=()=>{this.on("await_approval",async({approval:n,paymentIntents:r,userId:s,manualControl:i})=>{try{this.logger.debug("On await_approval");const o=await n();this.setPaymentIntents({sessionTopic:o.topic,paymentIntents:r}),await this.onSessionConnected({session:o,userId:s,manualControl:i})}catch(o){this.logger.error(o,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:o?.message,code:4001},userId:s})}})},this.onSessionConnected=async n=>{const{session:r,userId:s,manualControl:i}=n;this.logger.debug({sessionTopic:r.topic,userId:s},"On session connected"),this.emit("connected",{session:r,userId:s}),await this.signClient.session.update(r.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:r.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:r.topic,userId:s},"Emitted connected event"),i!==!0&&await this.sendPaymentsToWallet({sessionTopic:r.topic,userId:s})},this.disconnect=async(n={})=>{try{const{sessionTopic:r}=n,s=this.getSessionTopic(r);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(r){this.logger.error(r,"Error while disconnecting")}},this.fetchRpcRequest=async n=>{const{payload:r,userId:s}=n;this.logger.debug({url:this.getRpcUrl(),payload:r,userId:s},"Fetching RPC request");const i=await fetch(this.getRpcUrl(),{method:"POST",body:r});let o;try{o=await i.json()}catch(a){this.logger.error(a,"Error while getting json data from RPC response")}if(this.logger.debug({data:o},"Received RPC request response"),!i.ok||!o||o?.error){const a=o?.error?.code||-18900,c=ei?.[a]?`${ei?.[a]}: ${o?.error?.message}`:o?.error?.message||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:c,code:a},transaction:"",sessionTopic:this.client.session?.topic||"",userId:s}),new Error(c)}return o},this.validateApprovedNamespacesWithPaymentIntents=n=>{this.validateSessionTopic(n);const r=this.signClient.session.get(n),s=this.paymentIntents?.[n];if(!r||!s)throw new Error("No session or payment intents found");for(const i of s){const{token:o}=i,{namespace:a}=Ct(o.network.chainId);if(!r.namespaces?.[a]?.accounts?.find(c=>c.includes(`${o.network.chainId}:`)))throw new Error(`Address not found in session for chain id: ${o.network.chainId}, approved addresses: ${r.namespaces?.[a]?.accounts?.join(", ")}`)}},this.setPaymentIntents=n=>{const{sessionTopic:r,paymentIntents:s,userId:i}=n;this.paymentIntents[r]=s,this.logger.debug({paymentIntents:s,userId:i},"Payment intents set")},this.cleanup=(n={})=>{const{sessionTopic:r}=n;r&&(delete this.paymentIntents[r],delete this.transactions[r],delete this.manualControl[r],delete this.paymentsSendingInProgress[r],this.logger.debug({sessionTopic:r},"Cleaned up payment intents and transactions"))},this.getRpcUrl=()=>Sa({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId}),this.validateSessionTopic=n=>{if(n)try{this.signClient.session.get(n)}catch(r){throw this.logger.error(r,`No session found for topic: ${n}`),new Error(`No session found for topic: ${n}`)}},this.getSessionTopic=n=>{if(!n&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const r=n||this.client.session?.topic;if(!r)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(r),r},this.signClient={},this.logger=Bp({name:this.client.name,level:this.client.opts.loggerOptions?.posLevel||Qs}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{const{network:s}=r,{namespace:i}=Ct(s.chainId),o=this.supportedNamespaces.find(a=>a.name===i);if(!o)throw new Error(`Namespace not supported: ${i}`);n[i]={methods:o.methods,chains:[...n[i]?.chains||[],s.chainId],events:o.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{const{token:{network:s}}=r,{namespace:i}=Ct(s.chainId),o=this.supportedNamespaces.find(a=>a.name===i);if(!o)throw new Error(`Namespace not supported: ${i}`);n[i]={methods:o.methods,chains:[...n[i]?.chains||[],s.chainId],events:o.events}}),this.logger.debug({namespaces:n},"Composed namespaces"),n}}let qf=class Xf extends kf{constructor(e){super(e),this.events=new Zs,this.on=(n,r)=>this.engine.on(n,r),this.once=(n,r)=>this.engine.once(n,r),this.off=(n,r)=>this.engine.off(n,r),this.removeListener=(n,r)=>this.engine.removeListener(n,r),this.setTokens=async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.createPaymentIntent=async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.restart=async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.sendPaymentsToWallet=async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.disconnect=async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.connect=async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}},this.metadata=e.metadata,this.name=Xs,this.engine=new dS(this)}static async init(e){const n=new Xf(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}};const pS=qf;ie.CLIENT_CONTEXT=Xs,ie.CLIENT_STORAGE_OPTIONS=Js,ie.CLIENT_STORAGE_PREFIX=td,ie.DEFAULT_LOGGER_LEVEL=Qs,ie.DEFAULT_NAMESPACES=Ia,ie.IPOSClient=kf,ie.IPOSClientEngine=Lf,ie.MAX_TRANSACTION_STATUS_CHECKS=_a,ie.POSClient=pS,ie.POS_CLIENT_VERSION=xa,ie.PROTOCOL=Ea,ie.PROTOCOL_VERSION=ed,ie.RPC_ERROR_CODES=ei,ie.RPC_URL=Sa,ie.default=qf,Object.defineProperty(ie,"__esModule",{value:!0})});
40
40
  //# sourceMappingURL=index.umd.js.map