@walletconnect/pos-client 0.0.0-canary.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,42 @@
1
+ (function(Ve,kt){typeof exports=="object"&&typeof module<"u"?kt(exports):typeof define=="function"&&define.amd?define(["exports"],kt):(Ve=typeof globalThis<"u"?globalThis:Ve||self,kt(Ve["@walletconnect/pos-client"]={}))})(this,function(Ve){"use strict";var kt=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function mu(t){var e=t.default;if(typeof e=="function"){var n=function(){return e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var He={exports:{}},wr=typeof Reflect=="object"?Reflect:null,vu=wr&&typeof wr.apply=="function"?wr.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},Qi;wr&&typeof wr.ownKeys=="function"?Qi=wr.ownKeys:Object.getOwnPropertySymbols?Qi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Qi=function(e){return Object.getOwnPropertyNames(e)};function P0(t){console&&console.warn&&console.warn(t)}var Eu=Number.isNaN||function(e){return e!==e};function oe(){oe.init.call(this)}He.exports=oe,He.exports.once=U0,oe.EventEmitter=oe,oe.prototype._events=void 0,oe.prototype._eventsCount=0,oe.prototype._maxListeners=void 0;var _u=10;function es(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(oe,"defaultMaxListeners",{enumerable:!0,get:function(){return _u},set:function(t){if(typeof t!="number"||t<0||Eu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");_u=t}}),oe.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},oe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Eu(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function xu(t){return t._maxListeners===void 0?oe.defaultMaxListeners:t._maxListeners}oe.prototype.getMaxListeners=function(){return xu(this)},oe.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")vu(c,this,n);else for(var u=c.length,l=Ou(c,u),r=0;r<u;++r)vu(l[r],this,n);return!0};function Iu(t,e,n,r){var i,s,o;if(es(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),o=s[e]),o===void 0)o=s[e]=n,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=xu(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,P0(a)}return t}oe.prototype.addListener=function(e,n){return Iu(this,e,n,!1)},oe.prototype.on=oe.prototype.addListener,oe.prototype.prependListener=function(e,n){return Iu(this,e,n,!0)};function R0(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function Su(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=R0.bind(r);return i.listener=n,r.wrapFn=i,i}oe.prototype.once=function(e,n){return es(n),this.on(e,Su(this,e,n)),this},oe.prototype.prependOnceListener=function(e,n){return es(n),this.prependListener(e,Su(this,e,n)),this},oe.prototype.removeListener=function(e,n){var r,i,s,o,a;if(es(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(s=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,s=o;break}if(s<0)return this;s===0?r.shift():C0(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},oe.prototype.off=oe.prototype.removeListener,oe.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var s=Object.keys(r),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function Du(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?N0(i):Ou(i,i.length)}oe.prototype.listeners=function(e){return Du(this,e,!0)},oe.prototype.rawListeners=function(e){return Du(this,e,!1)},oe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):Au.call(t,e)},oe.prototype.listenerCount=Au;function Au(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}oe.prototype.eventNames=function(){return this._eventsCount>0?Qi(this._events):[]};function Ou(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function C0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function N0(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function U0(t,e){return new Promise(function(n,r){function i(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}$u(t,e,s,{once:!0}),e!=="error"&&F0(t,i,{once:!0})})}function F0(t,e,n){typeof t.on=="function"&&$u(t,"error",e,n)}function $u(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const Bu="wc",k0=2,Io="POSClient",L0=`${Bu}@2:${Io}:`,Tu={database:":memory:"},Pu="1.0.0";var M={};/*! *****************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */var So=function(t,e){return So=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},So(t,e)};function M0(t,e){So(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Do=function(){return Do=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Do.apply(this,arguments)};function j0(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function q0(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function z0(t,e){return function(n,r){e(n,r,t)}}function K0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function V0(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function H0(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function W0(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function G0(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Ao(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Ru(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function Z0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Ru(arguments[e]));return t}function Y0(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Xr(t){return this instanceof Xr?(this.v=t,this):new Xr(t)}function X0(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(r[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof Xr?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function J0(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Xr(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function Q0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Ao=="function"?Ao(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function ey(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ty(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 ny(t){return t&&t.__esModule?t:{default:t}}function ry(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function iy(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 sy=Object.freeze({__proto__:null,__extends:M0,get __assign(){return Do},__rest:j0,__decorate:q0,__param:z0,__metadata:K0,__awaiter:V0,__generator:H0,__createBinding:W0,__exportStar:G0,__values:Ao,__read:Ru,__spread:Z0,__spreadArrays:Y0,__await:Xr,__asyncGenerator:X0,__asyncDelegator:J0,__asyncValues:Q0,__makeTemplateObject:ey,__importStar:ty,__importDefault:ny,__classPrivateFieldGet:ry,__classPrivateFieldSet:iy}),ts=mu(sy),Oo={},Jr={},Cu;function oy(){if(Cu)return Jr;Cu=1,Object.defineProperty(Jr,"__esModule",{value:!0}),Jr.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return Jr.delay=t,Jr}var zn={},$o={},Kn={},Nu;function ay(){return Nu||(Nu=1,Object.defineProperty(Kn,"__esModule",{value:!0}),Kn.ONE_THOUSAND=Kn.ONE_HUNDRED=void 0,Kn.ONE_HUNDRED=100,Kn.ONE_THOUSAND=1e3),Kn}var Bo={},Uu;function cy(){return Uu||(Uu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(Bo)),Bo}var Fu;function ku(){return Fu||(Fu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(ay(),t),e.__exportStar(cy(),t)}($o)),$o}var Lu;function uy(){if(Lu)return zn;Lu=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.fromMiliseconds=zn.toMiliseconds=void 0;const t=ku();function e(r){return r*t.ONE_THOUSAND}zn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return zn.fromMiliseconds=n,zn}var Mu;function ly(){return Mu||(Mu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(oy(),t),e.__exportStar(uy(),t)}(Oo)),Oo}var br={},ju;function hy(){if(ju)return br;ju=1,Object.defineProperty(br,"__esModule",{value:!0}),br.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const i=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:i})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return br.Watch=t,br.default=t,br}var To={},Qr={},qu;function fy(){if(qu)return Qr;qu=1,Object.defineProperty(Qr,"__esModule",{value:!0}),Qr.IWatch=void 0;class t{}return Qr.IWatch=t,Qr}var zu;function dy(){return zu||(zu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),ts.__exportStar(fy(),t)}(To)),To}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=ts;e.__exportStar(ly(),t),e.__exportStar(hy(),t),e.__exportStar(dy(),t),e.__exportStar(ku(),t)})(M);class Vn{}class py extends Vn{constructor(e){super()}}const Ku=M.FIVE_SECONDS,Hn={pulse:"heartbeat_pulse"};class Po extends py{constructor(e){super(e),this.events=new He.exports.EventEmitter,this.interval=Ku,this.interval=e?.interval||Ku}static async init(e){const n=new Po(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(Hn.pulse)}}const gy=/"(?:_|\\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*:/,yy=/"(?: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*:/,wy=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function by(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){my(t);return}return e}function my(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function ns(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const n=t.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!wy.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(gy.test(t)||yy.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,by)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function vy(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return vy(t(...e))}catch(n){return Promise.reject(n)}}function Ey(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function _y(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function rs(t){if(Ey(t))return String(t);if(_y(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return rs(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ro="base64:";function xy(t){return typeof t=="string"?t:Ro+Dy(t)}function Iy(t){return typeof t!="string"||!t.startsWith(Ro)?t:Sy(t.slice(Ro.length))}function Sy(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Dy(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Qe(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Ay(...t){return Qe(t.join(":"))}function is(t){return t=Qe(t),t?t+":":""}function Oy(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 $y(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function x$(t){return t}const By="memory",Ty=()=>{const t=new Map;return{name:By,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 Py(t={}){const e={mounts:{"":t.driver||Ty()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},r=(u,l)=>e.mountpoints.filter(f=>f.startsWith(u)||l&&u.startsWith(f)).map(f=>({relativeBase:u.length>f.length?u.slice(f.length):void 0,mountpoint:f,driver:e.mounts[f]})),i=(u,l)=>{if(e.watching){l=Qe(l);for(const f of e.watchListeners)f(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await Vu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,f)=>{const h=new Map,d=p=>{let g=h.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},h.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",y=Qe(g?p:p.key),I=g?void 0:p.value,D=g||!p.options?l:{...l,...p.options},E=n(y);d(E).items.push({key:y,value:I,relativeKey:E.relativeKey,options:D})}return Promise.all([...h.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return xe(h.hasItem,f,l)},getItem(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return xe(h.getItem,f,l).then(d=>ns(d))},getItems(u,l={}){return a(u,l,f=>f.driver.getItems?xe(f.driver.getItems,f.items.map(h=>({key:h.relativeKey,options:h.options})),l).then(h=>h.map(d=>({key:Ay(f.base,d.key),value:ns(d.value)}))):Promise.all(f.items.map(h=>xe(f.driver.getItem,h.relativeKey,h.options).then(d=>({key:h.key,value:ns(d)})))))},getItemRaw(u,l={}){u=Qe(u);const{relativeKey:f,driver:h}=n(u);return h.getItemRaw?xe(h.getItemRaw,f,l):xe(h.getItem,f,l).then(d=>Iy(d))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=Qe(u);const{relativeKey:h,driver:d}=n(u);d.setItem&&(await xe(d.setItem,h,rs(l),f),d.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return xe(f.driver.setItems,f.items.map(h=>({key:h.relativeKey,value:rs(h.value),options:h.options})),l);f.driver.setItem&&await Promise.all(f.items.map(h=>xe(f.driver.setItem,h.relativeKey,rs(h.value),h.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=Qe(u);const{relativeKey:h,driver:d}=n(u);if(d.setItemRaw)await xe(d.setItemRaw,h,l,f);else if(d.setItem)await xe(d.setItem,h,xy(l),f);else return;d.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Qe(u);const{relativeKey:f,driver:h}=n(u);h.removeItem&&(await xe(h.removeItem,f,l),(l.removeMeta||l.removeMata)&&await xe(h.removeItem,f+"$",l),h.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Qe(u);const{relativeKey:f,driver:h}=n(u),d=Object.create(null);if(h.getMeta&&Object.assign(d,await xe(h.getMeta,f,l)),!l.nativeOnly){const p=await xe(h.getItem,f+"$",l).then(g=>ns(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=is(u);const f=r(u,!0);let h=[];const d=[];let p=!0;for(const y of f){y.driver.flags?.maxDepth||(p=!1);const I=await xe(y.driver.getKeys,y.relativeBase,l);for(const D of I){const E=y.mountpoint+Qe(D);h.some($=>E.startsWith($))||d.push(E)}h=[y.mountpoint,...h.filter(D=>!D.startsWith(y.mountpoint))]}const g=l.maxDepth!==void 0&&!p;return d.filter(y=>(!g||Oy(y,l.maxDepth))&&$y(y,u))},async clear(u,l={}){u=is(u),await Promise.all(r(u,!1).map(async f=>{if(f.driver.clear)return xe(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const h=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(h.map(d=>f.driver.removeItem(d,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Hu(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=is(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,h)=>h.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(Vu(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=is(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await Hu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=Qe(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Qe(u),r(u,l.parents).map(h=>({driver:h.driver,base:h.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,f={})=>c.setItem(u,l,f),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function Vu(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function Hu(t){typeof t.dispose=="function"&&await xe(t.dispose)}function Wn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function Wu(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Wn(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let Co;function ei(){return Co||(Co=Wu("keyval-store","keyval")),Co}function Gu(t,e=ei()){return e("readonly",n=>Wn(n.get(t)))}function Ry(t,e,n=ei()){return n("readwrite",r=>(r.put(e,t),Wn(r.transaction)))}function Cy(t,e=ei()){return e("readwrite",n=>(n.delete(t),Wn(n.transaction)))}function Ny(t=ei()){return t("readwrite",e=>(e.clear(),Wn(e.transaction)))}function Uy(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Wn(t.transaction)}function Fy(t=ei()){return t("readonly",e=>{if(e.getAllKeys)return Wn(e.getAllKeys());const n=[];return Uy(e,r=>n.push(r.key)).then(()=>n)})}const ky=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),Ly=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function mr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return Ly(t)}catch{return t}}function Gn(t){return typeof t=="string"?t:ky(t)||""}const My="idb-keyval";var jy=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=Wu(t.dbName,t.storeName)),{name:My,options:t,async hasItem(i){return!(typeof await Gu(n(i),r)>"u")},async getItem(i){return await Gu(n(i),r)??null},setItem(i,s){return Ry(n(i),s,r)},removeItem(i){return Cy(n(i),r)},getKeys(){return Fy(r)},clear(){return Ny(r)}}};const qy="WALLET_CONNECT_V2_INDEXED_DB",zy="keyvaluestorage";class Ky{constructor(){this.indexedDb=Py({driver:jy({dbName:qy,storeName:zy})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Gn(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var No=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ss={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof No<"u"&&No.localStorage?ss.exports=No.localStorage:typeof window<"u"&&window.localStorage?ss.exports=window.localStorage:ss.exports=new e})();function Vy(t){var e;return[t[0],mr((e=t[1])!=null?e:"")]}class Hy{constructor(){this.localStorage=ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Vy)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return mr(n)}async setItem(e,n){this.localStorage.setItem(e,Gn(n))}async removeItem(e){this.localStorage.removeItem(e)}}const Wy="wc_storage_version",Zu=1,Gy=async(t,e,n)=>{const r=Wy,i=await e.getItem(r);if(i&&i>=Zu){n(e);return}const s=await t.getKeys();if(!s.length){n(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(r,Zu),n(e),Zy(t,o)},Zy=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class Yy{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new Hy;this.storage=e;try{const n=new Ky;Gy(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}function Xy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Jy=Qy;function Qy(t,e,n){var r=n&&n.stringify||Xy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,f=-1,h=t&&t.length||0,d=0;d<h;){if(t.charCodeAt(d)===37&&d+1<h){switch(f=f>-1?f:0,t.charCodeAt(d+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Number(e[l]),f=d+2,d++;break;case 105:if(l>=c||e[l]==null)break;f<d&&(u+=t.slice(f,d)),u+=Math.floor(Number(e[l])),f=d+2,d++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<d&&(u+=t.slice(f,d));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=d+2,d++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=d+2,d++;break}u+=r(e[l]),f=d+2,d++;break;case 115:if(l>=c)break;f<d&&(u+=t.slice(f,d)),u+=String(e[l]),f=d+2,d++;break;case 37:f<d&&(u+=t.slice(f,d)),u+="%",f=d+2,d++,l--;break}++l}++d}return f===-1?t:(f<h&&(u+=t.slice(f)),u)}const Yu=Jy;var Yt=Lt;const ti=u1().console||{},e1={mapHttpRequest:as,mapHttpResponse:as,wrapRequestSerializer:Fo,wrapResponseSerializer:Fo,wrapErrorSerializer:Fo,req:as,res:as,err:s1};function t1(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Lt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const n=t.browser.write||ti;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=t1(t.browser.serialize,r);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=ni),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:f,set:h});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:o1(t)};c.levels=Lt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=ni,c.serializers=r,c._serialize=i,c._stdErrSerialize=s,c.child=d,e&&(c._logEvent=Uo());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function f(){return this._level}function h(p){if(p!=="silent"&&!this.levels.values[p])throw Error("unknown level "+p);this._level=p,vr(u,c,"error","log"),vr(u,c,"fatal","error"),vr(u,c,"warn","error"),vr(u,c,"info","log"),vr(u,c,"debug","log"),vr(u,c,"trace","log")}function d(p,g){if(!p)throw new Error("missing bindings for child Pino");g=g||{},i&&p.serializers&&(g.serializers=p.serializers);const y=g.serializers;if(i&&y){var I=Object.assign({},r,y),D=t.browser.serialize===!0?Object.keys(I):i;delete p.serializers,os([p],D,I,this._stdErrSerialize)}function E($){this._childLevel=($._childLevel|0)+1,this.error=Er($,p,"error"),this.fatal=Er($,p,"fatal"),this.warn=Er($,p,"warn"),this.info=Er($,p,"info"),this.debug=Er($,p,"debug"),this.trace=Er($,p,"trace"),I&&(this.serializers=I,this._serialize=D),e&&(this._logEvent=Uo([].concat($._logEvent.bindings,p)))}return E.prototype=this,new E(this)}return c}Lt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Lt.stdSerializers=e1,Lt.stdTimeFunctions=Object.assign({},{nullTime:Xu,epochTime:Ju,unixTime:a1,isoTime:c1});function vr(t,e,n,r){const i=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?ni:i[n]?i[n]:ti[n]||ti[r]||ni,n1(t,e,n)}function n1(t,e,n){!t.transmit&&e[n]===ni||(e[n]=function(r){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===ti?ti:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&os(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,r1(this,n,o,s)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Lt.levels.values[u],f=Lt.levels.values[n];if(f<l)return;i1(this,{ts:s,methodLevel:n,methodValue:f,transmitLevel:u,transmitValue:Lt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[n]))}function r1(t,e,n,r){t._serialize&&os(n,t._serialize,t.serializers,t._stdErrSerialize);const i=n.slice();let s=i[0];const o={};r&&(o.time=r),o.level=Lt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?Yu(i.shift(),i):void 0}else typeof s=="string"&&(s=Yu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function os(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=Lt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function Er(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var i=1;i<r.length;i++)r[i]=arguments[i-1];return t[n].apply(this,r)}}function i1(t,e,n){const r=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;os(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=n.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,r(s,t._logEvent,a),t._logEvent=Uo(c)}function Uo(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function s1(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 o1(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Xu:Ju}function as(){return{}}function Fo(t){return t}function ni(){}function Xu(){return!1}function Ju(){return Date.now()}function a1(){return Math.round(Date.now()/1e3)}function c1(){return new Date(Date.now()).toISOString()}function u1(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const l1={level:"info"},ri="custom_context",ko=1e3*1024;class h1{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class Qu{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new h1(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}class el{constructor(e,n=ko){this.level=e??"error",this.levelValue=Yt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Qu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===Yt.levels.values.error?console.error(e):n===Yt.levels.values.warn?console.warn(e):n===Yt.levels.values.debug?console.debug(e):n===Yt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Gn({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new Qu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Gn({extraMetadata:e})),new Blob(n,{type:"application/json"})}}class f1{constructor(e,n=ko){this.baseChunkLogger=new el(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}class d1{constructor(e,n=ko){this.baseChunkLogger=new el(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 p1=Object.defineProperty,g1=Object.defineProperties,y1=Object.getOwnPropertyDescriptors,tl=Object.getOwnPropertySymbols,w1=Object.prototype.hasOwnProperty,b1=Object.prototype.propertyIsEnumerable,nl=(t,e,n)=>e in t?p1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,cs=(t,e)=>{for(var n in e||(e={}))w1.call(e,n)&&nl(t,n,e[n]);if(tl)for(var n of tl(e))b1.call(e,n)&&nl(t,n,e[n]);return t},us=(t,e)=>g1(t,y1(e));function Lo(t){return us(cs({},t),{level:t?.level||l1.level})}function m1(t,e=ri){return t[e]||""}function v1(t,e,n=ri){return t[n]=e,t}function et(t,e=ri){let n="";return typeof t.bindings>"u"?n=m1(t,e):n=t.bindings().context||"",n}function E1(t,e,n=ri){const r=et(t,n);return r.trim()?`${r}/${e}`:e}function We(t,e,n=ri){const r=E1(t,e,n),i=t.child({context:r});return v1(i,r,n)}function _1(t){var e,n;const r=new f1((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Yt(us(cs({},t.opts),{level:"trace",browser:us(cs({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function x1(t){var e;const n=new d1((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:Yt(us(cs({},t.opts),{level:"trace"})),chunkLoggerController:n}}function I1(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?_1(t):x1(t)}var S1=Object.defineProperty,D1=(t,e,n)=>e in t?S1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,rl=(t,e,n)=>D1(t,typeof e!="symbol"?e+"":e,n);class A1 extends Vn{constructor(e){super(),this.opts=e,rl(this,"protocol","wc"),rl(this,"version",2)}}var O1=Object.defineProperty,$1=(t,e,n)=>e in t?O1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,B1=(t,e,n)=>$1(t,typeof e!="symbol"?e+"":e,n);class T1 extends Vn{constructor(e,n){super(),this.core=e,this.logger=n,B1(this,"records",new Map)}}class P1{constructor(e,n){this.logger=e,this.core=n}}class R1 extends Vn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class C1 extends Vn{constructor(e){super()}}class N1{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class U1 extends Vn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class F1 extends Vn{constructor(e,n){super(),this.core=e,this.logger=n}}class k1{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class L1{constructor(e,n){this.projectId=e,this.logger=n}}class M1{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var j1=Object.defineProperty,q1=(t,e,n)=>e in t?j1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,il=(t,e,n)=>q1(t,typeof e!="symbol"?e+"":e,n);class z1{constructor(e){this.opts=e,il(this,"protocol","wc"),il(this,"version",2)}}class K1{constructor(e){this.client=e}}function V1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sl(t,...e){if(!V1(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 ol(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 H1(t,e){sl(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const _r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mo=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function W1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function al(t){return typeof t=="string"&&(t=W1(t)),sl(t),t}class G1{clone(){return this._cloneInto()}}function Z1(t){const e=r=>t().update(al(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function cl(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return _r.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Y1(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}class X1 extends G1{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Mo(this.buffer)}update(e){ol(this);const{view:n,buffer:r,blockLen:i}=this;e=al(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Mo(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){ol(this),H1(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;Y1(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Mo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const ls=BigInt(2**32-1),jo=BigInt(32);function ul(t,e=!1){return e?{h:Number(t&ls),l:Number(t>>jo&ls)}:{h:Number(t>>jo&ls)|0,l:Number(t&ls)|0}}function J1(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=ul(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const Q1=(t,e)=>BigInt(t>>>0)<<jo|BigInt(e>>>0),ew=(t,e,n)=>t>>>n,tw=(t,e,n)=>t<<32-n|e>>>n,nw=(t,e,n)=>t>>>n|e<<32-n,rw=(t,e,n)=>t<<32-n|e>>>n,iw=(t,e,n)=>t<<64-n|e>>>n-32,sw=(t,e,n)=>t>>>n-32|e<<64-n,ow=(t,e)=>e,aw=(t,e)=>t,cw=(t,e,n)=>t<<n|e>>>32-n,uw=(t,e,n)=>e<<n|t>>>32-n,lw=(t,e,n)=>e<<n-32|t>>>64-n,hw=(t,e,n)=>t<<n-32|e>>>64-n;function fw(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const dw=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),pw=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,gw=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),yw=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,ww=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),bw=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,J={fromBig:ul,split:J1,toBig:Q1,shrSH:ew,shrSL:tw,rotrSH:nw,rotrSL:rw,rotrBH:iw,rotrBL:sw,rotr32H:ow,rotr32L:aw,rotlSH:cw,rotlSL:uw,rotlBH:lw,rotlBL:hw,add:fw,add3L:dw,add3H:pw,add4L:gw,add4H:yw,add5H:bw,add5L:ww},[mw,vw]=J.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),yn=new Uint32Array(80),wn=new Uint32Array(80);class Ew extends X1{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let E=0;E<16;E++,n+=4)yn[E]=e.getUint32(n),wn[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const $=yn[E-15]|0,R=wn[E-15]|0,C=J.rotrSH($,R,1)^J.rotrSH($,R,8)^J.shrSH($,R,7),U=J.rotrSL($,R,1)^J.rotrSL($,R,8)^J.shrSL($,R,7),N=yn[E-2]|0,O=wn[E-2]|0,G=J.rotrSH(N,O,19)^J.rotrBH(N,O,61)^J.shrSH(N,O,6),W=J.rotrSL(N,O,19)^J.rotrBL(N,O,61)^J.shrSL(N,O,6),P=J.add4L(U,W,wn[E-7],wn[E-16]),v=J.add4H(P,C,G,yn[E-7],yn[E-16]);yn[E]=v|0,wn[E]=P|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:y,Hh:I,Hl:D}=this;for(let E=0;E<80;E++){const $=J.rotrSH(f,h,14)^J.rotrSH(f,h,18)^J.rotrBH(f,h,41),R=J.rotrSL(f,h,14)^J.rotrSL(f,h,18)^J.rotrBL(f,h,41),C=f&d^~f&g,U=h&p^~h&y,N=J.add5L(D,R,U,vw[E],wn[E]),O=J.add5H(N,I,$,C,mw[E],yn[E]),G=N|0,W=J.rotrSH(r,i,28)^J.rotrBH(r,i,34)^J.rotrBH(r,i,39),P=J.rotrSL(r,i,28)^J.rotrBL(r,i,34)^J.rotrBL(r,i,39),v=r&s^r&a^s&a,m=i&o^i&c^o&c;I=g|0,D=y|0,g=d|0,y=p|0,d=f|0,p=h|0,{h:f,l:h}=J.add(u|0,l|0,O|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const w=J.add3L(G,P,m);r=J.add3H(w,O,W,v),i=w|0}({h:r,l:i}=J.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=J.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=J.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=J.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=J.add(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=J.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:y}=J.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:I,l:D}=J.add(this.Hh|0,this.Hl|0,I|0,D|0),this.set(r,i,s,o,a,c,u,l,f,h,d,p,g,y,I,D)}roundClean(){yn.fill(0),wn.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const _w=Z1(()=>new Ew);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qo=BigInt(0),ll=BigInt(1),xw=BigInt(2);function zo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ko(t){if(!zo(t))throw new Error("Uint8Array expected")}function Vo(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const Iw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ho(t){Ko(t);let e="";for(let n=0;n<t.length;n++)e+=Iw[t[n]];return e}function hl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?qo:BigInt("0x"+t)}const Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function fl(t){if(t>=Xt._0&&t<=Xt._9)return t-Xt._0;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function dl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=fl(t.charCodeAt(s)),a=fl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Sw(t){return hl(Ho(t))}function hs(t){return Ko(t),hl(Ho(Uint8Array.from(t).reverse()))}function pl(t,e){return dl(t.toString(16).padStart(e*2,"0"))}function Wo(t,e){return pl(t,e).reverse()}function Jt(t,e,n){let r;if(typeof e=="string")try{r=dl(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(zo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function gl(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Ko(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const Go=t=>typeof t=="bigint"&&qo<=t;function Dw(t,e,n){return Go(t)&&Go(e)&&Go(n)&&e<=t&&t<n}function ii(t,e,n,r){if(!Dw(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Aw(t){let e;for(e=0;t>qo;t>>=ll,e+=1);return e}const Ow=t=>(xw<<BigInt(t-1))-ll,$w={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||zo(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function Zo(t,e,n={}){const r=(i,s,o)=>{const a=$w[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function yl(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Ie=BigInt(0),de=BigInt(1),Zn=BigInt(2),Bw=BigInt(3),Yo=BigInt(4),wl=BigInt(5),bl=BigInt(8);function be(t,e){const n=t%e;return n>=Ie?n:e+n}function Tw(t,e,n){if(e<Ie)throw new Error("invalid exponent, negatives unsupported");if(n<=Ie)throw new Error("invalid modulus");if(n===de)return Ie;let r=de;for(;e>Ie;)e&de&&(r=r*t%n),t=t*t%n,e>>=de;return r}function Mt(t,e,n){let r=t;for(;e-- >Ie;)r*=r,r%=n;return r}function ml(t,e){if(t===Ie)throw new Error("invert: expected non-zero number");if(e<=Ie)throw new Error("invert: expected positive modulus, got "+e);let n=be(t,e),r=e,i=Ie,s=de;for(;n!==Ie;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==de)throw new Error("invert: does not exist");return be(i,e)}function Pw(t){const e=(t-de)/Zn;let n,r,i;for(n=t-de,r=0;n%Zn===Ie;n/=Zn,r++);for(i=Zn;i<t&&Tw(i,e,t)!==t-de;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+de)/Yo;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(n+de)/Zn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,i),n),l=o.pow(a,s),f=o.pow(a,n);for(;!o.eql(f,o.ONE);){if(o.eql(f,o.ZERO))return o.ZERO;let h=1;for(let p=o.sqr(f);h<c&&!o.eql(p,o.ONE);h++)p=o.sqr(p);const d=o.pow(u,de<<BigInt(c-h-1));u=o.sqr(d),l=o.mul(l,d),f=o.mul(f,u),c=h}return l}}function Rw(t){if(t%Yo===Bw){const e=(t+de)/Yo;return function(n,r){const i=n.pow(r,e);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%bl===wl){const e=(t-wl)/bl;return function(n,r){const i=n.mul(r,Zn),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Zn),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return Pw(t)}const Cw=(t,e)=>(be(t,e)&de)===de,Nw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Uw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=Nw.reduce((r,i)=>(r[i]="function",r),e);return Zo(t,n)}function Fw(t,e,n){if(n<Ie)throw new Error("invalid exponent, negatives unsupported");if(n===Ie)return t.ONE;if(n===de)return e;let r=t.ONE,i=e;for(;n>Ie;)n&de&&(r=t.mul(r,i)),i=t.sqr(i),n>>=de;return r}function kw(t,e){const n=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(n[a]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(n[a]=t.mul(s,n[a]),t.mul(s,o)),i),n}function vl(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function El(t,e,n=!1,r={}){if(t<=Ie)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=vl(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:Ow(i),ZERO:Ie,ONE:de,create:c=>be(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ie<=c&&c<t},is0:c=>c===Ie,isOdd:c=>(c&de)===de,neg:c=>be(-c,t),eql:(c,u)=>c===u,sqr:c=>be(c*c,t),add:(c,u)=>be(c+u,t),sub:(c,u)=>be(c-u,t),mul:(c,u)=>be(c*u,t),pow:(c,u)=>Fw(a,c,u),div:(c,u)=>be(c*ml(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>ml(c,t),sqrt:r.sqrt||(c=>(o||(o=Rw(t)),o(a,c))),invertBatch:c=>kw(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?Wo(c,s):pl(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?hs(c):Sw(c)}});return Object.freeze(a)}const _l=BigInt(0),fs=BigInt(1);function Xo(t,e){const n=e.negate();return t?n:e}function xl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Jo(t,e){xl(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function Lw(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 Mw(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Qo=new WeakMap,Il=new WeakMap;function ea(t){return Il.get(t)||1}function jw(t,e){return{constTimeNegate:Xo,hasPrecomputes(n){return ea(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>_l;)r&fs&&(i=i.add(s)),s=s.double(),r>>=fs;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Jo(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){const{windows:s,windowSize:o}=Jo(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let h=0;h<s;h++){const d=h*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=fs);const g=d,y=d+Math.abs(p)-1,I=h%2!==0,D=p<0;p===0?c=c.add(Xo(I,r[g])):a=a.add(Xo(D,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=Jo(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let f=0;f<o;f++){const h=f*a;if(i===_l)break;let d=Number(i&c);if(i>>=l,d>a&&(d-=u,i+=fs),d===0)continue;let p=r[h+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=Qo.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Qo.set(r,i(s))),s},wNAFCached(n,r,i){const s=ea(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=ea(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){xl(r,e),Il.set(n,r),Qo.delete(n)}}}function qw(t,e,n,r){if(Lw(n,t),Mw(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=Aw(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let f=u;f>=0;f-=o){c.fill(i);for(let d=0;d<r.length;d++){const p=r[d],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(n[d])}let h=i;for(let d=c.length-1,p=i;d>0;d--)p=p.add(c[d]),h=h.add(p);if(l=l.add(h),f!==0)for(let d=0;d<o;d++)l=l.double()}return l}function zw(t){return Uw(t.Fp),Zo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...vl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Bt=BigInt(0),tt=BigInt(1),ds=BigInt(2),Kw=BigInt(8),Vw={zip215:!0};function Hw(t){const e=zw(t);return Zo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Ww(t){const e=Hw(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=ds<<BigInt(a*8)-tt,l=n.create,f=El(e.n,e.nBitLength),h=e.uvRatio||((w,b)=>{try{return{isValid:!0,value:n.sqrt(w*n.inv(b))}}catch{return{isValid:!1,value:Bt}}}),d=e.adjustScalarBytes||(w=>w),p=e.domain||((w,b,x)=>{if(Vo("phflag",x),b.length||x)throw new Error("Contexts/pre-hash are not supported");return w});function g(w,b){ii("coordinate "+w,b,Bt,u)}function y(w){if(!(w instanceof E))throw new Error("ExtendedPoint expected")}const I=yl((w,b)=>{const{ex:x,ey:A,ez:_}=w,S=w.is0();b==null&&(b=S?Kw:n.inv(_));const B=l(x*b),T=l(A*b),q=l(_*b);if(S)return{x:Bt,y:tt};if(q!==tt)throw new Error("invZ was invalid");return{x:B,y:T}}),D=yl(w=>{const{a:b,d:x}=e;if(w.is0())throw new Error("bad point: ZERO");const{ex:A,ey:_,ez:S,et:B}=w,T=l(A*A),q=l(_*_),L=l(S*S),k=l(L*L),z=l(T*b),H=l(L*l(z+q)),Z=l(k+l(x*l(T*q)));if(H!==Z)throw new Error("bad point: equation left != right (1)");const V=l(A*_),Y=l(S*B);if(V!==Y)throw new Error("bad point: equation left != right (2)");return!0});class E{constructor(b,x,A,_){this.ex=b,this.ey=x,this.ez=A,this.et=_,g("x",b),g("y",x),g("z",A),g("t",_),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(b){if(b instanceof E)throw new Error("extended point not allowed");const{x,y:A}=b||{};return g("x",x),g("y",A),new E(x,A,tt,l(x*A))}static normalizeZ(b){const x=n.invertBatch(b.map(A=>A.ez));return b.map((A,_)=>A.toAffine(x[_])).map(E.fromAffine)}static msm(b,x){return qw(E,f,b,x)}_setWindowSize(b){C.setWindowSize(this,b)}assertValidity(){D(this)}equals(b){y(b);const{ex:x,ey:A,ez:_}=this,{ex:S,ey:B,ez:T}=b,q=l(x*T),L=l(S*_),k=l(A*T),z=l(B*_);return q===L&&k===z}is0(){return this.equals(E.ZERO)}negate(){return new E(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:b}=e,{ex:x,ey:A,ez:_}=this,S=l(x*x),B=l(A*A),T=l(ds*l(_*_)),q=l(b*S),L=x+A,k=l(l(L*L)-S-B),z=q+B,H=z-T,Z=q-B,V=l(k*H),Y=l(z*Z),he=l(k*Z),Ke=l(H*z);return new E(V,Y,Ke,he)}add(b){y(b);const{a:x,d:A}=e,{ex:_,ey:S,ez:B,et:T}=this,{ex:q,ey:L,ez:k,et:z}=b;if(x===BigInt(-1)){const S0=l((S-_)*(L+q)),D0=l((S+_)*(L-q)),bu=l(D0-S0);if(bu===Bt)return this.double();const A0=l(B*ds*z),O0=l(T*ds*k),$0=O0+A0,B0=D0+S0,T0=O0-A0,m$=l($0*bu),v$=l(B0*T0),E$=l($0*T0),_$=l(bu*B0);return new E(m$,v$,_$,E$)}const H=l(_*q),Z=l(S*L),V=l(T*A*z),Y=l(B*k),he=l((_+S)*(q+L)-H-Z),Ke=Y-V,mt=Y+V,gn=l(Z-x*H),wu=l(he*Ke),y$=l(mt*gn),w$=l(he*gn),b$=l(Ke*mt);return new E(wu,y$,b$,w$)}subtract(b){return this.add(b.negate())}wNAF(b){return C.wNAFCached(this,b,E.normalizeZ)}multiply(b){const x=b;ii("scalar",x,tt,r);const{p:A,f:_}=this.wNAF(x);return E.normalizeZ([A,_])[0]}multiplyUnsafe(b,x=E.ZERO){const A=b;return ii("scalar",A,Bt,r),A===Bt?R:this.is0()||A===tt?this:C.wNAFCachedUnsafe(this,A,E.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return C.unsafeLadder(this,r).is0()}toAffine(b){return I(this,b)}clearCofactor(){const{h:b}=e;return b===tt?this:this.multiplyUnsafe(b)}static fromHex(b,x=!1){const{d:A,a:_}=e,S=n.BYTES;b=Jt("pointHex",b,S),Vo("zip215",x);const B=b.slice(),T=b[S-1];B[S-1]=T&-129;const q=hs(B),L=x?u:n.ORDER;ii("pointHex.y",q,Bt,L);const k=l(q*q),z=l(k-tt),H=l(A*k-_);let{isValid:Z,value:V}=h(z,H);if(!Z)throw new Error("Point.fromHex: invalid y coordinate");const Y=(V&tt)===tt,he=(T&128)!==0;if(!x&&V===Bt&&he)throw new Error("Point.fromHex: x=0 and x_0=1");return he!==Y&&(V=l(-V)),E.fromAffine({x:V,y:q})}static fromPrivateKey(b){return O(b).point}toRawBytes(){const{x:b,y:x}=this.toAffine(),A=Wo(x,n.BYTES);return A[A.length-1]|=b&tt?128:0,A}toHex(){return Ho(this.toRawBytes())}}E.BASE=new E(e.Gx,e.Gy,tt,l(e.Gx*e.Gy)),E.ZERO=new E(Bt,tt,tt,Bt);const{BASE:$,ZERO:R}=E,C=jw(E,a*8);function U(w){return be(w,r)}function N(w){return U(hs(w))}function O(w){const b=n.BYTES;w=Jt("private key",w,b);const x=Jt("hashed private key",s(w),2*b),A=d(x.slice(0,b)),_=x.slice(b,2*b),S=N(A),B=$.multiply(S),T=B.toRawBytes();return{head:A,prefix:_,scalar:S,point:B,pointBytes:T}}function G(w){return O(w).pointBytes}function W(w=new Uint8Array,...b){const x=gl(...b);return N(s(p(x,Jt("context",w),!!i)))}function P(w,b,x={}){w=Jt("message",w),i&&(w=i(w));const{prefix:A,scalar:_,pointBytes:S}=O(b),B=W(x.context,A,w),T=$.multiply(B).toRawBytes(),q=W(x.context,T,S,w),L=U(B+q*_);ii("signature.s",L,Bt,r);const k=gl(T,Wo(L,n.BYTES));return Jt("result",k,n.BYTES*2)}const v=Vw;function m(w,b,x,A=v){const{context:_,zip215:S}=A,B=n.BYTES;w=Jt("signature",w,2*B),b=Jt("message",b),x=Jt("publicKey",x,B),S!==void 0&&Vo("zip215",S),i&&(b=i(b));const T=hs(w.slice(B,2*B));let q,L,k;try{q=E.fromHex(x,S),L=E.fromHex(w.slice(0,B),S),k=$.multiplyUnsafe(T)}catch{return!1}if(!S&&q.isSmallOrder())return!1;const z=W(_,L.toRawBytes(),q.toRawBytes(),b);return L.add(q.multiplyUnsafe(z)).subtract(k).clearCofactor().equals(E.ZERO)}return $._setWindowSize(8),{CURVE:e,getPublicKey:G,sign:P,verify:m,ExtendedPoint:E,utils:{getExtendedPublicKey:O,randomPrivateKey:()=>o(n.BYTES),precompute(w=8,b=E.BASE){return b._setWindowSize(w),b.multiply(BigInt(3)),b}}}}BigInt(0),BigInt(1);const ta=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Sl=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Gw=BigInt(1),Dl=BigInt(2);BigInt(3);const Zw=BigInt(5),Yw=BigInt(8);function Xw(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=ta,o=t*t%s*t%s,a=Mt(o,Dl,s)*o%s,c=Mt(a,Gw,s)*t%s,u=Mt(c,Zw,s)*c%s,l=Mt(u,e,s)*u%s,f=Mt(l,n,s)*l%s,h=Mt(f,r,s)*f%s,d=Mt(h,i,s)*h%s,p=Mt(d,i,s)*h%s,g=Mt(p,e,s)*u%s;return{pow_p_5_8:Mt(g,Dl,s)*t%s,b2:o}}function Jw(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Qw(t,e){const n=ta,r=be(e*e*e,n),i=be(r*r*e,n),s=Xw(t*i).pow_p_5_8;let o=be(t*r*s,n);const a=be(e*o*o,n),c=o,u=be(o*Sl,n),l=a===t,f=a===be(-t,n),h=a===be(-t*Sl,n);return l&&(o=c),(f||h)&&(o=u),Cw(o,n)&&(o=be(-o,n)),{isValid:l||f,value:o}}const eb=El(ta,void 0,!0),tb={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:eb,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Yw,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:_w,randomBytes:cl,adjustScalarBytes:Jw,uvRatio:Qw},Al=Ww(tb),nb="EdDSA",rb="JWT",ps=".",gs="base64url",Ol="utf8",$l="utf8",ib=":",sb="did",ob="key",Bl="base58btc",ab="z",cb="K36",ub=32;function na(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Tl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?na(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Pl(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Tl(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return na(n)}function lb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var hb=lb,fb=hb;const Rl=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")},db=t=>new TextEncoder().encode(t),pb=t=>new TextDecoder().decode(t);class gb{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class yb{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 Cl(this,e)}}class wb{constructor(e){this.decoders=e}or(e){return Cl(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 Cl=(t,e)=>new wb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class bb{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new gb(e,n,r),this.decoder=new yb(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ys=({name:t,prefix:e,encode:n,decode:r})=>new bb(t,e,n,r),si=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=fb(n,e);return ys({prefix:t,name:e,encode:r,decode:s=>Rl(i(s))})},mb=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},vb=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},De=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ys({prefix:e,name:t,encode(i){return vb(i,r,n)},decode(i){return mb(i,r,n,t)}}),Eb=ys({prefix:"\0",name:"identity",encode:t=>pb(t),decode:t=>db(t)});var _b=Object.freeze({__proto__:null,identity:Eb});const xb=De({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Ib=Object.freeze({__proto__:null,base2:xb});const Sb=De({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Db=Object.freeze({__proto__:null,base8:Sb});const Ab=si({prefix:"9",name:"base10",alphabet:"0123456789"});var Ob=Object.freeze({__proto__:null,base10:Ab});const $b=De({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Bb=De({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var Tb=Object.freeze({__proto__:null,base16:$b,base16upper:Bb});const Pb=De({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Rb=De({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cb=De({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Nb=De({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Ub=De({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Fb=De({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),kb=De({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Lb=De({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mb=De({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var jb=Object.freeze({__proto__:null,base32:Pb,base32upper:Rb,base32pad:Cb,base32padupper:Nb,base32hex:Ub,base32hexupper:Fb,base32hexpad:kb,base32hexpadupper:Lb,base32z:Mb});const qb=si({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zb=si({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var Kb=Object.freeze({__proto__:null,base36:qb,base36upper:zb});const Vb=si({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hb=si({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Wb=Object.freeze({__proto__:null,base58btc:Vb,base58flickr:Hb});const Gb=De({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Zb=De({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Yb=De({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Xb=De({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Jb=Object.freeze({__proto__:null,base64:Gb,base64pad:Zb,base64url:Yb,base64urlpad:Xb});const Nl=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}"),Qb=Nl.reduce((t,e,n)=>(t[n]=e,t),[]),em=Nl.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function tm(t){return t.reduce((e,n)=>(e+=Qb[n],e),"")}function nm(t){const e=[];for(const n of t){const r=em[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const rm=ys({prefix:"\u{1F680}",name:"base256emoji",encode:tm,decode:nm});var im=Object.freeze({__proto__:null,base256emoji:rm}),sm=Fl,Ul=128,om=127,am=~om,cm=Math.pow(2,31);function Fl(t,e,n){e=e||[],n=n||0;for(var r=n;t>=cm;)e[n++]=t&255|Ul,t/=128;for(;t&am;)e[n++]=t&255|Ul,t>>>=7;return e[n]=t|0,Fl.bytes=n-r+1,e}var um=ra,lm=128,kl=127;function ra(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw ra.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&kl)<<i:(o&kl)*Math.pow(2,i),i+=7}while(o>=lm);return ra.bytes=s-r,n}var hm=Math.pow(2,7),fm=Math.pow(2,14),dm=Math.pow(2,21),pm=Math.pow(2,28),gm=Math.pow(2,35),ym=Math.pow(2,42),wm=Math.pow(2,49),bm=Math.pow(2,56),mm=Math.pow(2,63),vm=function(t){return t<hm?1:t<fm?2:t<dm?3:t<pm?4:t<gm?5:t<ym?6:t<wm?7:t<bm?8:t<mm?9:10},Em={encode:sm,decode:um,encodingLength:vm},Ll=Em;const Ml=(t,e,n=0)=>(Ll.encode(t,e,n),e),jl=t=>Ll.encodingLength(t),ia=(t,e)=>{const n=e.byteLength,r=jl(t),i=r+jl(n),s=new Uint8Array(i+n);return Ml(t,s,0),Ml(n,s,r),s.set(e,i),new _m(t,n,e,s)};class _m{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const ql=({name:t,code:e,encode:n})=>new xm(t,e,n);class xm{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ia(this.code,n):n.then(r=>ia(this.code,r))}else throw Error("Unknown type, must be binary type")}}const zl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Im=ql({name:"sha2-256",code:18,encode:zl("SHA-256")}),Sm=ql({name:"sha2-512",code:19,encode:zl("SHA-512")});var Dm=Object.freeze({__proto__:null,sha256:Im,sha512:Sm});const Kl=0,Am="identity",Vl=Rl;var Om=Object.freeze({__proto__:null,identity:{code:Kl,name:Am,encode:Vl,digest:t=>ia(Kl,Vl(t))}});new TextEncoder,new TextDecoder;const Hl={..._b,...Ib,...Db,...Ob,...Tb,...jb,...Kb,...Wb,...Jb,...im};({...Dm,...Om});function Wl(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Gl=Wl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),sa=Wl("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=Tl(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Zl={utf8:Gl,"utf-8":Gl,hex:Hl.base16,latin1:sa,ascii:sa,binary:sa,...Hl};function ws(t,e="utf8"){const n=Zl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}function xr(t,e="utf8"){const n=Zl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?na(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Yl(t){return mr(ws(xr(t,gs),Ol))}function bs(t){return ws(xr(Gn(t),Ol),gs)}function Xl(t){const e=xr(cb,Bl),n=ab+ws(Pl([e,t]),Bl);return[sb,ob,n].join(ib)}function $m(t){return ws(t,gs)}function Bm(t){return xr(t,gs)}function Tm(t){return xr([bs(t.header),bs(t.payload)].join(ps),$l)}function Pm(t){return[bs(t.header),bs(t.payload),$m(t.signature)].join(ps)}function oa(t){const e=t.split(ps),n=Yl(e[0]),r=Yl(e[1]),i=Bm(e[2]),s=xr(e.slice(0,2).join(ps),$l);return{header:n,payload:r,signature:i,data:s}}function Jl(t=cl(ub)){const e=Al.getPublicKey(t);return{secretKey:Pl([t,e]),publicKey:e}}async function Rm(t,e,n,r,i=M.fromMiliseconds(Date.now())){const s={alg:nb,typ:rb},o=Xl(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=Tm({header:s,payload:c}),l=Al.sign(u,r.secretKey.slice(0,32));return Pm({header:s,payload:c,signature:l})}var Ql=function(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},Cm=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}(),Um=function(){function t(e,n,r,i){this.name=e,this.version=n,this.os=r,this.bot=i,this.type="bot-device"}return t}(),Fm=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),km=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),Lm=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,Mm=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,eh=3,jm=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",Lm]],th=[["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 qm(t){return t?nh(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new km:typeof navigator<"u"?nh(navigator.userAgent):Vm()}function zm(t){return t!==""&&jm.reduce(function(e,n){var r=n[0],i=n[1];if(e)return e;var s=i.exec(t);return!!s&&[r,s]},!1)}function nh(t){var e=zm(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new Fm;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<eh&&(i=Ql(Ql([],i,!0),Hm(eh-i.length),!0)):i=[];var s=i.join("."),o=Km(t),a=Mm.exec(t);return a&&a[1]?new Um(n,s,o,a[1]):new Cm(n,s,o)}function Km(t){for(var e=0,n=th.length;e<n;e++){var r=th[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function Vm(){var t=typeof process<"u"&&process.version;return t?new Nm(process.version.slice(1)):null}function Hm(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var ce={};Object.defineProperty(ce,"__esModule",{value:!0}),ce.getLocalStorage=ce.getLocalStorageOrThrow=ce.getCrypto=ce.getCryptoOrThrow=rh=ce.getLocation=ce.getLocationOrThrow=aa=ce.getNavigator=ce.getNavigatorOrThrow=Xn=ce.getDocument=ce.getDocumentOrThrow=ce.getFromWindowOrThrow=ce.getFromWindow=void 0;function Yn(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ce.getFromWindow=Yn;function Ir(t){const e=Yn(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ce.getFromWindowOrThrow=Ir;function Wm(){return Ir("document")}ce.getDocumentOrThrow=Wm;function Gm(){return Yn("document")}var Xn=ce.getDocument=Gm;function Zm(){return Ir("navigator")}ce.getNavigatorOrThrow=Zm;function Ym(){return Yn("navigator")}var aa=ce.getNavigator=Ym;function Xm(){return Ir("location")}ce.getLocationOrThrow=Xm;function Jm(){return Yn("location")}var rh=ce.getLocation=Jm;function Qm(){return Ir("crypto")}ce.getCryptoOrThrow=Qm;function ev(){return Yn("crypto")}ce.getCrypto=ev;function tv(){return Ir("localStorage")}ce.getLocalStorageOrThrow=tv;function nv(){return Yn("localStorage")}ce.getLocalStorage=nv;var ca={};Object.defineProperty(ca,"__esModule",{value:!0});var ih=ca.getWindowMetadata=void 0;const sh=ce;function rv(){let t,e;try{t=sh.getDocumentOrThrow(),e=sh.getLocationOrThrow()}catch{return null}function n(){const f=t.getElementsByTagName("link"),h=[];for(let d=0;d<f.length;d++){const p=f[d],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=p.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let I=e.protocol+"//"+e.host;if(y.indexOf("/")===0)I+=y;else{const D=e.pathname.split("/");D.pop();const E=D.join("/");I+=E+"/"+y}h.push(I)}else if(y.indexOf("//")===0){const I=e.protocol+y;h.push(I)}else h.push(y)}}return h}function r(...f){const h=t.getElementsByTagName("meta");for(let d=0;d<h.length;d++){const p=h[d],g=["itemprop","property","name"].map(y=>p.getAttribute(y)).filter(y=>y?f.includes(y):!1);if(g.length&&g){const y=p.getAttribute("content");if(y)return y}}return""}function i(){let f=r("name","og:site_name","og:title","twitter:title");return f||(f=t.title),f}function s(){return r("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=n();return{description:a,url:c,icons:u,name:o}}ih=ca.getWindowMetadata=rv;function oi(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function ua(t){return oi(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const oh="2.36.0";let la={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${oh}`};class Jn extends Error{constructor(e,n={}){const r=n.cause instanceof Jn?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof Jn&&n.cause.docsPath||n.docsPath,s=la.getDocsUrl?.({...n,docsPath:i}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...la.version?[`Version: ${la.version}`]:[]].join(`
15
+ `);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=oh}walk(e){return ah(this,e)}}function ah(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?ah(t.cause,e):e?null:t}class ch extends Jn{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}}function Sr(t,{dir:e,size:n=32}={}){return typeof t=="string"?iv(t,{dir:e,size:n}):sv(t,{dir:e,size:n})}function iv(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new ch({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function sv(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new ch({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s=e==="right";r[s?i:n-i-1]=t[s?i:t.length-i-1]}return r}class ov extends Jn{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${n} to ${e})`:`(above ${n})`}`,{name:"IntegerOutOfRangeError"})}}class av extends Jn{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed ${n} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function Dr(t,{size:e}){if(ua(t)>e)throw new av({givenSize:ua(t),maxSize:e})}function ha(t,e={}){const{signed:n}=e;e.size&&Dr(t,{size:e.size});const r=BigInt(t);if(!n)return r;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return r<=s?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function cv(t,e={}){return Number(ha(t,e))}const uv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function fa(t,e={}){return typeof t=="number"||typeof t=="bigint"?da(t,e):typeof t=="string"?fv(t,e):typeof t=="boolean"?lv(t,e):uh(t,e)}function lv(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{size:e.size})):n}function uh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=uv[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(Dr(r,{size:e.size}),Sr(r,{dir:"right",size:e.size})):r}function da(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new ov({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:n,size:r,value:`${t}${c}`})}const a=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Sr(a,{size:r}):a}const hv=new TextEncoder;function fv(t,e={}){const n=hv.encode(t);return uh(n,e)}const dv=new TextEncoder;function pv(t,e={}){return typeof t=="number"||typeof t=="bigint"?yv(t,e):typeof t=="boolean"?gv(t,e):oi(t)?hh(t,e):fh(t,e)}function gv(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{size:e.size})):n}const Qt={zero:48,nine:57,A:65,F:70,a:97,f:102};function lh(t){if(t>=Qt.zero&&t<=Qt.nine)return t-Qt.zero;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function hh(t,e={}){let n=t;e.size&&(Dr(n,{size:e.size}),n=Sr(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=lh(r.charCodeAt(a++)),u=lh(r.charCodeAt(a++));if(c===void 0||u===void 0)throw new Jn(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);s[o]=c*16+u}return s}function yv(t,e){const n=da(t,e);return hh(n)}function fh(t,e={}){const n=dv.encode(t);return typeof e.size=="number"?(Dr(n,{size:e.size}),Sr(n,{dir:"right",size:e.size})):n}const ms=BigInt(2**32-1),dh=BigInt(32);function wv(t,e=!1){return e?{h:Number(t&ms),l:Number(t>>dh&ms)}:{h:Number(t>>dh&ms)|0,l:Number(t&ms)|0}}function bv(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=wv(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const mv=(t,e,n)=>t<<n|e>>>32-n,vv=(t,e,n)=>e<<n|t>>>32-n,Ev=(t,e,n)=>e<<n-32|t>>>64-n,_v=(t,e,n)=>t<<n-32|e>>>64-n,Ar=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function ai(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ci(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!ai(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ph(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ci(t.outputLen),ci(t.blockLen)}function Or(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function gh(t,e){vt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function xv(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function $r(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function pa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function jt(t,e){return t<<32-e|t>>>e}const Iv=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sv(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Dv(t){for(let e=0;e<t.length;e++)t[e]=Sv(t[e]);return t}const yh=Iv?t=>t:Dv,wh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Av=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Br(t){if(vt(t),wh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Av[t[n]];return e}const en={_0:48,_9:57,A:65,F:70,a:97,f:102};function bh(t){if(t>=en._0&&t<=en._9)return t-en._0;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function vs(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(wh)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=bh(t.charCodeAt(s)),a=bh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Tr(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Es(t){return typeof t=="string"&&(t=Tr(t)),vt(t),t}function Ce(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];vt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class ga{}function mh(t){const e=r=>t().update(Es(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function _s(t=32){if(Ar&&typeof Ar.getRandomValues=="function")return Ar.getRandomValues(new Uint8Array(t));if(Ar&&typeof Ar.randomBytes=="function")return Uint8Array.from(Ar.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Ov=BigInt(0),ui=BigInt(1),$v=BigInt(2),Bv=BigInt(7),Tv=BigInt(256),Pv=BigInt(113),vh=[],Eh=[],_h=[];for(let t=0,e=ui,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],vh.push(2*(5*r+n)),Eh.push((t+1)*(t+2)/2%64);let i=Ov;for(let s=0;s<7;s++)e=(e<<ui^(e>>Bv)*Pv)%Tv,e&$v&&(i^=ui<<(ui<<BigInt(s))-ui);_h.push(i)}const xh=bv(_h,!0),Rv=xh[0],Cv=xh[1],Ih=(t,e,n)=>n>32?Ev(t,e,n):mv(t,e,n),Sh=(t,e,n)=>n>32?_v(t,e,n):vv(t,e,n);function Nv(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],f=Ih(u,l,1)^n[a],h=Sh(u,l,1)^n[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Eh[o],c=Ih(i,s,a),u=Sh(i,s,a),l=vh[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Rv[r],t[1]^=Cv[r]}$r(n)}class ya extends ga{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,ci(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=xv(this.state)}clone(){return this._cloneInto()}keccak(){yh(this.state32),Nv(this.state32,this.rounds),yh(this.state32),this.posOut=0,this.pos=0}update(e){Or(this),e=Es(e),vt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Or(this,!1),vt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return ci(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(gh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,$r(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ya(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Uv=(t,e,n)=>mh(()=>new ya(e,t,n)),Dh=Uv(1,136,256/8);function Ah(t,e){const n=e||"hex",r=Dh(oi(t,{strict:!1})?pv(t):t);return n==="bytes"?r:fa(r)}class Oh extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const wa=new Oh(8192);function Fv(t,e){if(wa.has(`${t}.${e}`))return wa.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=Ah(fh(n),"bytes"),i=(e?n.substring(`${e}0x`.length):n).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return wa.set(`${t}.${e}`,s),s}function kv(t){const e=Ah(`0x${t.substring(4)}`).substring(26);return Fv(`0x${e}`)}async function Lv({hash:t,signature:e}){const n=oi(t)?t:fa(t),{secp256k1:r}=await Promise.resolve().then(function(){return dE});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:f,yParity:h}=e,d=Number(h??f),p=$h(d);return new r.Signature(ha(u),ha(l)).addRecoveryBit(p)}const o=oi(e)?e:fa(e);if(ua(o)!==65)throw new Error("invalid signature length");const a=cv(`0x${o.slice(130)}`),c=$h(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function $h(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function Mv({hash:t,signature:e}){return kv(await Lv({hash:t,signature:e}))}function jv(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function qv(t,e,n){return t&e^~t&n}function zv(t,e,n){return t&e^t&n^e&n}class Kv extends ga{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=pa(this.buffer)}update(e){Or(this),e=Es(e),vt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=pa(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Or(this),gh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,$r(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;jv(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=pa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const bn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Vv=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),mn=new Uint32Array(64);class Hv extends Kv{constructor(e=32){super(64,e,8,!1),this.A=bn[0]|0,this.B=bn[1]|0,this.C=bn[2]|0,this.D=bn[3]|0,this.E=bn[4]|0,this.F=bn[5]|0,this.G=bn[6]|0,this.H=bn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)mn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const h=mn[f-15],d=mn[f-2],p=jt(h,7)^jt(h,18)^h>>>3,g=jt(d,17)^jt(d,19)^d>>>10;mn[f]=g+mn[f-7]+p+mn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=jt(a,6)^jt(a,11)^jt(a,25),d=l+h+qv(a,c,u)+Vv[f]+mn[f]|0,g=(jt(r,2)^jt(r,13)^jt(r,22))+zv(r,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=r,r=d+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){$r(mn)}destroy(){this.set(0,0,0,0,0,0,0,0),$r(this.buffer)}}const xs=mh(()=>new Hv),ba=BigInt(0),ma=BigInt(1);function Is(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Qn(t,e,n=""){const r=ai(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Ss(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Bh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ba:BigInt("0x"+t)}function er(t){return Bh(Br(t))}function Th(t){return vt(t),Bh(Br(Uint8Array.from(t).reverse()))}function Ds(t,e){return vs(t.toString(16).padStart(e*2,"0"))}function Ph(t,e){return Ds(t,e).reverse()}function me(t,e,n){let r;if(typeof e=="string")try{r=vs(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(ai(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const va=t=>typeof t=="bigint"&&ba<=t;function Ea(t,e,n){return va(t)&&va(e)&&va(n)&&e<=t&&t<n}function Wv(t,e,n,r){if(!Ea(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Rh(t){let e;for(e=0;t>ba;t>>=ma,e+=1);return e}const li=t=>(ma<<BigInt(t))-ma;function Gv(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=d=>new Uint8Array(d),i=d=>Uint8Array.of(d);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...d)=>n(o,s,...d),l=(d=r(0))=>{o=u(i(0),d),s=u(),d.length!==0&&(o=u(i(1),d),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let d=0;const p=[];for(;d<e;){s=u();const g=s.slice();p.push(g),d+=s.length}return Ce(...p)};return(d,p)=>{c(),l(d);let g;for(;!(g=p(f()));)l();return c(),g}}function Zv(t){return typeof t=="function"&&Number.isSafeInteger(t.outputLen)}function As(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function Ch(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Yv="0.1.1";function Xv(){return Yv}class Ge extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof Ge){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof Ge&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
16
+ `);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Xv()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Nh(this,e)}}function Nh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Nh(t.cause,e):e?null:t}function Jv(t,e){if(kh(t)>e)throw new o2({givenSize:kh(t),maxSize:e})}const tn={zero:48,nine:57,A:65,F:70,a:97,f:102};function Uh(t){if(t>=tn.zero&&t<=tn.nine)return t-tn.zero;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function Qv(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new a2({size:t.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=t[o?s:t.length-s-1]}return i}function _a(t,e){if(Ia(t)>e)throw new p2({givenSize:Ia(t),maxSize:e})}function Fh(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const i=t.replace("0x","");if(i.length>r*2)throw new g2({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const e2=new TextEncoder;function t2(t){return t instanceof Uint8Array?t:typeof t=="string"?r2(t):n2(t)}function n2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function r2(t,e={}){const{size:n}=e;let r=t;n&&(_a(t,n),r=xa(t,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Uh(i.charCodeAt(c++)),l=Uh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new Ge(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function i2(t,e={}){const{size:n}=e,r=e2.encode(t);return typeof n=="number"?(Jv(r,n),s2(r,n)):r}function s2(t,e){return Qv(t,{dir:"right",size:e})}function kh(t){return t.length}class o2 extends Ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class a2 extends Ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const c2=new TextEncoder,u2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lh(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function l2(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(_a(n,e.size),Os(n,e.size)):n}function Mh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=u2[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(_a(r,e.size),xa(r,e.size)):r}function h2(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new d2({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:n,size:r,value:`${t}${u}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Os(c,r):c}function f2(t,e={}){return Mh(c2.encode(t),e)}function Os(t,e){return Fh(t,{dir:"left",size:e})}function xa(t,e){return Fh(t,{dir:"right",size:e})}function Ia(t){return Math.ceil((t.length-2)/2)}class d2 extends Ge{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class p2 extends Ge{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class g2 extends Ge{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new Oh(128),da(0,{size:32});function y2(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=Dh(t2(t));return n==="Bytes"?r:Mh(r)}class w2 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Sa={checksum:new w2(8192)}.checksum,b2=/^0x[a-fA-F0-9]{40}$/;function jh(t,e={}){const{strict:n=!0}=e;if(!b2.test(t))throw new qh({address:t,cause:new v2});if(n){if(t.toLowerCase()===t)return;if(m2(t)!==t)throw new qh({address:t,cause:new E2})}}function m2(t){if(Sa.has(t))return Sa.get(t);jh(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=y2(i2(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return Sa.set(t,i),i}class qh extends Ge{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class v2 extends Ge{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class E2 extends Ge{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const _2=/^(.*)\[([0-9]*)\]$/,x2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,I2=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function Da(t,e){if(t.length!==e.length)throw new D2({expectedLength:t.length,givenLength:e.length});const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r];n.push(Da.encode(i,s))}return Lh(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return jh(c),Os(c.toLowerCase(),i?32:0)}if(n==="string")return f2(r);if(n==="bytes")return r;if(n==="bool")return Os(l2(r),i?32:1);const s=n.match(I2);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return h2(r,{size:i?32:f,signed:u==="int"})}const o=n.match(x2);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(r.length-2)/2)throw new S2({expectedSize:Number.parseInt(u,10),value:r});return xa(r,i?32:0)}const a=n.match(_2);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let f=0;f<r.length;f++)l.push(e(u,r[f],!0));return l.length===0?"0x":Lh(...l)}throw new A2(n)}t.encode=e})(Da||(Da={}));class S2 extends Ge{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${Ia(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class D2 extends Ge{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
17
+ `)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class A2 extends Ge{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class zh extends ga{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ph(e);const r=Es(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),$r(s)}update(e){return Or(this),this.iHash.update(e),this}digestInto(e){Or(this),vt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Kh=(t,e,n)=>new zh(t,e).update(n).digest();Kh.create=(t,e)=>new zh(t,e);const nt=BigInt(0),Ze=BigInt(1),tr=BigInt(2),Vh=BigInt(3),Hh=BigInt(4),Wh=BigInt(5),O2=BigInt(7),Gh=BigInt(8),$2=BigInt(9),Zh=BigInt(16);function ut(t,e){const n=t%e;return n>=nt?n:e+n}function Et(t,e,n){let r=t;for(;e-- >nt;)r*=r,r%=n;return r}function Yh(t,e){if(t===nt)throw new Error("invert: expected non-zero number");if(e<=nt)throw new Error("invert: expected positive modulus, got "+e);let n=ut(t,e),r=e,i=nt,s=Ze;for(;n!==nt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==Ze)throw new Error("invert: does not exist");return ut(i,e)}function Aa(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Xh(t,e){const n=(t.ORDER+Ze)/Hh,r=t.pow(e,n);return Aa(t,r,e),r}function B2(t,e){const n=(t.ORDER-Wh)/Gh,r=t.mul(e,tr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,tr),i),a=t.mul(s,t.sub(o,t.ONE));return Aa(t,a,e),a}function T2(t){const e=hi(t),n=Jh(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+O2)/Zh;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),y=a.cmov(u,l,g);return Aa(a,y,c),y}}function Jh(t){if(t<Vh)throw new Error("sqrt is not defined for small field");let e=t-Ze,n=0;for(;e%tr===nt;)e/=tr,n++;let r=tr;const i=hi(t);for(;ef(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Xh;let s=i.pow(r,e);const o=(e+Ze)/tr;return function(c,u){if(c.is0(u))return u;if(ef(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),h=c.pow(u,e),d=c.pow(u,o);for(;!c.eql(h,c.ONE);){if(c.is0(h))return c.ZERO;let p=1,g=c.sqr(h);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const y=Ze<<BigInt(l-p-1),I=c.pow(f,y);l=p,f=c.sqr(I),h=c.mul(h,f),d=c.mul(d,I)}return d}}function P2(t){return t%Hh===Vh?Xh:t%Gh===Wh?B2:t%Zh===$2?T2(t):Jh(t)}const R2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qh(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=R2.reduce((r,i)=>(r[i]="function",r),e);return As(t,n),t}function C2(t,e,n){if(n<nt)throw new Error("invalid exponent, negatives unsupported");if(n===nt)return t.ONE;if(n===Ze)return e;let r=t.ONE,i=e;for(;n>nt;)n&Ze&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ze;return r}function $s(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function ef(t,e){const n=(t.ORDER-Ze)/tr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function tf(t,e){e!==void 0&&ci(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function hi(t,e,n=!1,r={}){if(t<=nt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=tf(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:li(c),ZERO:nt,ONE:Ze,allowedLengths:a,create:h=>ut(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return nt<=h&&h<t},is0:h=>h===nt,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ze)===Ze,neg:h=>ut(-h,t),eql:(h,d)=>h===d,sqr:h=>ut(h*h,t),add:(h,d)=>ut(h+d,t),sub:(h,d)=>ut(h-d,t),mul:(h,d)=>ut(h*d,t),pow:(h,d)=>C2(f,h,d),div:(h,d)=>ut(h*Yh(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>Yh(h,t),sqrt:s||(h=>(l||(l=P2(t)),l(f,h))),toBytes:h=>n?Ph(h,u):Ds(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=n?Th(h):er(h);if(o&&(p=ut(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>$s(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function nf(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 rf(t){const e=nf(t);return e+Math.ceil(e/2)}function sf(t,e,n=!1){const r=t.length,i=nf(e),s=rf(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Th(t):er(t),a=ut(o,e-Ze)+Ze;return n?Ph(a,i):Ds(a,i)}const Pr=BigInt(0),nr=BigInt(1);function Bs(t,e){const n=e.negate();return t?n:e}function Oa(t,e){const n=$s(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function of(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $a(t,e){of(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=li(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function af(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=nr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function N2(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 U2(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ba=new WeakMap,cf=new WeakMap;function Ta(t){return cf.get(t)||1}function uf(t){if(t!==Pr)throw new Error("invalid wNAF")}class F2{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>Pr;)n&nr&&(r=r.add(i)),i=i.double(),n>>=nr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=$a(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=$a(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=af(r,a,o);r=c,l?s=s.add(Bs(h,n[d])):i=i.add(Bs(f,n[u]))}return uf(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=$a(e,this.bits);for(let o=0;o<s.windows&&r!==Pr;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=af(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return uf(r),i}getPrecomputes(e,n,r){let i=Ba.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Ba.set(n,i))),i}cached(e,n,r){const i=Ta(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Ta(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){of(n,this.bits),cf.set(e,n),Ba.delete(e)}hasCache(e){return Ta(e)!==1}}function k2(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Pr||r>Pr;)n&nr&&(s=s.add(i)),r&nr&&(o=o.add(i)),i=i.double(),n>>=nr,r>>=nr;return{p1:s,p2:o}}function L2(t,e,n,r){N2(n,t),U2(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Rh(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=li(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],I=Number(y>>BigInt(d)&u);l[I]=l[I].add(n[g])}let p=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),p=p.add(y);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function lf(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Qh(e),e}else return hi(t,{isLE:n})}function M2(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const c of["p","n","h"]){const u=e[c];if(!(typeof u=="bigint"&&u>Pr))throw new Error(`CURVE.${c} must be positive bigint`)}const i=lf(e.p,n.Fp,r),s=lf(e.n,n.Fn,r),a=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const c of a)if(!i.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}const hf=(t,e)=>(t+(t>=0?e:-e)/qt)/e;function j2(t,e,n){const[[r,i],[s,o]]=e,a=hf(o*t,n),c=hf(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<Tt,h=l<Tt;f&&(u=-u),h&&(l=-l);const d=li(Math.ceil(Rh(n)/2))+Ne;if(u<Tt||u>=d||l<Tt||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Pa(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Ra(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return Is(n.lowS,"lowS"),Is(n.prehash,"prehash"),n.format!==void 0&&Pa(n.format),n}class q2 extends Error{constructor(e=""){super(e)}}const nn={Err:q2,_tlv:{encode:(t,e)=>{const{Err:n}=nn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Ss(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Ss(i.length/2|128):"";return Ss(t)+s+i+e},decode(t,e){const{Err:n}=nn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=nn;if(t<Tt)throw new e("integer: negative integers are not allowed");let n=Ss(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=nn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return er(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=nn,i=me("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=nn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Tt=BigInt(0),Ne=BigInt(1),qt=BigInt(2),Rr=BigInt(3),Ca=BigInt(4);function rr(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=me("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function z2(t,e={}){const n=M2("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;As(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=df(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:w,y:b}=v.toAffine(),x=r.toBytes(w);if(Is(m,"isCompressed"),m){l();const A=!r.isOdd(b);return Ce(ff(A),x)}else return Ce(Uint8Array.of(4),x,r.toBytes(b))}function h(P){Qn(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,w=P.length,b=P[0],x=P.subarray(1);if(w===v&&(b===2||b===3)){const A=r.fromBytes(x);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const _=g(A);let S;try{S=r.sqrt(_)}catch(q){const L=q instanceof Error?": "+q.message:"";throw new Error("bad point: is not on curve, sqrt error"+L)}l();const B=r.isOdd(S);return(b&1)===1!==B&&(S=r.neg(S)),{x:A,y:S}}else if(w===m&&b===4){const A=r.BYTES,_=r.fromBytes(x.subarray(0,A)),S=r.fromBytes(x.subarray(A,A*2));if(!y(_,S))throw new Error("bad point: is not on curve");return{x:_,y:S}}else throw new Error(`bad point: got length ${w}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=r.sqr(P),m=r.mul(v,P);return r.add(r.add(m,r.mul(P,s.a)),s.b)}function y(P,v){const m=r.sqr(v),w=g(P);return r.eql(m,w)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=r.mul(r.pow(s.a,Rr),Ca),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(I,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!r.isValid(v)||m&&r.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function $(P){if(!(P instanceof O))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return j2(P,c.basises,i.ORDER)}const C=Ch((P,v)=>{const{X:m,Y:w,Z:b}=P;if(r.eql(b,r.ONE))return{x:m,y:w};const x=P.is0();v==null&&(v=x?r.ONE:r.inv(b));const A=r.mul(m,v),_=r.mul(w,v),S=r.mul(b,v);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),U=Ch(P=>{if(P.is0()){if(e.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!r.isValid(v)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,w,b){return m=new O(r.mul(m.X,P),m.Y,m.Z),v=Bs(w,v),m=Bs(b,m),v.add(m)}class O{constructor(v,m,w){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",w),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y:w}=v||{};if(!v||!r.isValid(m)||!r.isValid(w))throw new Error("invalid affine point");if(v instanceof O)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(w)?O.ZERO:new O(m,w,r.ONE)}static fromBytes(v){const m=O.fromAffine(p(Qn(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return O.fromBytes(me("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(Rr),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v,S=r.eql(r.mul(m,_),r.mul(x,b)),B=r.eql(r.mul(w,_),r.mul(A,b));return S&&B}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,w=r.mul(m,Rr),{X:b,Y:x,Z:A}=this;let _=r.ZERO,S=r.ZERO,B=r.ZERO,T=r.mul(b,b),q=r.mul(x,x),L=r.mul(A,A),k=r.mul(b,x);return k=r.add(k,k),B=r.mul(b,A),B=r.add(B,B),_=r.mul(v,B),S=r.mul(w,L),S=r.add(_,S),_=r.sub(q,S),S=r.add(q,S),S=r.mul(_,S),_=r.mul(k,_),B=r.mul(w,B),L=r.mul(v,L),k=r.sub(T,L),k=r.mul(v,k),k=r.add(k,B),B=r.add(T,T),T=r.add(B,T),T=r.add(T,L),T=r.mul(T,k),S=r.add(S,T),L=r.mul(x,A),L=r.add(L,L),T=r.mul(L,k),_=r.sub(_,T),B=r.mul(L,q),B=r.add(B,B),B=r.add(B,B),new O(_,S,B)}add(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v;let S=r.ZERO,B=r.ZERO,T=r.ZERO;const q=s.a,L=r.mul(s.b,Rr);let k=r.mul(m,x),z=r.mul(w,A),H=r.mul(b,_),Z=r.add(m,w),V=r.add(x,A);Z=r.mul(Z,V),V=r.add(k,z),Z=r.sub(Z,V),V=r.add(m,b);let Y=r.add(x,_);return V=r.mul(V,Y),Y=r.add(k,H),V=r.sub(V,Y),Y=r.add(w,b),S=r.add(A,_),Y=r.mul(Y,S),S=r.add(z,H),Y=r.sub(Y,S),T=r.mul(q,V),S=r.mul(L,H),T=r.add(S,T),S=r.sub(z,T),T=r.add(z,T),B=r.mul(S,T),z=r.add(k,k),z=r.add(z,k),H=r.mul(q,H),V=r.mul(L,V),z=r.add(z,H),H=r.sub(k,H),H=r.mul(q,H),V=r.add(V,H),k=r.mul(z,V),B=r.add(B,k),k=r.mul(Y,V),S=r.mul(Z,S),S=r.sub(S,k),k=r.mul(Z,z),T=r.mul(Y,T),T=r.add(T,k),new O(S,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals(O.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let w,b;const x=A=>W.cached(this,A,_=>Oa(O,_));if(m){const{k1neg:A,k1:_,k2neg:S,k2:B}=R(v),{p:T,f:q}=x(_),{p:L,f:k}=x(B);b=q.add(k),w=N(m.beta,T,L,A,S)}else{const{p:A,f:_}=x(v);w=A,b=_}return Oa(O,[w,b])[0]}multiplyUnsafe(v){const{endo:m}=e,w=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===Tt||w.is0())return O.ZERO;if(v===Ne)return w;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:x,k2neg:A,k2:_}=R(v),{p1:S,p2:B}=k2(O,w,x,_);return N(m.beta,S,B,b,A)}else return W.unsafe(w,v)}multiplyAndAddUnsafe(v,m,w){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(w));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===Ne?!0:v?v(O,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===Ne?this:v?v(O,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return Is(v,"isCompressed"),this.assertValidity(),d(O,this,v)}toHex(v=!0){return Br(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return Oa(O,v)}static msm(v,m){return L2(O,i,v,m)}static fromPrivateKey(v){return O.BASE.multiply(rr(i,v))}}O.BASE=new O(s.Gx,s.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=i;const G=i.BITS,W=new F2(O,e.endo?Math.ceil(G/2):G);return O.BASE.precompute(8),O}function ff(t){return Uint8Array.of(t?2:3)}function K2(t,e){const n=t.ORDER;let r=Tt;for(let p=n-Ne;p%qt===Tt;p/=qt)r+=Ne;const i=r,s=qt<<i-Ne-Ne,o=s*qt,a=(n-Ne)/o,c=(a-Ne)/qt,u=o-Ne,l=s,f=t.pow(e,a),h=t.pow(e,(a+Ne)/qt);let d=(p,g)=>{let y=f,I=t.pow(g,u),D=t.sqr(I);D=t.mul(D,g);let E=t.mul(p,D);E=t.pow(E,c),E=t.mul(E,I),I=t.mul(E,g),D=t.mul(E,p);let $=t.mul(D,I);E=t.pow($,l);let R=t.eql(E,t.ONE);I=t.mul(D,h),E=t.mul($,y),D=t.cmov(I,D,R),$=t.cmov(E,$,R);for(let C=i;C>Ne;C--){let U=C-qt;U=qt<<U-Ne;let N=t.pow($,U);const O=t.eql(N,t.ONE);I=t.mul(D,y),y=t.mul(y,y),N=t.mul($,y),D=t.cmov(I,D,O),$=t.cmov(N,$,O)}return{isValid:R,value:D}};if(t.ORDER%Ca===Rr){const p=(t.ORDER-Rr)/Ca,g=t.sqrt(t.neg(e));d=(y,I)=>{let D=t.sqr(I);const E=t.mul(y,I);D=t.mul(D,E);let $=t.pow(D,p);$=t.mul($,E);const R=t.mul($,g),C=t.mul(t.sqr($),I),U=t.eql(C,y);let N=t.cmov(R,$,U);return{isValid:U,value:N}}}return d}function V2(t,e){Qh(t);const{A:n,B:r,Z:i}=e;if(!t.isValid(n)||!t.isValid(r)||!t.isValid(i))throw new Error("mapToCurveSimpleSWU: invalid opts");const s=K2(t,i);if(!t.isOdd)throw new Error("Field does not have .isOdd()");return o=>{let a,c,u,l,f,h,d,p;a=t.sqr(o),a=t.mul(a,i),c=t.sqr(a),c=t.add(c,a),u=t.add(c,t.ONE),u=t.mul(u,r),l=t.cmov(i,t.neg(c),!t.eql(c,t.ZERO)),l=t.mul(l,n),c=t.sqr(u),h=t.sqr(l),f=t.mul(h,n),c=t.add(c,f),c=t.mul(c,u),h=t.mul(h,l),f=t.mul(h,r),c=t.add(c,f),d=t.mul(a,u);const{isValid:g,value:y}=s(c,h);p=t.mul(a,o),p=t.mul(p,y),d=t.cmov(d,u,g),p=t.cmov(p,y,g);const I=t.isOdd(o)===t.isOdd(p);p=t.cmov(t.neg(p),p,I);const D=$s(t,[l],!0)[0];return d=t.mul(d,D),{x:d,y:p}}}function df(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function H2(t,e={}){const{Fn:n}=t,r=e.randomBytes||_s,i=Object.assign(df(t.Fp,n),{seed:rf(n.ORDER)});function s(d){try{return!!rr(n,d)}catch{return!1}}function o(d,p){const{publicKey:g,publicKeyUncompressed:y}=i;try{const I=d.length;return p===!0&&I!==g||p===!1&&I!==y?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=r(i.seed)){return sf(Qn(d,i.seed,"seed"),n.ORDER)}function c(d,p=!0){return t.BASE.multiply(rr(n,d)).toBytes(p)}function u(d){const p=a(d);return{secretKey:p,publicKey:c(p)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:y}=i;if(n.allowedLengths||p===g)return;const I=me("key",d).length;return I===g||I===y}function f(d,p,g=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const y=rr(n,d);return t.fromHex(p).multiply(y).toBytes(g)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:d=>rr(n,d),precompute(d=8,p=t.BASE){return p.precompute(d,!1)}},lengths:i})}function W2(t,e,n={}){ph(e),As(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||_s,i=n.hmac||((m,...w)=>Kh(e,m,Ce(...w))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=H2(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(m){const w=a>>Ne;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function D(m,w){Pa(w);const b=d.signature,x=w==="compact"?b:w==="recovered"?b+1:void 0;return Qn(m,x,`${w} signature`)}class E{constructor(w,b,x){this.r=I("r",w),this.s=I("s",b),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(w,b=g){D(w,b);let x;if(b==="der"){const{r:B,s:T}=nn.toSig(Qn(w));return new E(B,T)}b==="recovered"&&(x=w[0],b="compact",w=w.subarray(1));const A=o.BYTES,_=w.subarray(0,A),S=w.subarray(A,A*2);return new E(o.fromBytes(_),o.fromBytes(S),x)}static fromHex(w,b){return this.fromBytes(vs(w),b)}addRecoveryBit(w){return new E(this.r,this.s,w)}recoverPublicKey(w){const b=s.ORDER,{r:x,s:A,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*qt<b&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const B=_===2||_===3?x+a:x;if(!s.isValid(B))throw new Error("recovery id 2 or 3 invalid");const T=s.toBytes(B),q=t.fromBytes(Ce(ff((_&1)===0),T)),L=o.inv(B),k=R(me("msgHash",w)),z=o.create(-k*L),H=o.create(A*L),Z=t.BASE.multiplyUnsafe(z).add(q.multiplyUnsafe(H));if(Z.is0())throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return y(this.s)}toBytes(w=g){if(Pa(w),w==="der")return vs(nn.hexFromSig(this));const b=o.toBytes(this.r),x=o.toBytes(this.s);if(w==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ce(Uint8Array.of(this.recovery),b,x)}return Ce(b,x)}toHex(w){return Br(this.toBytes(w))}assertValidity(){}static fromCompact(w){return E.fromBytes(me("sig",w),"compact")}static fromDER(w){return E.fromBytes(me("sig",w),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Br(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Br(this.toBytes("compact"))}}const $=n.bits2int||function(w){if(w.length>8192)throw new Error("input is too large");const b=er(w),x=w.length*8-c;return x>0?b>>BigInt(x):b},R=n.bits2int_modN||function(w){return o.create($(w))},C=li(c);function U(m){return Wv("num < 2^"+c,m,Tt,C),o.toBytes(m)}function N(m,w){return Qn(m,void 0,"message"),w?Qn(e(m),void 0,"prehashed message"):m}function O(m,w,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:A,extraEntropy:_}=Ra(b,p);m=N(m,A);const S=R(m),B=rr(o,w),T=[U(B),U(S)];if(_!=null&&_!==!1){const z=_===!0?r(d.secretKey):_;T.push(me("extraEntropy",z))}const q=Ce(...T),L=S;function k(z){const H=$(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===Tt)return;const he=o.create(Z*o.create(L+Y*B));if(he===Tt)return;let Ke=(V.x===Y?0:2)|Number(V.y&Ne),mt=he;return x&&y(he)&&(mt=o.neg(he),Ke^=1),new E(Y,mt,Ke)}return{seed:q,k2sig:k}}function G(m,w,b={}){m=me("message",m);const{seed:x,k2sig:A}=O(m,w,b);return Gv(e.outputLen,o.BYTES,i)(x,A)}function W(m){let w;const b=typeof m=="string"||ai(m),x=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)w=new E(m.r,m.s);else if(b){try{w=E.fromBytes(me("sig",m),"der")}catch(A){if(!(A instanceof nn.Err))throw A}if(!w)try{w=E.fromBytes(me("sig",m),"compact")}catch{return!1}}return w||!1}function P(m,w,b,x={}){const{lowS:A,prehash:_,format:S}=Ra(x,p);if(b=me("publicKey",b),w=N(me("message",w),_),"strict"in x)throw new Error("options.strict was renamed to lowS");const B=S===void 0?W(m):E.fromBytes(me("sig",m),S);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:q,s:L}=B,k=R(w),z=o.inv(L),H=o.create(k*z),Z=o.create(q*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===q}catch{return!1}}function v(m,w,b={}){const{prehash:x}=Ra(b,p);return w=N(w,x),E.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function G2(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=hi(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function Z2(t){const{CURVE:e,curveOpts:n}=G2(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 Y2(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,tf(n.Fn.ORDER,n.Fn.BITS))})}function X2(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Z2(t),s=z2(e,n),o=W2(s,r,i);return Y2(t,o)}function J2(t,e){const n=r=>X2({...t,hash:r});return{...n(e),create:n}}const Q2=er;function vn(t,e){if(fi(t),fi(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function eE(t,e){const n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function fi(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function pf(t){if(!ai(t)&&typeof t!="string")throw new Error("DST must be Uint8Array or string");return typeof t=="string"?Tr(t):t}function tE(t,e,n,r){vt(t),fi(n),e=pf(e),e.length>255&&(e=r(Ce(Tr("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=Ce(e,vn(e.length,1)),c=vn(0,s),u=vn(n,2),l=new Array(o),f=r(Ce(c,t,u,vn(0,1),a));l[0]=r(Ce(f,vn(1,1),a));for(let d=1;d<=o;d++){const p=[eE(f,l[d-1]),vn(d+1,1),a];l[d]=r(Ce(...p))}return Ce(...l).slice(0,n)}function nE(t,e,n,r,i){if(vt(t),fi(n),e=pf(e),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(Tr("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(t).update(vn(n,2)).update(e).update(vn(e.length,1)).digest()}function Na(t,e,n){As(n,{p:"bigint",m:"number",k:"number",hash:"function"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;if(!Zv(n.hash))throw new Error("expected valid hash");vt(t),fi(e);const u=r.toString(2).length,l=Math.ceil((u+i)/8),f=e*s*l;let h;if(a==="xmd")h=tE(t,c,f,o);else if(a==="xof")h=nE(t,c,f,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let p=0;p<e;p++){const g=new Array(s);for(let y=0;y<s;y++){const I=l*(y+p*s),D=h.subarray(I,I+l);g[y]=ut(Q2(D),r)}d[p]=g}return d}function rE(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(f=>f.reduce((h,d)=>t.add(t.mul(h,r),d))),[u,l]=$s(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}const iE=Tr("HashToScalar-");function sE(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const a=Object.assign({},n,o),c=Na(s,2,a),u=r(c[0]),l=r(c[1]);return i(u.add(l))},encodeToCurve(s,o){const a=n.encodeDST?{DST:n.encodeDST}:{},c=Object.assign({},n,a,o),u=Na(s,1,c),l=r(u[0]);return i(l)},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))},hashToScalar(s,o){const a=t.Fn.ORDER,c=Object.assign({},n,{p:a,m:1,DST:iE},o);return Na(s,1,c)[0][0]}}}const Cr={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},oE={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},aE=BigInt(0),gf=BigInt(1),Ua=BigInt(2);function cE(t){const e=Cr.p,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,f=Et(l,n,e)*l%e,h=Et(f,n,e)*l%e,d=Et(h,Ua,e)*u%e,p=Et(d,i,e)*d%e,g=Et(p,s,e)*p%e,y=Et(g,a,e)*g%e,I=Et(y,c,e)*y%e,D=Et(I,a,e)*g%e,E=Et(D,n,e)*l%e,$=Et(E,o,e)*p%e,R=Et($,r,e)*u%e,C=Et(R,Ua,e);if(!rn.eql(rn.sqr(C),t))throw new Error("Cannot find square root");return C}const rn=hi(Cr.p,{sqrt:cE}),Ts=J2({...Cr,Fp:rn,lowS:!0,endo:oE},xs),yf={};function Ps(t,...e){let n=yf[t];if(n===void 0){const r=xs(Tr(t));n=Ce(r,r),yf[t]=n}return xs(Ce(n,...e))}const Fa=t=>t.toBytes(!0).slice(1),Nr=Ts.Point,ka=t=>t%Ua===aE;function La(t){const{Fn:e,BASE:n}=Nr,r=rr(e,t),i=n.multiply(r);return{scalar:ka(i.y)?r:e.neg(r),bytes:Fa(i)}}function wf(t){const e=rn;if(!e.isValidNot0(t))throw new Error("invalid x: Fail if x \u2265 p");const n=e.create(t*t),r=e.create(n*t+BigInt(7));let i=e.sqrt(r);ka(i)||(i=e.neg(i));const s=Nr.fromAffine({x:t,y:i});return s.assertValidity(),s}const di=er;function bf(...t){return Nr.Fn.create(di(Ps("BIP0340/challenge",...t)))}function mf(t){return La(t).bytes}function uE(t,e,n=_s(32)){const{Fn:r}=Nr,i=me("message",t),{bytes:s,scalar:o}=La(e),a=me("auxRand",n,32),c=r.toBytes(o^di(Ps("BIP0340/aux",a))),u=Ps("BIP0340/nonce",c,s,i),{bytes:l,scalar:f}=La(u),h=bf(l,s,i),d=new Uint8Array(64);if(d.set(l,0),d.set(r.toBytes(r.create(f+h*o)),32),!vf(d,i,s))throw new Error("sign: Invalid signature produced");return d}function vf(t,e,n){const{Fn:r,BASE:i}=Nr,s=me("signature",t,64),o=me("message",e),a=me("publicKey",n,32);try{const c=wf(di(a)),u=di(s.subarray(0,32));if(!Ea(u,gf,Cr.p))return!1;const l=di(s.subarray(32,64));if(!Ea(l,gf,Cr.n))return!1;const f=bf(r.toBytes(u),Fa(c),o),h=i.multiplyUnsafe(l).add(c.multiplyUnsafe(r.neg(f))),{x:d,y:p}=h.toAffine();return!(h.is0()||!ka(p)||d!==u)}catch{return!1}}const lE=(()=>{const n=(i=_s(48))=>sf(i,Cr.n);Ts.utils.randomSecretKey;function r(i){const s=n(i);return{secretKey:s,publicKey:mf(s)}}return{keygen:r,getPublicKey:mf,sign:uE,verify:vf,Point:Nr,utils:{randomSecretKey:n,randomPrivateKey:n,taggedHash:Ps,lift_x:wf,pointToBytes:Fa,numberToBytesBE:Ds,bytesToNumberBE:er,mod:ut},lengths:{secretKey:32,publicKey:32,publicKeyHasPrefix:!1,signature:32*2,seed:48}}})(),hE=rE(rn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),fE=V2(rn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:rn.create(BigInt("-11"))}),Ma=sE(Ts.Point,t=>{const{x:e,y:n}=fE(rn.create(t[0]));return hE(e,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:rn.ORDER,m:1,k:128,expand:"xmd",hash:xs});var dE=Object.freeze({__proto__:null,secp256k1:Ts,schnorr:lE,secp256k1_hasher:Ma,hashToCurve:Ma.hashToCurve,encodeToCurve:Ma.encodeToCurve});function pE(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),f=l.charCodeAt(0);if(e[f]!==255)throw new TypeError(l+" is ambiguous");e[f]=u}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,f=0,h=0;const d=u.length;for(;h!==d&&u[h]===0;)h++,l++;const p=(d-h)*s+1>>>0,g=new Uint8Array(p);for(;h!==d;){let D=u[h],E=0;for(let $=p-1;(D!==0||E<f)&&$!==-1;$--,E++)D+=256*g[$]>>>0,g[$]=D%n>>>0,D=D/n>>>0;if(D!==0)throw new Error("Non-zero carry");f=E,h++}let y=p-f;for(;y!==p&&g[y]===0;)y++;let I=r.repeat(l);for(;y<p;++y)I+=t.charAt(g[y]);return I}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,h=0;for(;u[l]===r;)f++,l++;const d=(u.length-l)*i+1>>>0,p=new Uint8Array(d);for(;l<u.length;){const D=u.charCodeAt(l);if(D>255)return;let E=e[D];if(E===255)return;let $=0;for(let R=d-1;(E!==0||$<h)&&R!==-1;R--,$++)E+=n*p[R]>>>0,p[R]=E%256>>>0,E=E/256>>>0;if(E!==0)throw new Error("Non-zero carry");h=$,l++}let g=d-h;for(;g!==d&&p[g]===0;)g++;const y=new Uint8Array(f+(d-g));let I=f;for(;g!==d;)y[I++]=p[g++];return y}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var gE="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",pi=pE(gE);function yE(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function wE(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if((o&4294967168)===0){e[i++]=o;continue}else if((o&4294965248)===0)e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128):(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128)}e[i++]=o&63|128}}const bE=new TextEncoder,mE=50;function vE(t,e,n){bE.encodeInto(t,e.subarray(n))}function EE(t,e,n){t.length>mE?vE(t,e,n):wE(t,e,n)}const _E=4096;function Ef(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const a=t[r++];if((a&128)===0)s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,l=t[r++]&63;let f=(a&7)<<18|c<<12|u<<6|l;f>65535&&(f-=65536,s.push(f>>>10&1023|55296),f=56320|f&1023),s.push(f)}else s.push(a);s.length>=_E&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const xE=new TextDecoder,IE=200;function SE(t,e,n){const r=t.subarray(e,e+n);return xE.decode(r)}function DE(t,e,n){return n>IE?SE(t,e,n):Ef(t,e,n)}class Rs{constructor(e,n){this.type=e,this.data=n}}class lt extends Error{constructor(e){super(e);const n=Object.create(lt.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:lt.name})}}const gi=4294967295;function AE(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function _f(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function xf(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function OE(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const $E=-1,BE=4294967296-1,TE=17179869184-1;function PE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=TE)if(e===0&&t<=BE){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),_f(r,4,t),n}}function RE(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function CE(t){if(t instanceof Date){const e=RE(t);return PE(e)}else return null}function NE(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=xf(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new lt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function UE(t){const e=NE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const FE={type:$E,encode:CE,decode:UE};class Cs{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(FE)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new Rs(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new Rs(o,s)}}}return e instanceof Rs?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new Rs(n,e)}}Cs.defaultCodec=new Cs;function kE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function ja(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):kE(t)?new Uint8Array(t):Uint8Array.from(t)}const LE=100,ME=2048;class qa{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Cs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??LE,this.initialBufferSize=e?.initialBufferSize??ME,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new qa({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=yE(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),EE(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=ja(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),AE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),_f(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 jE(t,e){return new qa(e).encodeSharedRef(t)}function za(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const qE=16,zE=16;class KE{constructor(e=qE,n=zE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=Ef(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Ka="array",yi="map_key",If="map_value",VE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new lt("The type of key must be string or number but "+typeof t)};class HE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Ka,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=yi,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ka){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===yi||e.type===If){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const wi=-1,Va=new DataView(new ArrayBuffer(0)),WE=new Uint8Array(Va.buffer);try{Va.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const Sf=new RangeError("Insufficient data"),GE=new KE;class Ha{constructor(e){this.totalPos=0,this.pos=0,this.view=Va,this.bytes=WE,this.headByte=wi,this.stack=new HE,this.entered=!1,this.extensionCodec=e?.extensionCodec??Cs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??gi,this.maxBinLength=e?.maxBinLength??gi,this.maxArrayLength=e?.maxArrayLength??gi,this.maxMapLength=e?.maxMapLength??gi,this.maxExtLength=e?.maxExtLength??gi,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:GE,this.mapKeyConverter=e?.mapKeyConverter??VE}clone(){return new Ha({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=wi,this.stack.reset()}setBuffer(e){const n=ja(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===wi&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=ja(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${za(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new lt(`Unrecognized type byte: ${za(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Ka)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===yi){if(n==="__proto__")throw new lt("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=If;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=yi;continue e}}return n}}readHeadByte(){return this.headByte===wi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=wi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new lt(`Unrecognized array type byte: ${za(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new lt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new lt(`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 lt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Sf;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=DE(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===yi:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new lt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Sf;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new lt(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=OE(this.view,this.pos);return this.pos+=8,e}readI64(){const e=xf(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 ZE(t,e){return new Ha(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ns(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Wa(t,...e){if(!Ns(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Df(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 Af(t){if(typeof t!="function")throw new Error("function expected");return!0}function En(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function bi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Us(t){if(!Array.isArray(t))throw new Error("array expected")}function Fs(t,e){if(!Df(!0,e))throw new Error(`${t}: array of strings expected`)}function Ga(t,e){if(!Df(!1,e))throw new Error(`${t}: array of numbers expected`)}function ht(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function ft(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Fs("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Us(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Us(i),i.map(s=>{En("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function dt(t=""){return En("join",t),{encode:e=>(Fs("join.decode",e),e.join(t)),decode:e=>(En("join.decode",e),e.split(t))}}function ks(t,e="="){return bi(t),En("padding",e),{encode(n){for(Fs("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Fs("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function Of(t){return Af(t),{encode:e=>e,decode:e=>t(e)}}function $f(t,e,n){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Us(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(bi(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=r;u<o;u++){const l=s[u],f=e*a,h=f+l;if(!Number.isSafeInteger(h)||f/e!==a||h-l!==f)throw new Error("convertRadix: carry overflow");const d=h/n;a=h%n;const p=Math.floor(d);if(s[u]=p,!Number.isSafeInteger(p)||p*n+a!==h)throw new Error("convertRadix: carry overflow");if(c)p?c=!1:r=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const Bf=(t,e)=>e===0?t:Bf(e,t%e),Ls=(t,e)=>t+(e-Bf(t,e)),Ms=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Za(t,e,n,r){if(Us(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Ls(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Ls(e,n)}`);let i=0,s=0;const o=Ms[e],a=Ms[n]-1,c=[];for(const u of t){if(bi(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const l=Ms[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function YE(t){bi(t);const e=2**8;return{encode:n=>{if(!Ns(n))throw new Error("radix.encode input should be Uint8Array");return $f(Array.from(n),e,t)},decode:n=>(Ga("radix.decode",n),Uint8Array.from($f(n,t,e)))}}function _t(t,e=!1){if(bi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Ls(8,t)>32||Ls(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Ns(n))throw new Error("radix2.encode input should be Uint8Array");return Za(Array.from(n),8,t,!e)},decode:n=>(Ga("radix2.decode",n),Uint8Array.from(Za(n,t,8,e)))}}function Tf(t){return Af(t),function(...e){try{return t.apply(null,e)}catch{}}}const XE=ht(_t(5),ft("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ks(5),dt("")),Pf=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Rf=(t,e)=>{En("base64",t);const n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Ya=t=>ht(YE(58),ft(t),dt("")),Xa=ht(ft("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),dt("")),Cf=[996825010,642813549,513874426,1027748829,705979059];function mi(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Cf.length;r++)(e>>r&1)===1&&(n^=Cf[r]);return n}function Nf(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=mi(i)^o>>5}i=mi(i);for(let s=0;s<r;s++)i=mi(i)^t.charCodeAt(s)&31;for(let s of e)i=mi(i)^s;for(let s=0;s<6;s++)i=mi(i);return i^=n,Xa.encode(Za([i%Ms[30]],30,5,!1))}function Uf(t){const e=t==="bech32"?1:734539939,n=_t(5),r=n.decode,i=n.encode,s=Tf(r);function o(f,h,d=90){En("bech32.encode prefix",f),Ns(h)&&(h=Array.from(h)),Ga("bech32.encode",h);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+h.length;if(d!==!1&&g>d)throw new TypeError(`Length ${g} exceeds limit ${d}`);const y=f.toLowerCase(),I=Nf(y,h,e);return`${y}1${Xa.encode(h)}${I}`}function a(f,h=90){En("bech32.decode input",f);const d=f.length;if(d<8||h!==!1&&d>h)throw new TypeError(`invalid string length: ${d} (${f}). Expected (8..${h})`);const p=f.toLowerCase();if(f!==p&&f!==f.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=p.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=p.slice(0,g),I=p.slice(g+1);if(I.length<6)throw new Error("Data must be at least 6 characters long");const D=Xa.decode(I).slice(0,-6),E=Nf(y,D,e);if(!I.endsWith(E))throw new Error(`Invalid checksum in ${f}: expected "${E}"`);return{prefix:y,words:D}}const c=Tf(a);function u(f){const{prefix:h,words:d}=a(f,!1);return{prefix:h,words:d,bytes:r(d)}}function l(f,h){return o(f,i(h))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const JE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",QE={encode(t){return Wa(t),t.toHex()},decode(t){return En("hex",t),Uint8Array.fromHex(t)}};function Ja(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Ff(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ja(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function vi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Ff(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Ja(n)}function e3(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var t3=e3,n3=t3;const kf=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")},r3=t=>new TextEncoder().encode(t),i3=t=>new TextDecoder().decode(t);class s3{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class o3{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 Lf(this,e)}}class a3{constructor(e){this.decoders=e}or(e){return Lf(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 Lf=(t,e)=>new a3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class c3{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new s3(e,n,r),this.decoder=new o3(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const js=({name:t,prefix:e,encode:n,decode:r})=>new c3(t,e,n,r),Ei=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=n3(n,e);return js({prefix:t,name:e,encode:r,decode:s=>kf(i(s))})},u3=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},l3=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Ae=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>js({prefix:e,name:t,encode(i){return l3(i,r,n)},decode(i){return u3(i,r,n,t)}}),h3=js({prefix:"\0",name:"identity",encode:t=>i3(t),decode:t=>r3(t)});var f3=Object.freeze({__proto__:null,identity:h3});const d3=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var p3=Object.freeze({__proto__:null,base2:d3});const g3=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var y3=Object.freeze({__proto__:null,base8:g3});const w3=Ei({prefix:"9",name:"base10",alphabet:"0123456789"});var b3=Object.freeze({__proto__:null,base10:w3});const m3=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),v3=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var E3=Object.freeze({__proto__:null,base16:m3,base16upper:v3});const _3=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),x3=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),I3=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),S3=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),D3=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),A3=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),O3=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),$3=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),B3=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var T3=Object.freeze({__proto__:null,base32:_3,base32upper:x3,base32pad:I3,base32padupper:S3,base32hex:D3,base32hexupper:A3,base32hexpad:O3,base32hexpadupper:$3,base32z:B3});const P3=Ei({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),R3=Ei({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var C3=Object.freeze({__proto__:null,base36:P3,base36upper:R3});const N3=Ei({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),U3=Ei({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var F3=Object.freeze({__proto__:null,base58btc:N3,base58flickr:U3});const k3=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),L3=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),M3=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),j3=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var q3=Object.freeze({__proto__:null,base64:k3,base64pad:L3,base64url:M3,base64urlpad:j3});const Mf=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}"),z3=Mf.reduce((t,e,n)=>(t[n]=e,t),[]),K3=Mf.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function V3(t){return t.reduce((e,n)=>(e+=z3[n],e),"")}function H3(t){const e=[];for(const n of t){const r=K3[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const W3=js({prefix:"\u{1F680}",name:"base256emoji",encode:V3,decode:H3});var G3=Object.freeze({__proto__:null,base256emoji:W3}),Z3=qf,jf=128,Y3=127,X3=~Y3,J3=Math.pow(2,31);function qf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=J3;)e[n++]=t&255|jf,t/=128;for(;t&X3;)e[n++]=t&255|jf,t>>>=7;return e[n]=t|0,qf.bytes=n-r+1,e}var Q3=Qa,e_=128,zf=127;function Qa(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&zf)<<i:(o&zf)*Math.pow(2,i),i+=7}while(o>=e_);return Qa.bytes=s-r,n}var t_=Math.pow(2,7),n_=Math.pow(2,14),r_=Math.pow(2,21),i_=Math.pow(2,28),s_=Math.pow(2,35),o_=Math.pow(2,42),a_=Math.pow(2,49),c_=Math.pow(2,56),u_=Math.pow(2,63),l_=function(t){return t<t_?1:t<n_?2:t<r_?3:t<i_?4:t<s_?5:t<o_?6:t<a_?7:t<c_?8:t<u_?9:10},h_={encode:Z3,decode:Q3,encodingLength:l_},Kf=h_;const Vf=(t,e,n=0)=>(Kf.encode(t,e,n),e),Hf=t=>Kf.encodingLength(t),ec=(t,e)=>{const n=e.byteLength,r=Hf(t),i=r+Hf(n),s=new Uint8Array(i+n);return Vf(t,s,0),Vf(n,s,r),s.set(e,i),new f_(t,n,e,s)};class f_{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Wf=({name:t,code:e,encode:n})=>new d_(t,e,n);class d_{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?ec(this.code,n):n.then(r=>ec(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Gf=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),p_=Wf({name:"sha2-256",code:18,encode:Gf("SHA-256")}),g_=Wf({name:"sha2-512",code:19,encode:Gf("SHA-512")});var y_=Object.freeze({__proto__:null,sha256:p_,sha512:g_});const Zf=0,w_="identity",Yf=kf;var b_=Object.freeze({__proto__:null,identity:{code:Zf,name:w_,encode:Yf,digest:t=>ec(Zf,Yf(t))}});new TextEncoder,new TextDecoder;const Xf={...f3,...p3,...y3,...b3,...E3,...T3,...C3,...F3,...q3,...G3};({...y_,...b_});function Jf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Qf=Jf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),tc=Jf("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=Ff(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),ed={utf8:Qf,"utf-8":Qf,hex:Xf.base16,latin1:tc,ascii:tc,binary:tc,...Xf};function xt(t,e="utf8"){const n=ed[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ja(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function rt(t,e="utf8"){const n=ed[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 m_={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"}},v_="Input must be an string, Buffer or Uint8Array";function E_(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(v_);return e}function __(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function qs(t){return(4294967296+t).toString(16).substring(1)}function x_(t,e,n){let r=`
18
+ `+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=qs(e[i]).toUpperCase(),r+=" ",r+=qs(e[i+1]).toUpperCase();else if(n===64)r+=qs(e[i+1]).toUpperCase(),r+=qs(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
19
+ `+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function I_(t,e,n){let r=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=t(i),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var td={normalizeInput:E_,toHex:__,debugPrint:x_,testSpeed:I_};const zs=td;function Ks(t,e,n){const r=t[e]+t[n];let i=t[e+1]+t[n+1];r>=4294967296&&i++,t[e]=r,t[e+1]=i}function nd(t,e,n,r){let i=t[e]+n;n<0&&(i+=4294967296);let s=t[e+1]+r;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function rd(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function _n(t,e,n,r,i,s){const o=_i[i],a=_i[i+1],c=_i[s],u=_i[s+1];Ks(X,t,e),nd(X,t,o,a);let l=X[r]^X[t],f=X[r+1]^X[t+1];X[r]=f,X[r+1]=l,Ks(X,n,r),l=X[e]^X[n],f=X[e+1]^X[n+1],X[e]=l>>>24^f<<8,X[e+1]=f>>>24^l<<8,Ks(X,t,e),nd(X,t,c,u),l=X[r]^X[t],f=X[r+1]^X[t+1],X[r]=l>>>16^f<<16,X[r+1]=f>>>16^l<<16,Ks(X,n,r),l=X[e]^X[n],f=X[e+1]^X[n+1],X[e]=f>>>31^l<<1,X[e+1]=l>>>31^f<<1}const id=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),S_=[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],Ue=new Uint8Array(S_.map(function(t){return t*2})),X=new Uint32Array(32),_i=new Uint32Array(32);function sd(t,e){let n=0;for(n=0;n<16;n++)X[n]=t.h[n],X[n+16]=id[n];for(X[24]=X[24]^t.t,X[25]=X[25]^t.t/4294967296,e&&(X[28]=~X[28],X[29]=~X[29]),n=0;n<32;n++)_i[n]=rd(t.b,4*n);for(n=0;n<12;n++)_n(0,8,16,24,Ue[n*16+0],Ue[n*16+1]),_n(2,10,18,26,Ue[n*16+2],Ue[n*16+3]),_n(4,12,20,28,Ue[n*16+4],Ue[n*16+5]),_n(6,14,22,30,Ue[n*16+6],Ue[n*16+7]),_n(0,10,20,30,Ue[n*16+8],Ue[n*16+9]),_n(2,12,22,24,Ue[n*16+10],Ue[n*16+11]),_n(4,14,16,26,Ue[n*16+12],Ue[n*16+13]),_n(6,8,18,28,Ue[n*16+14],Ue[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^X[n]^X[n+16]}const xn=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function od(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};xn.fill(0),xn[0]=t,e&&(xn[1]=e.length),xn[2]=1,xn[3]=1,n&&xn.set(n,32),r&&xn.set(r,48);for(let s=0;s<16;s++)i.h[s]=id[s]^rd(xn,s*4);return e&&(nc(i,e),i.c=128),i}function nc(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,sd(t,!1),t.c=0),t.b[t.c++]=e[n]}function ad(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;sd(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3);return e}function cd(t,e,n,r,i){n=n||64,t=zs.normalizeInput(t),r&&(r=zs.normalizeInput(r)),i&&(i=zs.normalizeInput(i));const s=od(n,e,r,i);return nc(s,t),ad(s)}function D_(t,e,n,r,i){const s=cd(t,e,n,r,i);return zs.toHex(s)}var A_={blake2b:cd,blake2bHex:D_,blake2bInit:od,blake2bUpdate:nc,blake2bFinal:ad};const ud=td;function O_(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function In(t,e,n,r,i,s){te[t]=te[t]+te[e]+i,te[r]=Vs(te[r]^te[t],16),te[n]=te[n]+te[r],te[e]=Vs(te[e]^te[n],12),te[t]=te[t]+te[e]+s,te[r]=Vs(te[r]^te[t],8),te[n]=te[n]+te[r],te[e]=Vs(te[e]^te[n],7)}function Vs(t,e){return t>>>e^t<<32-e}const ld=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Fe=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),te=new Uint32Array(16),Oe=new Uint32Array(16);function hd(t,e){let n=0;for(n=0;n<8;n++)te[n]=t.h[n],te[n+8]=ld[n];for(te[12]^=t.t,te[13]^=t.t/4294967296,e&&(te[14]=~te[14]),n=0;n<16;n++)Oe[n]=O_(t.b,4*n);for(n=0;n<10;n++)In(0,4,8,12,Oe[Fe[n*16+0]],Oe[Fe[n*16+1]]),In(1,5,9,13,Oe[Fe[n*16+2]],Oe[Fe[n*16+3]]),In(2,6,10,14,Oe[Fe[n*16+4]],Oe[Fe[n*16+5]]),In(3,7,11,15,Oe[Fe[n*16+6]],Oe[Fe[n*16+7]]),In(0,5,10,15,Oe[Fe[n*16+8]],Oe[Fe[n*16+9]]),In(1,6,11,12,Oe[Fe[n*16+10]],Oe[Fe[n*16+11]]),In(2,7,8,13,Oe[Fe[n*16+12]],Oe[Fe[n*16+13]]),In(3,4,9,14,Oe[Fe[n*16+14]],Oe[Fe[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=te[n]^te[n+8]}function fd(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(ld),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(rc(r,e),r.c=64),r}function rc(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,hd(t,!1),t.c=0),t.b[t.c++]=e[n]}function dd(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;hd(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3)&255;return e}function pd(t,e,n){n=n||32,t=ud.normalizeInput(t);const r=fd(n,e);return rc(r,t),dd(r)}function $_(t,e,n){const r=pd(t,e,n);return ud.toHex(r)}var B_={blake2s:pd,blake2sHex:$_,blake2sInit:fd,blake2sUpdate:rc,blake2sFinal:dd};const xi=A_,Ii=B_;var T_={blake2b:xi.blake2b,blake2bHex:xi.blake2bHex,blake2bInit:xi.blake2bInit,blake2bUpdate:xi.blake2bUpdate,blake2bFinal:xi.blake2bFinal,blake2s:Ii.blake2s,blake2sHex:Ii.blake2sHex,blake2sInit:Ii.blake2sInit,blake2sUpdate:Ii.blake2sUpdate,blake2sFinal:Ii.blake2sFinal},P_=Object.defineProperty,R_=Object.defineProperties,C_=Object.getOwnPropertyDescriptors,gd=Object.getOwnPropertySymbols,N_=Object.prototype.hasOwnProperty,U_=Object.prototype.propertyIsEnumerable,yd=(t,e,n)=>e in t?P_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ur=(t,e)=>{for(var n in e||(e={}))N_.call(e,n)&&yd(t,n,e[n]);if(gd)for(var n of gd(e))U_.call(e,n)&&yd(t,n,e[n]);return t},Si=(t,e)=>R_(t,C_(e));const F_=":";function ir(t){const[e,n]=t.split(F_);return{namespace:e,reference:n}}function wd(t,e){return t.includes(":")?[t]:e.chains||[]}var k_=Object.defineProperty,L_=Object.defineProperties,M_=Object.getOwnPropertyDescriptors,bd=Object.getOwnPropertySymbols,j_=Object.prototype.hasOwnProperty,q_=Object.prototype.propertyIsEnumerable,ic=(t,e,n)=>e in t?k_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,md=(t,e)=>{for(var n in e||(e={}))j_.call(e,n)&&ic(t,n,e[n]);if(bd)for(var n of bd(e))q_.call(e,n)&&ic(t,n,e[n]);return t},z_=(t,e)=>L_(t,M_(e)),vd=(t,e,n)=>ic(t,typeof e!="symbol"?e+"":e,n);const K_="ReactNative",pt={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},V_="js";function Hs(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Sn(){return!Xn()&&!!aa()&&navigator.product===K_}function H_(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function W_(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Fr(){return!Hs()&&!!aa()&&!!Xn()}function Di(){return Sn()?pt.reactNative:Hs()?pt.node:Fr()?pt.browser:pt.unknown}function Ed(){var t;try{return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function G_(t,e){const n=new URLSearchParams(t);return Object.entries(e).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!=null&&n.set(r,String(i))}),n.toString()}function Z_(t){var e,n;const r=_d();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),z_(md(md({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function _d(){return ih()||{name:"",description:"",url:"",icons:[""]}}function Y_(){if(Di()===pt.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=qm();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 X_(){var t;const e=Di();return e===pt.browser?[e,((t=rh())==null?void 0:t.host)||"unknown"].join(":"):e}function xd(t,e,n){const r=Y_(),i=X_();return[[t,e].join("-"),[V_,n].join("-"),r,i].join("/")}function J_({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=xd(t,e,r),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},h=G_(u[1]||"",f);return u[0]+"?"+h}function sr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function sc(t){return Object.fromEntries(t.entries())}function oc(t){return new Map(Object.entries(t))}function or(t=M.FIVE_MINUTES,e){const n=M.toMiliseconds(t||M.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},n),r=a,i=c})}}function zt(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function Id(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 Q_(t){return Id("topic",t)}function ex(t){return Id("id",t)}function Sd(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function ve(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function Dn(t){return Date.now()>=M.toMiliseconds(t)}function ie(t,e){return`${t}${e?`:${e}`:""}`}function ar(t=[],e=[]){return[...new Set([...t,...e])]}async function tx({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=nx(s,t,e),a=Di();if(a===pt.browser){if(!((r=Xn())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}rx(o)}else a===pt.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function nx(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${ax(r,!0)}`}else i=`${i}/wc?${r}`;return i}function rx(t){let e="_self";ox()?e="_top":(sx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function ix(t,e){let n="";try{if(Fr()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function Dd(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function Ad(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function ac(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function sx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function ox(){try{return window.self!==window.top}catch{return!1}}function ax(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function Od(t){return Buffer.from(t,"base64").toString("utf-8")}function cx(t){return new Promise(e=>setTimeout(e,t))}class ux{constructor({limit:e}){vd(this,"limit"),vd(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}}const Ws=BigInt(2**32-1),$d=BigInt(32);function Bd(t,e=!1){return e?{h:Number(t&Ws),l:Number(t>>$d&Ws)}:{h:Number(t>>$d&Ws)|0,l:Number(t&Ws)|0}}function Td(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Bd(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Pd=(t,e,n)=>t>>>n,Rd=(t,e,n)=>t<<32-n|e>>>n,An=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,Ai=(t,e,n)=>t<<64-n|e>>>n-32,Oi=(t,e,n)=>t>>>n-32|e<<64-n,lx=(t,e)=>e,hx=(t,e)=>t,fx=(t,e,n)=>t<<n|e>>>32-n,dx=(t,e,n)=>e<<n|t>>>32-n,px=(t,e,n)=>e<<n-32|t>>>64-n,gx=(t,e,n)=>t<<n-32|e>>>64-n;function Pt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const cc=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),uc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,yx=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),wx=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,bx=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),mx=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,kr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Gs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function sn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Rt(t,...e){if(!Gs(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Zs(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");sn(t.outputLen),sn(t.blockLen)}function $n(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function lc(t,e){Rt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function $i(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function It(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function hc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Kt(t,e){return t<<32-e|t>>>e}const Cd=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Nd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const on=Cd?t=>t:t=>Nd(t);function vx(t){for(let e=0;e<t.length;e++)t[e]=Nd(t[e]);return t}const Bn=Cd?t=>t:vx,Ud=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Ex=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lr(t){if(Rt(t),Ud)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=Ex[t[n]];return e}const an={_0:48,_9:57,A:65,F:70,a:97,f:102};function Fd(t){if(t>=an._0&&t<=an._9)return t-an._0;if(t>=an.A&&t<=an.F)return t-(an.A-10);if(t>=an.a&&t<=an.f)return t-(an.a-10)}function Ys(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Ud)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Fd(t.charCodeAt(s)),a=Fd(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function kd(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ct(t){return typeof t=="string"&&(t=kd(t)),Rt(t),t}function Tn(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Rt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class Xs{}function Bi(t){const e=r=>t().update(Ct(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function _x(t){const e=(r,i)=>t(i).update(Ct(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function cr(t=32){if(kr&&typeof kr.getRandomValues=="function")return kr.getRandomValues(new Uint8Array(t));if(kr&&typeof kr.randomBytes=="function")return Uint8Array.from(kr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const xx=BigInt(0),Ti=BigInt(1),Ix=BigInt(2),Sx=BigInt(7),Dx=BigInt(256),Ax=BigInt(113),Ld=[],Md=[],jd=[];for(let t=0,e=Ti,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ld.push(2*(5*r+n)),Md.push((t+1)*(t+2)/2%64);let i=xx;for(let s=0;s<7;s++)e=(e<<Ti^(e>>Sx)*Ax)%Dx,e&Ix&&(i^=Ti<<(Ti<<BigInt(s))-Ti);jd.push(i)}const qd=Td(jd,!0),Ox=qd[0],$x=qd[1],zd=(t,e,n)=>n>32?px(t,e,n):fx(t,e,n),Kd=(t,e,n)=>n>32?gx(t,e,n):dx(t,e,n);function Bx(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],f=zd(u,l,1)^n[a],h=Kd(u,l,1)^n[a+1];for(let d=0;d<50;d+=10)t[o+d]^=f,t[o+d+1]^=h}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Md[o],c=zd(i,s,a),u=Kd(i,s,a),l=Ld[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Ox[r],t[1]^=$x[r]}It(n)}class fc extends Xs{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,sn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=$i(this.state)}clone(){return this._cloneInto()}keccak(){Bn(this.state32),Bx(this.state32,this.rounds),Bn(this.state32),this.posOut=0,this.pos=0}update(e){$n(this),e=Ct(e),Rt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){$n(this,!1),Rt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return sn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(lc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,It(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new fc(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Tx=(t,e,n)=>Bi(()=>new fc(e,t,n)),Px=Tx(1,136,256/8);function Rx(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Cx(t,e,n){return t&e^~t&n}function Nx(t,e,n){return t&e^t&n^e&n}class Vd extends Xs{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=hc(this.buffer)}update(e){$n(this),e=Ct(e),Rt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=hc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$n(this),lc(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,It(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;Rx(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=hc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<u;f++)a.setUint32(4*f,l[f],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Pn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Le=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Ux=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Rn=new Uint32Array(64);class Fx extends Vd{constructor(e=32){super(64,e,8,!1),this.A=Pn[0]|0,this.B=Pn[1]|0,this.C=Pn[2]|0,this.D=Pn[3]|0,this.E=Pn[4]|0,this.F=Pn[5]|0,this.G=Pn[6]|0,this.H=Pn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let f=0;f<16;f++,n+=4)Rn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const h=Rn[f-15],d=Rn[f-2],p=Kt(h,7)^Kt(h,18)^h>>>3,g=Kt(d,17)^Kt(d,19)^d>>>10;Rn[f]=g+Rn[f-7]+p+Rn[f-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let f=0;f<64;f++){const h=Kt(a,6)^Kt(a,11)^Kt(a,25),d=l+h+Cx(a,c,u)+Ux[f]+Rn[f]|0,p=(Kt(r,2)^Kt(r,13)^Kt(r,22))+Nx(r,i,s)|0;l=u,u=c,c=a,a=o+d|0,o=s,s=i,i=r,r=d+p|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){It(Rn)}destroy(){this.set(0,0,0,0,0,0,0,0),It(this.buffer)}}const Hd=Td(["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))),kx=Hd[0],Lx=Hd[1],Cn=new Uint32Array(80),Nn=new Uint32Array(80);class dc extends Vd{constructor(e=64){super(128,e,16,!1),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:f,Fl:h,Gh:d,Gl:p,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=f|0,this.Fl=h|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let E=0;E<16;E++,n+=4)Cn[E]=e.getUint32(n),Nn[E]=e.getUint32(n+=4);for(let E=16;E<80;E++){const $=Cn[E-15]|0,R=Nn[E-15]|0,C=An($,R,1)^An($,R,8)^Pd($,R,7),U=On($,R,1)^On($,R,8)^Rd($,R,7),N=Cn[E-2]|0,O=Nn[E-2]|0,G=An(N,O,19)^Ai(N,O,61)^Pd(N,O,6),W=On(N,O,19)^Oi(N,O,61)^Rd(N,O,6),P=yx(U,W,Nn[E-7],Nn[E-16]),v=wx(P,C,G,Cn[E-7],Cn[E-16]);Cn[E]=v|0,Nn[E]=P|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:h,Fh:d,Fl:p,Gh:g,Gl:y,Hh:I,Hl:D}=this;for(let E=0;E<80;E++){const $=An(f,h,14)^An(f,h,18)^Ai(f,h,41),R=On(f,h,14)^On(f,h,18)^Oi(f,h,41),C=f&d^~f&g,U=h&p^~h&y,N=bx(D,R,U,Lx[E],Nn[E]),O=mx(N,I,$,C,kx[E],Cn[E]),G=N|0,W=An(r,i,28)^Ai(r,i,34)^Ai(r,i,39),P=On(r,i,28)^Oi(r,i,34)^Oi(r,i,39),v=r&s^r&a^s&a,m=i&o^i&c^o&c;I=g|0,D=y|0,g=d|0,y=p|0,d=f|0,p=h|0,{h:f,l:h}=Pt(u|0,l|0,O|0,G|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const w=cc(G,P,m);r=uc(w,O,W,v),i=w|0}({h:r,l:i}=Pt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Pt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:h}=Pt(this.Eh|0,this.El|0,f|0,h|0),{h:d,l:p}=Pt(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:y}=Pt(this.Gh|0,this.Gl|0,g|0,y|0),{h:I,l:D}=Pt(this.Hh|0,this.Hl|0,I|0,D|0),this.set(r,i,s,o,a,c,u,l,f,h,d,p,g,y,I,D)}roundClean(){It(Cn,Nn)}destroy(){It(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class Mx extends dc{constructor(){super(48),this.Ah=ke[0]|0,this.Al=ke[1]|0,this.Bh=ke[2]|0,this.Bl=ke[3]|0,this.Ch=ke[4]|0,this.Cl=ke[5]|0,this.Dh=ke[6]|0,this.Dl=ke[7]|0,this.Eh=ke[8]|0,this.El=ke[9]|0,this.Fh=ke[10]|0,this.Fl=ke[11]|0,this.Gh=ke[12]|0,this.Gl=ke[13]|0,this.Hh=ke[14]|0,this.Hl=ke[15]|0}}const Me=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class jx extends dc{constructor(){super(32),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}}const Js=Bi(()=>new Fx),qx=Bi(()=>new dc),zx=Bi(()=>new Mx),Kx=Bi(()=>new jx),Vx=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Ee=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),K=new Uint32Array(32);function Un(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*n],d=K[2*n+1],p=K[2*r],g=K[2*r+1],y=cc(c,l,o);u=uc(y,u,f,a),c=y|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:lx(g,p),Dl:hx(g)},{h:d,l:h}=Pt(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:An(f,l,24),Bl:On(f,l,24)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*n]=h,K[2*n+1]=d,K[2*r]=p,K[2*r+1]=g}function Fn(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=K[2*t],u=K[2*t+1],l=K[2*e],f=K[2*e+1],h=K[2*n],d=K[2*n+1],p=K[2*r],g=K[2*r+1],y=cc(c,l,o);u=uc(y,u,f,a),c=y|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:An(g,p,16),Dl:On(g,p,16)},{h:d,l:h}=Pt(d,h,g,p),{Bh:f,Bl:l}={Bh:f^d,Bl:l^h},{Bh:f,Bl:l}={Bh:Ai(f,l,63),Bl:Oi(f,l,63)},K[2*t]=c,K[2*t+1]=u,K[2*e]=l,K[2*e+1]=f,K[2*n]=h,K[2*n+1]=d,K[2*r]=p,K[2*r+1]=g}function Hx(t,e={},n,r,i){if(sn(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class Wx extends Xs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,sn(e),sn(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=$i(this.buffer)}update(e){$n(this),e=Ct(e),Rt(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(Bn(i),this.compress(i,0,!1),Bn(i),this.pos=0);const u=Math.min(n-this.pos,s-c),l=o+c;if(u===n&&!(l%4)&&c+u<s){const f=new Uint32Array(a,l,Math.floor((s-c)/4));Bn(f);for(let h=0;c+n<s;h+=i.length,c+=n)this.length+=n,this.compress(f,h,!1);Bn(f);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){$n(this),lc(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,It(this.buffer.subarray(n)),Bn(r),this.compress(r,0,!0),Bn(r);const i=$i(e);this.get().forEach((s,o)=>i[o]=on(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Gx extends Wx{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Ee[0]|0,this.v0h=Ee[1]|0,this.v1l=Ee[2]|0,this.v1h=Ee[3]|0,this.v2l=Ee[4]|0,this.v2h=Ee[5]|0,this.v3l=Ee[6]|0,this.v3h=Ee[7]|0,this.v4l=Ee[8]|0,this.v4h=Ee[9]|0,this.v5l=Ee[10]|0,this.v5h=Ee[11]|0,this.v6l=Ee[12]|0,this.v6h=Ee[13]|0,this.v7l=Ee[14]|0,this.v7h=Ee[15]|0,Hx(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Ct(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Ct(s);const a=$i(s);this.v4l^=on(a[0]),this.v4h^=on(a[1]),this.v5l^=on(a[2]),this.v5h^=on(a[3])}if(i!==void 0){i=Ct(i);const a=$i(i);this.v6l^=on(a[0]),this.v6h^=on(a[1]),this.v7l^=on(a[2]),this.v7h^=on(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:f,v5h:h,v6l:d,v6h:p,v7l:g,v7h:y}=this;return[e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y]}set(e,n,r,i,s,o,a,c,u,l,f,h,d,p,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=f|0,this.v5h=h|0,this.v6l=d|0,this.v6h=p|0,this.v7l=g|0,this.v7h=y|0}compress(e,n,r){this.get().forEach((c,u)=>K[u]=c),K.set(Ee,16);let{h:i,l:s}=Bd(BigInt(this.length));K[24]=Ee[8]^s,K[25]=Ee[9]^i,r&&(K[28]=~K[28],K[29]=~K[29]);let o=0;const a=Vx;for(let c=0;c<12;c++)Un(0,4,8,12,e,n+2*a[o++]),Fn(0,4,8,12,e,n+2*a[o++]),Un(1,5,9,13,e,n+2*a[o++]),Fn(1,5,9,13,e,n+2*a[o++]),Un(2,6,10,14,e,n+2*a[o++]),Fn(2,6,10,14,e,n+2*a[o++]),Un(3,7,11,15,e,n+2*a[o++]),Fn(3,7,11,15,e,n+2*a[o++]),Un(0,5,10,15,e,n+2*a[o++]),Fn(0,5,10,15,e,n+2*a[o++]),Un(1,6,11,12,e,n+2*a[o++]),Fn(1,6,11,12,e,n+2*a[o++]),Un(2,7,8,13,e,n+2*a[o++]),Fn(2,7,8,13,e,n+2*a[o++]),Un(3,4,9,14,e,n+2*a[o++]),Fn(3,4,9,14,e,n+2*a[o++]);this.v0l^=K[0]^K[16],this.v0h^=K[1]^K[17],this.v1l^=K[2]^K[18],this.v1h^=K[3]^K[19],this.v2l^=K[4]^K[20],this.v2h^=K[5]^K[21],this.v3l^=K[6]^K[22],this.v3h^=K[7]^K[23],this.v4l^=K[8]^K[24],this.v4h^=K[9]^K[25],this.v5l^=K[10]^K[26],this.v5h^=K[11]^K[27],this.v6l^=K[12]^K[28],this.v6h^=K[13]^K[29],this.v7l^=K[14]^K[30],this.v7h^=K[15]^K[31],It(K)}destroy(){this.destroyed=!0,It(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Zx=_x(t=>new Gx(t)),Yx="https://rpc.walletconnect.org/v1";function Wd(t){const e=`Ethereum Signed Message:
20
+ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Px(n)).toString("hex")}async function Xx(t,e,n,r,i,s){switch(n.t){case"eip191":return await Jx(t,e,n.s);case"eip1271":return await Qx(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}async function Jx(t,e,n){return(await Mv({hash:Wd(e),signature:n})).toLowerCase()===t.toLowerCase()}async function Qx(t,e,n,r,i,s){const o=ir(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),f=(e.startsWith("0x")?e:Wd(e)).substring(2),h=a+f+c+l+u,d=await fetch(`${s||Yx}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:e8(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:h},"latest"]})}),{result:p}=await d.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function e8(){return Date.now()+Math.floor(Math.random()*1e3)}function t8(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return pi.encode(s)}function n8(t){const e=new Uint8Array(Buffer.from(t,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const i=Zx(r,{dkLen:32});return pi.encode(i)}function Gd(t){const e=new Uint8Array(Js(r8(t)));return pi.encode(e)}function r8(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Zd(t){const e=Buffer.from(t,"base64"),n=ZE(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=jE(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=Kx(s);return XE.encode(o).replace(/=+$/,"")}function pc(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function i8(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(pc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(pc(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(pc(r.length)),i.push(r);const s=Buffer.concat(i),o=Js(s);return Buffer.from(o).toString("hex").toUpperCase()}function s8(t){var e,n;const r=[];try{if(typeof t=="string")return r.push(t),r;if(typeof t!="object")return r;t!=null&&t.id&&r.push(t.id);const i=(n=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:n.transactionHashes;i&&r.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return r}var o8=Object.defineProperty,a8=Object.defineProperties,c8=Object.getOwnPropertyDescriptors,Yd=Object.getOwnPropertySymbols,u8=Object.prototype.hasOwnProperty,l8=Object.prototype.propertyIsEnumerable,Xd=(t,e,n)=>e in t?o8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,h8=(t,e)=>{for(var n in e||(e={}))u8.call(e,n)&&Xd(t,n,e[n]);if(Yd)for(var n of Yd(e))l8.call(e,n)&&Xd(t,n,e[n]);return t},f8=(t,e)=>a8(t,c8(e));const d8="did:pkh:",gc=t=>t?.split(":"),p8=t=>{const e=t&&gc(t);if(e)return t.includes(d8)?e[3]:e[1]},yc=t=>{const e=t&&gc(t);if(e)return e[2]+":"+e[3]},Qs=t=>{const e=t&&gc(t);if(e)return e.pop()};async function Jd(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=Qd(i,i.iss),o=Qs(i.iss);return await Xx(o,s,r,yc(i.iss),n)}const Qd=(t,e)=>{const n=`${t.domain} wants you to sign in with your Ethereum account:`,r=Qs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${p8(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(g=>`
21
+ - ${g}`).join("")}`:void 0,p=eo(t.resources);if(p){const g=Pi(p);i=x8(i,g)}return[n,r,"",i,"",s,o,a,c,u,l,f,h,d].filter(g=>g!=null).join(`
22
+ `)};function g8(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function y8(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function ur(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function w8(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:b8(e,n,r)}}}function b8(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function ep(t){return ur(t),`urn:recap:${g8(t).replace(/=/g,"")}`}function Pi(t){const e=y8(t.replace("urn:recap:",""));return ur(e),e}function m8(t,e,n){const r=w8(t,e,n);return ep(r)}function v8(t){return t&&t.includes("urn:recap:")}function E8(t,e){const n=Pi(t),r=Pi(e),i=_8(n,r);return ep(i)}function _8(t,e){ur(t),ur(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;r.att[i]=f8(h8({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function x8(t="",e){ur(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(f=>({ability:f.split("/")[0],action:f.split("/")[1]}));c.sort((f,h)=>f.action.localeCompare(h.action));const u={};c.forEach(f=>{u[f.ability]||(u[f.ability]=[]),u[f.ability].push(f.action)});const l=Object.keys(u).map(f=>(i++,`(${i}) '${f}': '${u[f].join("', '")}' for '${a}'.`));r.push(l.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${t?t+" ":""}${o}`}function tp(t){var e;const n=Pi(t);ur(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function np(t){const e=Pi(t);ur(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function eo(t){if(!t)return;const e=t?.[t.length-1];return v8(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function rp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function bc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function it(t,...e){if(!rp(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ip(t,e=!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 I8(t,e){it(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function kn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Mr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function S8(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const D8=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function A8(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function mc(t){if(typeof t=="string")t=A8(t);else if(rp(t))t=vc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function O8(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function $8(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 B8=(t,e)=>{function n(r,...i){if(it(r),!D8)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?it(u):it(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&it(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");it(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,it(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(it(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(n,t),n};function sp(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&&!P8(e))throw new Error("invalid output, must be aligned");return e}function op(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function T8(t,e,n){wc(n);const r=new Uint8Array(16),i=S8(r);return op(i,0,BigInt(e),n),op(i,8,BigInt(t),n),r}function P8(t){return t.byteOffset%4===0}function vc(t){return Uint8Array.from(t)}const ap=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),R8=ap("expand 16-byte k"),C8=ap("expand 32-byte k"),N8=kn(R8),U8=kn(C8);function ne(t,e){return t<<e|t>>>32-e}function Ec(t){return t.byteOffset%4===0}const to=64,F8=16,cp=2**32-1,up=new Uint32Array;function k8(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(to),l=kn(u),f=Ec(i)&&Ec(s),h=f?kn(i):up,d=f?kn(s):up;for(let p=0;p<c;o++){if(t(e,n,r,l,o,a),o>=cp)throw new Error("arx: counter overflow");const g=Math.min(to,c-p);if(f&&g===to){const y=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let I=0,D;I<F8;I++)D=y+I,d[D]=h[D]^l[I];p+=to;continue}for(let y=0,I;y<g;y++)I=p+y,s[I]=i[I]^u[y];p+=g}}function L8(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=O8({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return bc(i),bc(o),wc(s),wc(n),(a,c,u,l,f=0)=>{it(a),it(c),it(u);const h=u.length;if(l===void 0&&(l=new Uint8Array(h)),it(l),bc(f),f<0||f>=cp)throw new Error("arx: counter overflow");if(l.length<h)throw new Error(`arx: output (${l.length}) is shorter than data (${h})`);const d=[];let p=a.length,g,y;if(p===32)d.push(g=vc(a)),y=U8;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=N8,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Ec(c)||d.push(c=vc(c));const I=kn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,I,kn(c.subarray(0,16)),I),c=c.subarray(16)}const D=16-i;if(D!==c.length)throw new Error(`arx: nonce must be ${D} or 16 bytes`);if(D!==12){const $=new Uint8Array(12);$.set(c,s?0:12-c.length),c=$,d.push(c)}const E=kn(c);return k8(t,y,I,E,u,l,f,o),Mr(...d),l}}const $e=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class M8{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=mc(e),it(e,32);const n=$e(e,0),r=$e(e,2),i=$e(e,4),s=$e(e,6),o=$e(e,8),a=$e(e,10),c=$e(e,12),u=$e(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=$e(e,16+2*l)}process(e,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],f=o[4],h=o[5],d=o[6],p=o[7],g=o[8],y=o[9],I=$e(e,n+0),D=$e(e,n+2),E=$e(e,n+4),$=$e(e,n+6),R=$e(e,n+8),C=$e(e,n+10),U=$e(e,n+12),N=$e(e,n+14);let O=s[0]+(I&8191),G=s[1]+((I>>>13|D<<3)&8191),W=s[2]+((D>>>10|E<<6)&8191),P=s[3]+((E>>>7|$<<9)&8191),v=s[4]+(($>>>4|R<<12)&8191),m=s[5]+(R>>>1&8191),w=s[6]+((R>>>14|C<<2)&8191),b=s[7]+((C>>>11|U<<5)&8191),x=s[8]+((U>>>8|N<<8)&8191),A=s[9]+(N>>>5|i),_=0,S=_+O*a+G*(5*y)+W*(5*g)+P*(5*p)+v*(5*d);_=S>>>13,S&=8191,S+=m*(5*h)+w*(5*f)+b*(5*l)+x*(5*u)+A*(5*c),_+=S>>>13,S&=8191;let B=_+O*c+G*a+W*(5*y)+P*(5*g)+v*(5*p);_=B>>>13,B&=8191,B+=m*(5*d)+w*(5*h)+b*(5*f)+x*(5*l)+A*(5*u),_+=B>>>13,B&=8191;let T=_+O*u+G*c+W*a+P*(5*y)+v*(5*g);_=T>>>13,T&=8191,T+=m*(5*p)+w*(5*d)+b*(5*h)+x*(5*f)+A*(5*l),_+=T>>>13,T&=8191;let q=_+O*l+G*u+W*c+P*a+v*(5*y);_=q>>>13,q&=8191,q+=m*(5*g)+w*(5*p)+b*(5*d)+x*(5*h)+A*(5*f),_+=q>>>13,q&=8191;let L=_+O*f+G*l+W*u+P*c+v*a;_=L>>>13,L&=8191,L+=m*(5*y)+w*(5*g)+b*(5*p)+x*(5*d)+A*(5*h),_+=L>>>13,L&=8191;let k=_+O*h+G*f+W*l+P*u+v*c;_=k>>>13,k&=8191,k+=m*a+w*(5*y)+b*(5*g)+x*(5*p)+A*(5*d),_+=k>>>13,k&=8191;let z=_+O*d+G*h+W*f+P*l+v*u;_=z>>>13,z&=8191,z+=m*c+w*a+b*(5*y)+x*(5*g)+A*(5*p),_+=z>>>13,z&=8191;let H=_+O*p+G*d+W*h+P*f+v*l;_=H>>>13,H&=8191,H+=m*u+w*c+b*a+x*(5*y)+A*(5*g),_+=H>>>13,H&=8191;let Z=_+O*g+G*p+W*d+P*h+v*f;_=Z>>>13,Z&=8191,Z+=m*l+w*u+b*c+x*a+A*(5*y),_+=Z>>>13,Z&=8191;let V=_+O*y+G*g+W*p+P*d+v*h;_=V>>>13,V&=8191,V+=m*f+w*l+b*u+x*c+A*a,_+=V>>>13,V&=8191,_=(_<<2)+_|0,_=_+S|0,S=_&8191,_=_>>>13,B+=_,s[0]=S,s[1]=B,s[2]=T,s[3]=q,s[4]=L,s[5]=k,s[6]=z,s[7]=H,s[8]=Z,s[9]=V}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Mr(r)}update(e){ip(this),e=mc(e),it(e);const{buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Mr(this.h,this.r,this.buffer,this.pad)}digestInto(e){ip(this),I8(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function j8(t){const e=(r,i)=>t(i).update(mc(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const q8=j8(t=>new M8(t));function z8(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],f=e[1],h=e[2],d=e[3],p=e[4],g=e[5],y=e[6],I=e[7],D=i,E=n[0],$=n[1],R=n[2],C=o,U=a,N=c,O=u,G=l,W=f,P=h,v=d,m=p,w=g,b=y,x=I,A=D,_=E,S=$,B=R;for(let q=0;q<s;q+=2)C=C+G|0,A=ne(A^C,16),m=m+A|0,G=ne(G^m,12),C=C+G|0,A=ne(A^C,8),m=m+A|0,G=ne(G^m,7),U=U+W|0,_=ne(_^U,16),w=w+_|0,W=ne(W^w,12),U=U+W|0,_=ne(_^U,8),w=w+_|0,W=ne(W^w,7),N=N+P|0,S=ne(S^N,16),b=b+S|0,P=ne(P^b,12),N=N+P|0,S=ne(S^N,8),b=b+S|0,P=ne(P^b,7),O=O+v|0,B=ne(B^O,16),x=x+B|0,v=ne(v^x,12),O=O+v|0,B=ne(B^O,8),x=x+B|0,v=ne(v^x,7),C=C+W|0,B=ne(B^C,16),b=b+B|0,W=ne(W^b,12),C=C+W|0,B=ne(B^C,8),b=b+B|0,W=ne(W^b,7),U=U+P|0,A=ne(A^U,16),x=x+A|0,P=ne(P^x,12),U=U+P|0,A=ne(A^U,8),x=x+A|0,P=ne(P^x,7),N=N+v|0,_=ne(_^N,16),m=m+_|0,v=ne(v^m,12),N=N+v|0,_=ne(_^N,8),m=m+_|0,v=ne(v^m,7),O=O+G|0,S=ne(S^O,16),w=w+S|0,G=ne(G^w,12),O=O+G|0,S=ne(S^O,8),w=w+S|0,G=ne(G^w,7);let T=0;r[T++]=o+C|0,r[T++]=a+U|0,r[T++]=c+N|0,r[T++]=u+O|0,r[T++]=l+G|0,r[T++]=f+W|0,r[T++]=h+P|0,r[T++]=d+v|0,r[T++]=p+m|0,r[T++]=g+w|0,r[T++]=y+b|0,r[T++]=I+x|0,r[T++]=D+A|0,r[T++]=E+_|0,r[T++]=$+S|0,r[T++]=R+B|0}const K8=L8(z8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),V8=new Uint8Array(16),lp=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(V8.subarray(n))},H8=new Uint8Array(32);function hp(t,e,n,r,i){const s=t(e,n,H8),o=q8.create(s);i&&lp(o,i),lp(o,r);const a=T8(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Mr(s,a),c}const W8=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=sp(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=hp(t,e,n,a,r);return s.set(c,o),Mr(c),s},decrypt(i,s){s=sp(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=hp(t,e,n,o,r);if(!$8(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Mr(c),s}}),fp=B8({blockSize:64,nonceLength:12,tagLength:16},W8(K8));class dp extends Xs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Zs(e);const r=Ct(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),It(s)}update(e){return $n(this),this.iHash.update(e),this}digestInto(e){$n(this),Rt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const no=(t,e,n)=>new dp(t,e).update(n).digest();no.create=(t,e)=>new dp(t,e);function G8(t,e,n){return Zs(t),n===void 0&&(n=new Uint8Array(t.outputLen)),no(t,Ct(n),Ct(e))}const _c=Uint8Array.from([0]),pp=Uint8Array.of();function Z8(t,e,n,r=32){Zs(t),sn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=pp);const o=new Uint8Array(s*i),a=no.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)_c[0]=l+1,c.update(l===0?pp:u).update(n).update(_c).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),It(u,_c),o.slice(0,r)}const Y8=(t,e,n,r,i)=>Z8(t,G8(t,e,n),r,i),ro=Js,xc=BigInt(0),Ic=BigInt(1);function io(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function lr(t,e,n=""){const r=Gs(t),i=t?.length,s=e!==void 0;if(!r||s&&i!==e){const o=n&&`"${n}" `,a=s?` of length ${e}`:"",c=r?`length=${i}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function so(t){const e=t.toString(16);return e.length&1?"0"+e:e}function gp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xc:BigInt("0x"+t)}function oo(t){return gp(Lr(t))}function ao(t){return Rt(t),gp(Lr(Uint8Array.from(t).reverse()))}function Sc(t,e){return Ys(t.toString(16).padStart(e*2,"0"))}function Dc(t,e){return Sc(t,e).reverse()}function je(t,e,n){let r;if(typeof e=="string")try{r=Ys(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Gs(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Ac=t=>typeof t=="bigint"&&xc<=t;function X8(t,e,n){return Ac(t)&&Ac(e)&&Ac(n)&&e<=t&&t<n}function Oc(t,e,n,r){if(!X8(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function yp(t){let e;for(e=0;t>xc;t>>=Ic,e+=1);return e}const Ri=t=>(Ic<<BigInt(t))-Ic;function J8(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=h=>new Uint8Array(h),i=h=>Uint8Array.of(h);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...h)=>n(o,s,...h),l=(h=r(0))=>{o=u(i(0),h),s=u(),h.length!==0&&(o=u(i(1),h),s=u())},f=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const d=[];for(;h<e;){s=u();const p=s.slice();d.push(p),h+=s.length}return Tn(...d)};return(h,d)=>{c(),l(h);let p;for(;!(p=d(f()));)l();return c(),p}}function co(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function wp(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const st=BigInt(0),Ye=BigInt(1),hr=BigInt(2),bp=BigInt(3),mp=BigInt(4),vp=BigInt(5),Q8=BigInt(7),Ep=BigInt(8),eI=BigInt(9),_p=BigInt(16);function gt(t,e){const n=t%e;return n>=st?n:e+n}function Nt(t,e,n){let r=t;for(;e-- >st;)r*=r,r%=n;return r}function xp(t,e){if(t===st)throw new Error("invert: expected non-zero number");if(e<=st)throw new Error("invert: expected positive modulus, got "+e);let n=gt(t,e),r=e,i=st,s=Ye;for(;n!==st;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==Ye)throw new Error("invert: does not exist");return gt(i,e)}function $c(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Ip(t,e){const n=(t.ORDER+Ye)/mp,r=t.pow(e,n);return $c(t,r,e),r}function tI(t,e){const n=(t.ORDER-vp)/Ep,r=t.mul(e,hr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,hr),i),a=t.mul(s,t.sub(o,t.ONE));return $c(t,a,e),a}function nI(t){const e=Ln(t),n=Sp(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+Q8)/_p;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),h=a.mul(u,s),d=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,d),l=a.cmov(h,f,p);const g=a.eql(a.sqr(l),c),y=a.cmov(u,l,g);return $c(a,y,c),y}}function Sp(t){if(t<bp)throw new Error("sqrt is not defined for small field");let e=t-Ye,n=0;for(;e%hr===st;)e/=hr,n++;let r=hr;const i=Ln(t);for(;Ap(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Ip;let s=i.pow(r,e);const o=(e+Ye)/hr;return function(a,c){if(a.is0(c))return c;if(Ap(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),f=a.pow(c,e),h=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let d=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(d++,p=a.sqr(p),d===u)throw new Error("Cannot find square root");const g=Ye<<BigInt(u-d-1),y=a.pow(l,g);u=d,l=a.sqr(y),f=a.mul(f,l),h=a.mul(h,y)}return h}}function rI(t){return t%mp===bp?Ip:t%Ep===vp?tI:t%_p===eI?nI(t):Sp(t)}const iI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function sI(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=iI.reduce((r,i)=>(r[i]="function",r),e);return co(t,n),t}function oI(t,e,n){if(n<st)throw new Error("invalid exponent, negatives unsupported");if(n===st)return t.ONE;if(n===Ye)return e;let r=t.ONE,i=e;for(;n>st;)n&Ye&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ye;return r}function Dp(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Ap(t,e){const n=(t.ORDER-Ye)/hr,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Op(t,e){e!==void 0&&sn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Ln(t,e,n=!1,r={}){if(t<=st)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const h=e;h.BITS&&(i=h.BITS),h.sqrt&&(s=h.sqrt),typeof h.isLE=="boolean"&&(n=h.isLE),typeof h.modFromBytes=="boolean"&&(o=h.modFromBytes),a=h.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=Op(t,i);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const f=Object.freeze({ORDER:t,isLE:n,BITS:c,BYTES:u,MASK:Ri(c),ZERO:st,ONE:Ye,allowedLengths:a,create:h=>gt(h,t),isValid:h=>{if(typeof h!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof h);return st<=h&&h<t},is0:h=>h===st,isValidNot0:h=>!f.is0(h)&&f.isValid(h),isOdd:h=>(h&Ye)===Ye,neg:h=>gt(-h,t),eql:(h,d)=>h===d,sqr:h=>gt(h*h,t),add:(h,d)=>gt(h+d,t),sub:(h,d)=>gt(h-d,t),mul:(h,d)=>gt(h*d,t),pow:(h,d)=>oI(f,h,d),div:(h,d)=>gt(h*xp(d,t),t),sqrN:h=>h*h,addN:(h,d)=>h+d,subN:(h,d)=>h-d,mulN:(h,d)=>h*d,inv:h=>xp(h,t),sqrt:s||(h=>(l||(l=rI(t)),l(f,h))),toBytes:h=>n?Dc(h,u):Sc(h,u),fromBytes:(h,d=!0)=>{if(a){if(!a.includes(h.length)||h.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+h.length);const g=new Uint8Array(u);g.set(h,n?0:g.length-h.length),h=g}if(h.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+h.length);let p=n?ao(h):oo(h);if(o&&(p=gt(p,t)),!d&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:h=>Dp(f,h),cmov:(h,d,p)=>p?d:h});return Object.freeze(f)}function $p(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 Bp(t){const e=$p(t);return e+Math.ceil(e/2)}function aI(t,e,n=!1){const r=t.length,i=$p(e),s=Bp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ao(t):oo(t),a=gt(o,e-Ye)+Ye;return n?Dc(a,i):Sc(a,i)}const jr=BigInt(0),fr=BigInt(1);function uo(t,e){const n=e.negate();return t?n:e}function Bc(t,e){const n=Dp(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Tp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Tc(t,e){Tp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Ri(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Pp(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=fr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,h=a<0,d=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:h,isNegF:d,offsetF:u}}function cI(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 uI(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Pc=new WeakMap,Rp=new WeakMap;function Rc(t){return Rp.get(t)||1}function Cp(t){if(t!==jr)throw new Error("invalid wNAF")}class lI{constructor(e,n){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=n}_unsafeLadder(e,n,r=this.ZERO){let i=e;for(;n>jr;)n&fr&&(r=r.add(i)),i=i.double(),n>>=fr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=Tc(n,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let u=1;u<i;u++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,n,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let i=this.ZERO,s=this.BASE;const o=Tc(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:h,offsetF:d}=Pp(r,a,o);r=c,l?s=s.add(uo(h,n[d])):i=i.add(uo(f,n[u]))}return Cp(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=Tc(e,this.bits);for(let o=0;o<s.windows&&r!==jr;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Pp(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return Cp(r),i}getPrecomputes(e,n,r){let i=Pc.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),Pc.set(n,i))),i}cached(e,n,r){const i=Rc(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=Rc(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Tp(n,this.bits),Rp.set(e,n),Pc.delete(e)}hasCache(e){return Rc(e)!==1}}function hI(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>jr||r>jr;)n&fr&&(s=s.add(i)),r&fr&&(o=o.add(i)),i=i.double(),n>>=fr,r>>=fr;return{p1:s,p2:o}}function fI(t,e,n,r){cI(n,t),uI(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=yp(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Ri(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let h=o;for(let d=f;d>=0;d-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],I=Number(y>>BigInt(d)&u);l[I]=l[I].add(n[g])}let p=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),p=p.add(y);if(h=h.add(p),d!==0)for(let g=0;g<c;g++)h=h.double()}return h}function Np(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return sI(e),e}else return Ln(t,{isLE:n})}function dI(t,e,n={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>jr))throw new Error(`CURVE.${a} must be positive bigint`)}const i=Np(e.p,n.Fp,r),s=Np(e.n,n.Fn,r),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!i.isValid(e[a]))throw new Error(`CURVE.${a} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:i,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),kd("HashToScalar-");const Ci=BigInt(0),qr=BigInt(1),lo=BigInt(2);function pI(t){return co(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(Ur({},t))}function gI(t){const e=pI(t),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||cr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),h=BigInt(a?121665:39081),d=a?lo**BigInt(254):lo**BigInt(447),p=a?BigInt(8)*lo**BigInt(251)-qr:BigInt(4)*lo**BigInt(445)-qr,g=d+p+qr,y=P=>gt(P,n),I=D(f);function D(P){return Dc(y(P),l)}function E(P){const v=je("u coordinate",P,l);return a&&(v[31]&=127),y(ao(v))}function $(P){return ao(i(je("scalar",P,l)))}function R(P,v){const m=N(E(v),$(P));if(m===Ci)throw new Error("invalid private or public key received");return D(m)}function C(P){return R(P,I)}function U(P,v,m){const w=y(P*(v-m));return v=y(v-w),m=y(m+w),{x_2:v,x_3:m}}function N(P,v){Oc("u",P,Ci,n),Oc("scalar",v,d,g);const m=v,w=P;let b=qr,x=Ci,A=P,_=qr,S=Ci;for(let T=BigInt(u-1);T>=Ci;T--){const q=m>>T&qr;S^=q,{x_2:b,x_3:A}=U(S,b,A),{x_2:x,x_3:_}=U(S,x,_),S=q;const L=b+x,k=y(L*L),z=b-x,H=y(z*z),Z=k-H,V=A+_,Y=A-_,he=y(Y*L),Ke=y(V*z),mt=he+Ke,gn=he-Ke;A=y(mt*mt),_=y(w*y(gn*gn)),b=y(k*H),x=y(Z*(k+y(h*Z)))}({x_2:b,x_3:A}=U(S,b,A)),{x_2:x,x_3:_}=U(S,x,_);const B=s(x);return y(b*B)}const O={secretKey:l,publicKey:l,seed:l},G=(P=c(l))=>(Rt(P,O.seed),P);function W(P){const v=G(P);return{secretKey:v,publicKey:C(v)}}return{keygen:W,getSharedSecret:(P,v)=>R(P,v),getPublicKey:P=>C(P),scalarMult:R,scalarMultBase:C,utils:{randomSecretKey:G,randomPrivateKey:G},GuBytes:I.slice(),lengths:O}}const yI=BigInt(1),Up=BigInt(2),wI=BigInt(3),bI=BigInt(5),mI=BigInt(8),Fp=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),vI={p:Fp,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:mI,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function EI(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Fp,o=t*t%s*t%s,a=Nt(o,Up,s)*o%s,c=Nt(a,yI,s)*t%s,u=Nt(c,bI,s)*c%s,l=Nt(u,e,s)*u%s,f=Nt(l,n,s)*l%s,h=Nt(f,r,s)*f%s,d=Nt(h,i,s)*h%s,p=Nt(d,i,s)*h%s,g=Nt(p,e,s)*u%s;return{pow_p_5_8:Nt(g,Up,s)*t%s,b2:o}}function _I(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const xI=Ln(vI.p,{isLE:!0}),Cc=(()=>{const t=xI.ORDER;return gI({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=EI(e);return gt(Nt(n,wI,t)*r,t)},adjustScalarBytes:_I})})(),kp=(t,e)=>(t+(t>=0?e:-e)/Lp)/e;function II(t,e,n){const[[r,i],[s,o]]=e,a=kp(o*t,n),c=kp(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<un,h=l<un;f&&(u=-u),h&&(l=-l);const d=Ri(Math.ceil(yp(n)/2))+zr;if(u<un||u>=d||l<un||l>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:h,k2:l}}function Nc(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Uc(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return io(n.lowS,"lowS"),io(n.prehash,"prehash"),n.format!==void 0&&Nc(n.format),n}class SI extends Error{constructor(e=""){super(e)}}const cn={Err:SI,_tlv:{encode:(t,e)=>{const{Err:n}=cn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=so(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?so(i.length/2|128):"";return so(t)+s+i+e},decode(t,e){const{Err:n}=cn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=cn;if(t<un)throw new e("integer: negative integers are not allowed");let n=so(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=cn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return oo(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=cn,i=je("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=cn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},un=BigInt(0),zr=BigInt(1),Lp=BigInt(2),ho=BigInt(3),DI=BigInt(4);function Kr(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=je("private key",e);try{r=t.fromBytes(i)}catch{throw new Error(`invalid private key: expected ui8a of size ${n}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function AI(t,e={}){const n=dI("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;co(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=jp(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(P,v,m){const{x:w,y:b}=v.toAffine(),x=r.toBytes(w);if(io(m,"isCompressed"),m){l();const A=!r.isOdd(b);return Tn(Mp(A),x)}else return Tn(Uint8Array.of(4),x,r.toBytes(b))}function h(P){lr(P,void 0,"Point");const{publicKey:v,publicKeyUncompressed:m}=u,w=P.length,b=P[0],x=P.subarray(1);if(w===v&&(b===2||b===3)){const A=r.fromBytes(x);if(!r.isValid(A))throw new Error("bad point: is not on curve, wrong x");const _=g(A);let S;try{S=r.sqrt(_)}catch(T){const q=T instanceof Error?": "+T.message:"";throw new Error("bad point: is not on curve, sqrt error"+q)}l();const B=r.isOdd(S);return(b&1)===1!==B&&(S=r.neg(S)),{x:A,y:S}}else if(w===m&&b===4){const A=r.BYTES,_=r.fromBytes(x.subarray(0,A)),S=r.fromBytes(x.subarray(A,A*2));if(!y(_,S))throw new Error("bad point: is not on curve");return{x:_,y:S}}else throw new Error(`bad point: got length ${w}, expected compressed=${v} or uncompressed=${m}`)}const d=e.toBytes||f,p=e.fromBytes||h;function g(P){const v=r.sqr(P),m=r.mul(v,P);return r.add(r.add(m,r.mul(P,s.a)),s.b)}function y(P,v){const m=r.sqr(v),w=g(P);return r.eql(m,w)}if(!y(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=r.mul(r.pow(s.a,ho),DI),D=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(I,D)))throw new Error("bad curve params: a or b");function E(P,v,m=!1){if(!r.isValid(v)||m&&r.is0(v))throw new Error(`bad point coordinate ${P}`);return v}function $(P){if(!(P instanceof O))throw new Error("ProjectivePoint expected")}function R(P){if(!c||!c.basises)throw new Error("no endo");return II(P,c.basises,i.ORDER)}const C=wp((P,v)=>{const{X:m,Y:w,Z:b}=P;if(r.eql(b,r.ONE))return{x:m,y:w};const x=P.is0();v==null&&(v=x?r.ONE:r.inv(b));const A=r.mul(m,v),_=r.mul(w,v),S=r.mul(b,v);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:A,y:_}}),U=wp(P=>{if(P.is0()){if(e.allowInfinityPoint&&!r.is0(P.Y))return;throw new Error("bad point: ZERO")}const{x:v,y:m}=P.toAffine();if(!r.isValid(v)||!r.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(v,m))throw new Error("bad point: equation left != right");if(!P.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(P,v,m,w,b){return m=new O(r.mul(m.X,P),m.Y,m.Z),v=uo(w,v),m=uo(b,m),v.add(m)}class O{constructor(v,m,w){this.X=E("x",v),this.Y=E("y",m,!0),this.Z=E("z",w),Object.freeze(this)}static CURVE(){return s}static fromAffine(v){const{x:m,y:w}=v||{};if(!v||!r.isValid(m)||!r.isValid(w))throw new Error("invalid affine point");if(v instanceof O)throw new Error("projective point not allowed");return r.is0(m)&&r.is0(w)?O.ZERO:new O(m,w,r.ONE)}static fromBytes(v){const m=O.fromAffine(p(lr(v,void 0,"point")));return m.assertValidity(),m}static fromHex(v){return O.fromBytes(je("pointHex",v))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(v=8,m=!0){return W.createCache(this,v),m||this.multiply(ho),this}assertValidity(){U(this)}hasEvenY(){const{y:v}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(v)}equals(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v,S=r.eql(r.mul(m,_),r.mul(x,b)),B=r.eql(r.mul(w,_),r.mul(A,b));return S&&B}negate(){return new O(this.X,r.neg(this.Y),this.Z)}double(){const{a:v,b:m}=s,w=r.mul(m,ho),{X:b,Y:x,Z:A}=this;let _=r.ZERO,S=r.ZERO,B=r.ZERO,T=r.mul(b,b),q=r.mul(x,x),L=r.mul(A,A),k=r.mul(b,x);return k=r.add(k,k),B=r.mul(b,A),B=r.add(B,B),_=r.mul(v,B),S=r.mul(w,L),S=r.add(_,S),_=r.sub(q,S),S=r.add(q,S),S=r.mul(_,S),_=r.mul(k,_),B=r.mul(w,B),L=r.mul(v,L),k=r.sub(T,L),k=r.mul(v,k),k=r.add(k,B),B=r.add(T,T),T=r.add(B,T),T=r.add(T,L),T=r.mul(T,k),S=r.add(S,T),L=r.mul(x,A),L=r.add(L,L),T=r.mul(L,k),_=r.sub(_,T),B=r.mul(L,q),B=r.add(B,B),B=r.add(B,B),new O(_,S,B)}add(v){$(v);const{X:m,Y:w,Z:b}=this,{X:x,Y:A,Z:_}=v;let S=r.ZERO,B=r.ZERO,T=r.ZERO;const q=s.a,L=r.mul(s.b,ho);let k=r.mul(m,x),z=r.mul(w,A),H=r.mul(b,_),Z=r.add(m,w),V=r.add(x,A);Z=r.mul(Z,V),V=r.add(k,z),Z=r.sub(Z,V),V=r.add(m,b);let Y=r.add(x,_);return V=r.mul(V,Y),Y=r.add(k,H),V=r.sub(V,Y),Y=r.add(w,b),S=r.add(A,_),Y=r.mul(Y,S),S=r.add(z,H),Y=r.sub(Y,S),T=r.mul(q,V),S=r.mul(L,H),T=r.add(S,T),S=r.sub(z,T),T=r.add(z,T),B=r.mul(S,T),z=r.add(k,k),z=r.add(z,k),H=r.mul(q,H),V=r.mul(L,V),z=r.add(z,H),H=r.sub(k,H),H=r.mul(q,H),V=r.add(V,H),k=r.mul(z,V),B=r.add(B,k),k=r.mul(Y,V),S=r.mul(Z,S),S=r.sub(S,k),k=r.mul(Z,z),T=r.mul(Y,T),T=r.add(T,k),new O(S,B,T)}subtract(v){return this.add(v.negate())}is0(){return this.equals(O.ZERO)}multiply(v){const{endo:m}=e;if(!i.isValidNot0(v))throw new Error("invalid scalar: out of range");let w,b;const x=A=>W.cached(this,A,_=>Bc(O,_));if(m){const{k1neg:A,k1:_,k2neg:S,k2:B}=R(v),{p:T,f:q}=x(_),{p:L,f:k}=x(B);b=q.add(k),w=N(m.beta,T,L,A,S)}else{const{p:A,f:_}=x(v);w=A,b=_}return Bc(O,[w,b])[0]}multiplyUnsafe(v){const{endo:m}=e,w=this;if(!i.isValid(v))throw new Error("invalid scalar: out of range");if(v===un||w.is0())return O.ZERO;if(v===zr)return w;if(W.hasCache(this))return this.multiply(v);if(m){const{k1neg:b,k1:x,k2neg:A,k2:_}=R(v),{p1:S,p2:B}=hI(O,w,x,_);return N(m.beta,S,B,b,A)}else return W.unsafe(w,v)}multiplyAndAddUnsafe(v,m,w){const b=this.multiplyUnsafe(m).add(v.multiplyUnsafe(w));return b.is0()?void 0:b}toAffine(v){return C(this,v)}isTorsionFree(){const{isTorsionFree:v}=e;return o===zr?!0:v?v(O,this):W.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:v}=e;return o===zr?this:v?v(O,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(v=!0){return io(v,"isCompressed"),this.assertValidity(),d(O,this,v)}toHex(v=!0){return Lr(this.toBytes(v))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(v=!0){return this.toBytes(v)}_setWindowSize(v){this.precompute(v)}static normalizeZ(v){return Bc(O,v)}static msm(v,m){return fI(O,i,v,m)}static fromPrivateKey(v){return O.BASE.multiply(Kr(i,v))}}O.BASE=new O(s.Gx,s.Gy,r.ONE),O.ZERO=new O(r.ZERO,r.ONE,r.ZERO),O.Fp=r,O.Fn=i;const G=i.BITS,W=new lI(O,e.endo?Math.ceil(G/2):G);return O.BASE.precompute(8),O}function Mp(t){return Uint8Array.of(t?2:3)}function jp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function OI(t,e={}){const{Fn:n}=t,r=e.randomBytes||cr,i=Object.assign(jp(t.Fp,n),{seed:Bp(n.ORDER)});function s(h){try{return!!Kr(n,h)}catch{return!1}}function o(h,d){const{publicKey:p,publicKeyUncompressed:g}=i;try{const y=h.length;return d===!0&&y!==p||d===!1&&y!==g?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return aI(lr(h,i.seed,"seed"),n.ORDER)}function c(h,d=!0){return t.BASE.multiply(Kr(n,h)).toBytes(d)}function u(h){const d=a(h);return{secretKey:d,publicKey:c(d)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:d,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||d===p)return;const y=je("key",h).length;return y===p||y===g}function f(h,d,p=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(d)===!1)throw new Error("second arg must be public key");const g=Kr(n,h);return t.fromHex(d).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:f,keygen:u,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:h=>Kr(n,h),precompute(h=8,d=t.BASE){return d.precompute(h,!1)}},lengths:i})}function $I(t,e,n={}){Zs(e),co(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||cr,i=n.hmac||((m,...w)=>no(e,m,Tn(...w))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d}=OI(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function y(m){const w=a>>zr;return m>w}function I(m,w){if(!o.isValidNot0(w))throw new Error(`invalid signature ${m}: out of range 1..Point.Fn.ORDER`);return w}function D(m,w){Nc(w);const b=d.signature,x=w==="compact"?b:w==="recovered"?b+1:void 0;return lr(m,x,`${w} signature`)}class E{constructor(w,b,x){this.r=I("r",w),this.s=I("s",b),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(w,b=g){D(w,b);let x;if(b==="der"){const{r:B,s:T}=cn.toSig(lr(w));return new E(B,T)}b==="recovered"&&(x=w[0],b="compact",w=w.subarray(1));const A=o.BYTES,_=w.subarray(0,A),S=w.subarray(A,A*2);return new E(o.fromBytes(_),o.fromBytes(S),x)}static fromHex(w,b){return this.fromBytes(Ys(w),b)}addRecoveryBit(w){return new E(this.r,this.s,w)}recoverPublicKey(w){const b=s.ORDER,{r:x,s:A,recovery:_}=this;if(_==null||![0,1,2,3].includes(_))throw new Error("recovery id invalid");if(a*Lp<b&&_>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=_===2||_===3?x+a:x;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const B=s.toBytes(S),T=t.fromBytes(Tn(Mp((_&1)===0),B)),q=o.inv(S),L=R(je("msgHash",w)),k=o.create(-L*q),z=o.create(A*q),H=t.BASE.multiplyUnsafe(k).add(T.multiplyUnsafe(z));if(H.is0())throw new Error("point at infinify");return H.assertValidity(),H}hasHighS(){return y(this.s)}toBytes(w=g){if(Nc(w),w==="der")return Ys(cn.hexFromSig(this));const b=o.toBytes(this.r),x=o.toBytes(this.s);if(w==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Tn(Uint8Array.of(this.recovery),b,x)}return Tn(b,x)}toHex(w){return Lr(this.toBytes(w))}assertValidity(){}static fromCompact(w){return E.fromBytes(je("sig",w),"compact")}static fromDER(w){return E.fromBytes(je("sig",w),"der")}normalizeS(){return this.hasHighS()?new E(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Lr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Lr(this.toBytes("compact"))}}const $=n.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const w=oo(m),b=m.length*8-c;return b>0?w>>BigInt(b):w},R=n.bits2int_modN||function(m){return o.create($(m))},C=Ri(c);function U(m){return Oc("num < 2^"+c,m,un,C),o.toBytes(m)}function N(m,w){return lr(m,void 0,"message"),w?lr(e(m),void 0,"prehashed message"):m}function O(m,w,b){if(["recovered","canonical"].some(z=>z in b))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:A,extraEntropy:_}=Uc(b,p);m=N(m,A);const S=R(m),B=Kr(o,w),T=[U(B),U(S)];if(_!=null&&_!==!1){const z=_===!0?r(d.secretKey):_;T.push(je("extraEntropy",z))}const q=Tn(...T),L=S;function k(z){const H=$(z);if(!o.isValidNot0(H))return;const Z=o.inv(H),V=t.BASE.multiply(H).toAffine(),Y=o.create(V.x);if(Y===un)return;const he=o.create(Z*o.create(L+Y*B));if(he===un)return;let Ke=(V.x===Y?0:2)|Number(V.y&zr),mt=he;return x&&y(he)&&(mt=o.neg(he),Ke^=1),new E(Y,mt,Ke)}return{seed:q,k2sig:k}}function G(m,w,b={}){m=je("message",m);const{seed:x,k2sig:A}=O(m,w,b);return J8(e.outputLen,o.BYTES,i)(x,A)}function W(m){let w;const b=typeof m=="string"||Gs(m),x=!b&&m!==null&&typeof m=="object"&&typeof m.r=="bigint"&&typeof m.s=="bigint";if(!b&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)w=new E(m.r,m.s);else if(b){try{w=E.fromBytes(je("sig",m),"der")}catch(A){if(!(A instanceof cn.Err))throw A}if(!w)try{w=E.fromBytes(je("sig",m),"compact")}catch{return!1}}return w||!1}function P(m,w,b,x={}){const{lowS:A,prehash:_,format:S}=Uc(x,p);if(b=je("publicKey",b),w=N(je("message",w),_),"strict"in x)throw new Error("options.strict was renamed to lowS");const B=S===void 0?W(m):E.fromBytes(je("sig",m),S);if(B===!1)return!1;try{const T=t.fromBytes(b);if(A&&B.hasHighS())return!1;const{r:q,s:L}=B,k=R(w),z=o.inv(L),H=o.create(k*z),Z=o.create(q*z),V=t.BASE.multiplyUnsafe(H).add(T.multiplyUnsafe(Z));return V.is0()?!1:o.create(V.x)===q}catch{return!1}}function v(m,w,b={}){const{prehash:x}=Uc(b,p);return w=N(w,x),E.fromBytes(m,"recovered").recoverPublicKey(w).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:h,lengths:d,Point:t,sign:G,verify:P,recoverPublicKey:v,Signature:E,hash:e})}function BI(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const i=Ln(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:n,Fn:i,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function TI(t){const{CURVE:e,curveOpts:n}=BI(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 PI(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,Op(n.Fn.ORDER,n.Fn.BITS))})}function RI(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=TI(t),s=AI(e,n),o=$I(s,r,i);return PI(t,o)}function Fc(t,e){const n=r=>RI(Si(Ur({},t),{hash:r}));return Si(Ur({},n(e)),{create:n})}const qp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},zp={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Kp={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},CI=Ln(qp.p),NI=Ln(zp.p),UI=Ln(Kp.p),FI=Fc(Si(Ur({},qp),{Fp:CI,lowS:!1}),Js);Fc(Si(Ur({},zp),{Fp:NI,lowS:!1}),zx),Fc(Si(Ur({},Kp),{Fp:UI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),qx);const kI=FI,Vp="base10",Xe="base16",ot="base64pad",Mn="base64url",Ni="utf8",Hp=0,ln=1,Ui=2,LI=0,Wp=1,Fi=12,kc=32;function MI(){const t=Cc.utils.randomPrivateKey(),e=Cc.getPublicKey(t);return{privateKey:rt(t,Xe),publicKey:rt(e,Xe)}}function Lc(){const t=cr(kc);return rt(t,Xe)}function jI(t,e){const n=Cc.getSharedSecret(xt(t,Xe),xt(e,Xe)),r=Y8(ro,n,void 0,void 0,kc);return rt(r,Xe)}function fo(t){const e=ro(xt(t,Xe));return rt(e,Xe)}function St(t){const e=ro(xt(t,Ni));return rt(e,Xe)}function Gp(t){return xt(`${t}`,Vp)}function dr(t){return Number(rt(t,Vp))}function Zp(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Yp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function qI(t){const e=Gp(typeof t.type<"u"?t.type:Hp);if(dr(e)===ln&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?xt(t.senderPublicKey,Xe):void 0,r=typeof t.iv<"u"?xt(t.iv,Xe):cr(Fi),i=xt(t.symKey,Xe),s=fp(i,r).encrypt(xt(t.message,Ni)),o=Xp({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===Mn?Zp(o):o}function zI(t){const e=xt(t.symKey,Xe),{sealed:n,iv:r}=ki({encoded:t.encoded,encoding:t.encoding}),i=fp(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return rt(i,Ni)}function KI(t,e){const n=Gp(Ui),r=cr(Fi),i=xt(t,Ni),s=Xp({type:n,sealed:i,iv:r});return e===Mn?Zp(s):s}function VI(t,e){const{sealed:n}=ki({encoded:t,encoding:e});return rt(n,Ni)}function Xp(t){if(dr(t.type)===Ui)return rt(vi([t.type,t.sealed]),ot);if(dr(t.type)===ln){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return rt(vi([t.type,t.senderPublicKey,t.iv,t.sealed]),ot)}return rt(vi([t.type,t.iv,t.sealed]),ot)}function ki(t){const e=(t.encoding||ot)===Mn?Yp(t.encoded):t.encoded,n=xt(e,ot),r=n.slice(LI,Wp),i=Wp;if(dr(r)===ln){const c=i+kc,u=c+Fi,l=n.slice(i,c),f=n.slice(c,u),h=n.slice(u);return{type:r,sealed:h,iv:f,senderPublicKey:l}}if(dr(r)===Ui){const c=n.slice(i),u=cr(Fi);return{type:r,sealed:c,iv:u}}const s=i+Fi,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function HI(t,e){const n=ki({encoded:t,encoding:e?.encoding});return Jp({type:dr(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?rt(n.senderPublicKey,Xe):void 0,receiverPublicKey:e?.receiverPublicKey})}function Jp(t){const e=t?.type||Hp;if(e===ln){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function Qp(t){return t.type===ln&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function eg(t){return t.type===Ui}function WI(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return vi([new Uint8Array([4]),e,n])}function GI(t,e){const[n,r,i]=t.split("."),s=Buffer.from(Yp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,u=ro(c),l=WI(e);if(!kI.verify(vi([o,a]),u,l))throw new Error("Invalid signature");return oa(t).payload}const ZI="irn";function po(t){return t?.relay||{protocol:ZI}}function Vr(t){const e=m_[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var YI=Object.defineProperty,XI=Object.defineProperties,JI=Object.getOwnPropertyDescriptors,tg=Object.getOwnPropertySymbols,QI=Object.prototype.hasOwnProperty,eS=Object.prototype.propertyIsEnumerable,ng=(t,e,n)=>e in t?YI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Mc=(t,e)=>{for(var n in e||(e={}))QI.call(e,n)&&ng(t,n,e[n]);if(tg)for(var n of tg(e))eS.call(e,n)&&ng(t,n,e[n]);return t},tS=(t,e)=>XI(t,JI(e));function nS(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=t[i];n[s]=o}}),n}function rg(t){if(!t.includes("wc:")){const u=Od(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,n).split("@"),s=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:rS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:nS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function rS(t){return t.startsWith("//")?t.substring(2):t}function iS(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(i=>{const s=i,o=n+e+s;t[s]&&(r[o]=t[s])}),r}function ig(t){const e=new URLSearchParams,n=Mc(Mc(tS(Mc({},iS(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(n).sort(([r],[i])=>r.localeCompare(i)).forEach(([r,i])=>{i!==void 0&&e.append(r,String(i))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function go(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var sS=Object.defineProperty,oS=Object.defineProperties,aS=Object.getOwnPropertyDescriptors,sg=Object.getOwnPropertySymbols,cS=Object.prototype.hasOwnProperty,uS=Object.prototype.propertyIsEnumerable,og=(t,e,n)=>e in t?sS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lS=(t,e)=>{for(var n in e||(e={}))cS.call(e,n)&&og(t,n,e[n]);if(sg)for(var n of sg(e))uS.call(e,n)&&og(t,n,e[n]);return t},hS=(t,e)=>oS(t,aS(e));function Hr(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function fS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Hr(n.accounts))}),e}function dS(t,e){const n=[];return Object.values(t).forEach(r=>{Hr(r.accounts).includes(e)&&n.push(...r.methods)}),n}function pS(t,e){const n=[];return Object.values(t).forEach(r=>{Hr(r.accounts).includes(e)&&n.push(...r.events)}),n}function ag(t){return t.includes(":")}function gS(t){return ag(t)?t.split(":")[0]:t}function cg(t){var e,n,r;const i={};if(!Li(t))return i;for(const[s,o]of Object.entries(t)){const a=ag(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=gS(s);i[l]=hS(lS({},i[l]),{chains:ar(a,(e=i[l])==null?void 0:e.chains),methods:ar(c,(n=i[l])==null?void 0:n.methods),events:ar(u,(r=i[l])==null?void 0:r.events)})}return i}function yS(t){const e={};return t?.forEach(n=>{var r;const[i,s]=n.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(n),(r=e[i].chains)==null||r.push(`${i}:${s}`)}),e}function ug(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=yS(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=ar(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function wS(t,e){var n,r,i,s,o,a;const c=cg(t),u=cg(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const h of f)l[h]={chains:ar((n=c[h])==null?void 0:n.chains,(r=u[h])==null?void 0:r.chains),methods:ar((i=c[h])==null?void 0:i.methods,(s=u[h])==null?void 0:s.methods),events:ar((o=c[h])==null?void 0:o.events,(a=u[h])==null?void 0:a.events)};return l}const bS={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}},mS={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function j(t,e){const{message:n,code:r}=mS[t];return{message:e?`${n} ${e}`:n,code:r}}function fe(t,e){const{message:n,code:r}=bS[t];return{message:e?`${n} ${e}`:n,code:r}}function Wr(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Li(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function ge(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function jc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function vS(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return sr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Hr(a),f=n[o];(!sr(wd(o,f),l)||!sr(f.methods,c)||!sr(f.events,u))&&(s=!1)}),s):!1}function Mi(t){return ge(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function ES(t){if(ge(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Mi(n)}}return!1}function _S(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(ge(t,!1)){if(e(t))return!0;const n=Od(t);return e(n)}}catch{}return!1}function xS(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function IS(t){return t?.topic}function SS(t,e){let n=null;return ge(t?.publicKey,!1)||(n=j("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function lg(t){let e=!0;return Wr(t)?t.length&&(e=t.every(n=>ge(n,!1))):e=!1,e}function DS(t,e,n){let r=null;return Wr(e)&&e.length?e.forEach(i=>{r||Mi(i)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Mi(t)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function AS(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=DS(i,wd(i,s),`${e} ${n}`);o&&(r=o)}),r}function OS(t,e){let n=null;return Wr(t)?t.forEach(r=>{n||ES(r)||(n=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function $S(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=OS(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function BS(t,e){let n=null;return lg(t?.methods)?lg(t?.events)||(n=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function hg(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=BS(r,`${e}, namespace`);i&&(n=i)}),n}function TS(t,e,n){let r=null;if(t&&Li(t)){const i=hg(t,e);i&&(r=i);const s=AS(t,e,n);s&&(r=s)}else r=j("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function qc(t,e){let n=null;if(t&&Li(t)){const r=hg(t,e);r&&(n=r);const i=$S(t,e);i&&(n=i)}else n=j("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function fg(t){return ge(t.protocol,!0)}function PS(t,e){let n=!1;return e&&!t?n=!0:t&&Wr(t)&&t.length&&t.forEach(r=>{n=fg(r)}),n}function RS(t){return typeof t=="number"}function at(t){return typeof t<"u"&&typeof t!==null}function CS(t){return!(!t||typeof t!="object"||!t.code||!jc(t.code,!1)||!t.message||!ge(t.message,!1))}function NS(t){return!(_e(t)||!ge(t.method,!1))}function US(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!jc(t.id,!1)||!ge(t.jsonrpc,!1))}function FS(t){return!(_e(t)||!ge(t.name,!1))}function dg(t,e){return!(!Mi(e)||!fS(t).includes(e))}function kS(t,e,n){return ge(n,!1)?dS(t,e).includes(n):!1}function LS(t,e,n){return ge(n,!1)?pS(t,e).includes(n):!1}function pg(t,e,n){let r=null;const i=MS(t),s=jS(e),o=Object.keys(i),a=Object.keys(s),c=gg(Object.keys(t)),u=gg(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
23
+ Required: ${l.toString()}
24
+ Received: ${Object.keys(e).toString()}`)),sr(o,a)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
25
+ Required: ${o.toString()}
26
+ Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||r)return;const h=Hr(e[f].accounts);h.includes(f)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${f}
27
+ Required: ${f}
28
+ Approved: ${h.toString()}`))}),o.forEach(f=>{r||(sr(i[f].methods,s[f].methods)?sr(i[f].events,s[f].events)||(r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${f}`)):r=j("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${f}`))}),r}function MS(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(i=>{e[i]={methods:t[n].methods,events:t[n].events}})}),e}function gg(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function jS(t){const e={};return Object.keys(t).forEach(n=>{if(n.includes(":"))e[n]=t[n];else{const r=Hr(t[n].accounts);r?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}}),e}function qS(t,e){return jc(t,!1)&&t<=e.max&&t>=e.min}function yg(){const t=Di();return new Promise(e=>{switch(t){case pt.browser:e(zS());break;case pt.reactNative:e(KS());break;case pt.node:e(VS());break;default:e(!0)}})}function zS(){return Fr()&&navigator?.onLine}async function KS(){if(Sn()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t?.isConnected}return!0}function VS(){return!0}function HS(t){switch(Di()){case pt.browser:WS(t);break;case pt.reactNative:GS(t);break}}function WS(t){!Sn()&&Fr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function GS(t){Sn()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function ZS(){var t;return Fr()&&Xn()?((t=Xn())==null?void 0:t.visibilityState)==="visible":!0}const zc={};class ji{static get(e){return zc[e]}static set(e,n){zc[e]=n}static delete(e){delete zc[e]}}function YS(t){const e=pi.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function XS({publicKey:t,signature:e,payload:n}){var r;const i=Kc(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=e6(n.address),a=n.era==="00"?new Uint8Array([0]):Kc(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${QS(n.tip)}`),f=n6(l),h=new Uint8Array([0,...t,o,...e,...a,...u,...f,...i]),d=t6(h.length+1);return new Uint8Array([...d,s,...h])}function JS(t){const e=Kc(t),n=T_.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function Kc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function QS(t){return t.startsWith("0x")?t.slice(2):t}function e6(t){const e=pi.decode(t)[0];return e===42?0:e===60?2:1}function t6(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 n6(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function r6(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=YS(t.transaction.address),r=XS({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return JS(i)}const i6="PARSE_ERROR",s6="INVALID_REQUEST",o6="METHOD_NOT_FOUND",a6="INVALID_PARAMS",wg="INTERNAL_ERROR",Vc="SERVER_ERROR",c6=[-32700,-32600,-32601,-32602,-32603],qi={[i6]:{code:-32700,message:"Parse error"},[s6]:{code:-32600,message:"Invalid Request"},[o6]:{code:-32601,message:"Method not found"},[a6]:{code:-32602,message:"Invalid params"},[wg]:{code:-32603,message:"Internal error"},[Vc]:{code:-32e3,message:"Server error"}},bg=Vc;function u6(t){return c6.includes(t)}function mg(t){return Object.keys(qi).includes(t)?qi[t]:qi[bg]}function l6(t){const e=Object.values(qi).find(n=>n.code===t);return e||qi[bg]}function h6(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var vg={};/*! *****************************************************************************
29
+ Copyright (c) Microsoft Corporation.
30
+
31
+ Permission to use, copy, modify, and/or distribute this software for any
32
+ purpose with or without fee is hereby granted.
33
+
34
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
35
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
36
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
37
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
38
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
39
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
40
+ PERFORMANCE OF THIS SOFTWARE.
41
+ ***************************************************************************** */var Hc=function(t,e){return Hc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Hc(t,e)};function f6(t,e){Hc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Wc=function(){return Wc=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},Wc.apply(this,arguments)};function d6(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function p6(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function g6(t,e){return function(n,r){e(n,r,t)}}function y6(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function w6(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(f){o(f)}}function c(l){try{u(r.throw(l))}catch(f){o(f)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function b6(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function m6(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function v6(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Gc(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Eg(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function E6(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Eg(arguments[e]));return t}function _6(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function zi(t){return this instanceof zi?(this.v=t,this):new zi(t)}function x6(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(h){r[h]&&(i[h]=function(d){return new Promise(function(p,g){s.push([h,d,p,g])>1||a(h,d)})})}function a(h,d){try{c(r[h](d))}catch(p){f(s[0][3],p)}}function c(h){h.value instanceof zi?Promise.resolve(h.value.v).then(u,l):f(s[0][2],h)}function u(h){a("next",h)}function l(h){a("throw",h)}function f(h,d){h(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function I6(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:zi(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function S6(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Gc=="function"?Gc(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function D6(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function A6(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 O6(t){return t&&t.__esModule?t:{default:t}}function $6(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function B6(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 T6=Object.freeze({__proto__:null,__extends:f6,get __assign(){return Wc},__rest:d6,__decorate:p6,__param:g6,__metadata:y6,__awaiter:w6,__generator:b6,__createBinding:m6,__exportStar:v6,__values:Gc,__read:Eg,__spread:E6,__spreadArrays:_6,__await:zi,__asyncGenerator:x6,__asyncDelegator:I6,__asyncValues:S6,__makeTemplateObject:D6,__importStar:A6,__importDefault:O6,__classPrivateFieldGet:$6,__classPrivateFieldSet:B6}),P6=mu(T6),hn={},_g;function R6(){if(_g)return hn;_g=1,Object.defineProperty(hn,"__esModule",{value:!0}),hn.isBrowserCryptoAvailable=hn.getSubtleCrypto=hn.getBrowerCrypto=void 0;function t(){return kt?.crypto||kt?.msCrypto||{}}hn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}hn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return hn.isBrowserCryptoAvailable=n,hn}var fn={},xg;function C6(){if(xg)return fn;xg=1,Object.defineProperty(fn,"__esModule",{value:!0}),fn.isBrowser=fn.isNode=fn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}fn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}fn.isNode=e;function n(){return!t()&&!e()}return fn.isBrowser=n,fn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=P6;e.__exportStar(R6(),t),e.__exportStar(C6(),t)})(vg);function yt(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function jn(t=6){return BigInt(yt(t))}function dn(t,e,n){return{id:n||yt(),jsonrpc:"2.0",method:t,params:e}}function yo(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Zc(t,e,n){return{id:t,jsonrpc:"2.0",error:N6(e,n)}}function N6(t,e){return typeof t>"u"?mg(wg):(typeof t=="string"&&(t=Object.assign(Object.assign({},mg(Vc)),{message:t})),typeof e<"u"&&(t.data=e),u6(t.code)&&(t=l6(t.code)),t)}class U6{}class F6 extends U6{constructor(){super()}}class k6 extends F6{constructor(e){super()}}const L6="^wss?:";function M6(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function j6(t,e){const n=M6(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function Ig(t){return j6(t,L6)}function q6(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Sg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Yc(t){return Sg(t)&&"method"in t}function wo(t){return Sg(t)&&(Vt(t)||Dt(t))}function Vt(t){return"result"in t}function Dt(t){return"error"in t}class z6 extends k6{constructor(e){super(e),this.events=new He.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(dn(e.method,e.params||[],e.id||jn().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{Dt(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),wo(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const K6=()=>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"),V6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Dg=t=>t.split("?")[0],Ag=10,H6=K6();class W6{constructor(e){if(this.url=e,this.events=new He.exports.EventEmitter,this.registering=!1,!Ig(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Gn(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!Ig(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=vg.isReactNative()?void 0:{rejectUnauthorized:!q6(e)},s=new H6(e,[],i);V6()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?mr(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Zc(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return h6(e,Dg(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ag&&this.events.setMaxListeners(Ag)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Dg(this.url)}`));return this.events.emit("register_error",n),n}}var G6=Object.defineProperty,Og=Object.getOwnPropertySymbols,Z6=Object.prototype.hasOwnProperty,Y6=Object.prototype.propertyIsEnumerable,$g=(t,e,n)=>e in t?G6(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Je=(t,e)=>{for(var n in e||(e={}))Z6.call(e,n)&&$g(t,n,e[n]);if(Og)for(var n of Og(e))Y6.call(e,n)&&$g(t,n,e[n]);return t};const Bg="wc",Tg=2,bo="core",Ht=`${Bg}@2:${bo}:`,X6={name:bo,logger:"error"},J6={database:":memory:"},Q6="crypto",Pg="client_ed25519_seed",e4=M.ONE_DAY,t4="keychain",n4="0.3",r4="messages",i4="0.3",s4=M.SIX_HOURS,o4="publisher",Rg="irn",a4="error",Cg="wss://relay.walletconnect.org",c4="relayer",pe={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},u4="_subscription",At={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},l4=.1,Xc="2.21.8",le={link_mode:"link_mode",relay:"relay"},mo={inbound:"inbound",outbound:"outbound"},h4="0.3",f4="WALLETCONNECT_CLIENT_ID",Ng="WALLETCONNECT_LINK_MODE_APPS",wt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},d4="subscription",p4="0.3",g4="pairing",y4="0.3",Ki={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},pr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ut={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},w4="history",b4="0.3",m4="expirer",Ot={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},v4="0.3",E4="verify-api",_4="https://verify.walletconnect.com",Ug="https://verify.walletconnect.org",Vi=Ug,x4=`${Vi}/v3`,I4=[_4,Ug],S4="echo",D4="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"},pn={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},qn={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},Hi={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},gr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Wi={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},A4=.1,O4="event-client",$4=86400,B4="https://pulse.walletconnect.org/batch";function T4(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function f(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,y=0,I=0,D=p.length;I!==D&&p[I]===0;)I++,g++;for(var E=(D-I)*l+1>>>0,$=new Uint8Array(E);I!==D;){for(var R=p[I],C=0,U=E-1;(R!==0||C<y)&&U!==-1;U--,C++)R+=256*$[U]>>>0,$[U]=R%a>>>0,R=R/a>>>0;if(R!==0)throw new Error("Non-zero carry");y=C,I++}for(var N=E-y;N!==E&&$[N]===0;)N++;for(var O=c.repeat(g);N<E;++N)O+=t.charAt($[N]);return O}function h(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var y=0,I=0;p[g]===c;)y++,g++;for(var D=(p.length-g)*u+1>>>0,E=new Uint8Array(D);p[g];){var $=n[p.charCodeAt(g)];if($===255)return;for(var R=0,C=D-1;($!==0||R<I)&&C!==-1;C--,R++)$+=a*E[C]>>>0,E[C]=$%256>>>0,$=$/256>>>0;if($!==0)throw new Error("Non-zero carry");I=R,g++}if(p[g]!==" "){for(var U=D-I;U!==D&&E[U]===0;)U++;for(var N=new Uint8Array(y+(D-U)),O=y;U!==D;)N[O++]=E[U++];return N}}}function d(p){var g=h(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:h,decode:d}}var P4=T4,R4=P4;const Fg=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")},C4=t=>new TextEncoder().encode(t),N4=t=>new TextDecoder().decode(t);class U4{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class F4{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 kg(this,e)}}class k4{constructor(e){this.decoders=e}or(e){return kg(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 kg=(t,e)=>new k4(Je(Je({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class L4{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new U4(e,n,r),this.decoder=new F4(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const vo=({name:t,prefix:e,encode:n,decode:r})=>new L4(t,e,n,r),Gi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=R4(n,e);return vo({prefix:t,name:e,encode:r,decode:s=>Fg(i(s))})},M4=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const f=i[t[l]];if(f===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|f,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},j4=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Be=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>vo({prefix:e,name:t,encode(i){return j4(i,r,n)},decode(i){return M4(i,r,n,t)}}),q4=vo({prefix:"\0",name:"identity",encode:t=>N4(t),decode:t=>C4(t)});var z4=Object.freeze({__proto__:null,identity:q4});const K4=Be({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var V4=Object.freeze({__proto__:null,base2:K4});const H4=Be({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var W4=Object.freeze({__proto__:null,base8:H4});const G4=Gi({prefix:"9",name:"base10",alphabet:"0123456789"});var Z4=Object.freeze({__proto__:null,base10:G4});const Y4=Be({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),X4=Be({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var J4=Object.freeze({__proto__:null,base16:Y4,base16upper:X4});const Q4=Be({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),eD=Be({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),tD=Be({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),nD=Be({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),rD=Be({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),iD=Be({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),sD=Be({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),oD=Be({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),aD=Be({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var cD=Object.freeze({__proto__:null,base32:Q4,base32upper:eD,base32pad:tD,base32padupper:nD,base32hex:rD,base32hexupper:iD,base32hexpad:sD,base32hexpadupper:oD,base32z:aD});const uD=Gi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),lD=Gi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var hD=Object.freeze({__proto__:null,base36:uD,base36upper:lD});const fD=Gi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),dD=Gi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var pD=Object.freeze({__proto__:null,base58btc:fD,base58flickr:dD});const gD=Be({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),yD=Be({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),wD=Be({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),bD=Be({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var mD=Object.freeze({__proto__:null,base64:gD,base64pad:yD,base64url:wD,base64urlpad:bD});const Lg=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}"),vD=Lg.reduce((t,e,n)=>(t[n]=e,t),[]),ED=Lg.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function _D(t){return t.reduce((e,n)=>(e+=vD[n],e),"")}function xD(t){const e=[];for(const n of t){const r=ED[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const ID=vo({prefix:"\u{1F680}",name:"base256emoji",encode:_D,decode:xD});var SD=Object.freeze({__proto__:null,base256emoji:ID}),DD=jg,Mg=128,AD=127,OD=~AD,$D=Math.pow(2,31);function jg(t,e,n){e=e||[],n=n||0;for(var r=n;t>=$D;)e[n++]=t&255|Mg,t/=128;for(;t&OD;)e[n++]=t&255|Mg,t>>>=7;return e[n]=t|0,jg.bytes=n-r+1,e}var BD=Jc,TD=128,qg=127;function Jc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Jc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&qg)<<i:(o&qg)*Math.pow(2,i),i+=7}while(o>=TD);return Jc.bytes=s-r,n}var PD=Math.pow(2,7),RD=Math.pow(2,14),CD=Math.pow(2,21),ND=Math.pow(2,28),UD=Math.pow(2,35),FD=Math.pow(2,42),kD=Math.pow(2,49),LD=Math.pow(2,56),MD=Math.pow(2,63),jD=function(t){return t<PD?1:t<RD?2:t<CD?3:t<ND?4:t<UD?5:t<FD?6:t<kD?7:t<LD?8:t<MD?9:10},qD={encode:DD,decode:BD,encodingLength:jD},zg=qD;const Kg=(t,e,n=0)=>(zg.encode(t,e,n),e),Vg=t=>zg.encodingLength(t),Qc=(t,e)=>{const n=e.byteLength,r=Vg(t),i=r+Vg(n),s=new Uint8Array(i+n);return Kg(t,s,0),Kg(n,s,r),s.set(e,i),new zD(t,n,e,s)};class zD{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Hg=({name:t,code:e,encode:n})=>new KD(t,e,n);class KD{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Qc(this.code,n):n.then(r=>Qc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Wg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),VD=Hg({name:"sha2-256",code:18,encode:Wg("SHA-256")}),HD=Hg({name:"sha2-512",code:19,encode:Wg("SHA-512")});var WD=Object.freeze({__proto__:null,sha256:VD,sha512:HD});const Gg=0,GD="identity",Zg=Fg;var ZD=Object.freeze({__proto__:null,identity:{code:Gg,name:GD,encode:Zg,digest:t=>Qc(Gg,Zg(t))}});new TextEncoder,new TextDecoder;const Yg=Je(Je(Je(Je(Je(Je(Je(Je(Je(Je({},z4),V4),W4),Z4),J4),cD),hD),pD),mD),SD);Je(Je({},WD),ZD);function Xg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function YD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Xg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jg(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Qg=Jg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),eu=Jg("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=YD(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),XD=Je({utf8:Qg,"utf-8":Qg,hex:Yg.base16,latin1:eu,ascii:eu,binary:eu},Yg);function JD(t,e="utf8"){const n=XD[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Xg(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var QD=Object.defineProperty,eA=(t,e,n)=>e in t?QD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gt=(t,e,n)=>eA(t,typeof e!="symbol"?e+"":e,n);class tA{constructor(e,n){this.core=e,this.logger=n,Gt(this,"keychain",new Map),Gt(this,"name",t4),Gt(this,"version",n4),Gt(this,"initialized",!1),Gt(this,"storagePrefix",Ht),Gt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Gt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Gt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Gt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=j("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),Gt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=We(n,this.name)}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,sc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?oc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var nA=Object.defineProperty,rA=(t,e,n)=>e in t?nA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Te=(t,e,n)=>rA(t,typeof e!="symbol"?e+"":e,n);class iA{constructor(e,n,r){this.core=e,this.logger=n,Te(this,"name",Q6),Te(this,"keychain"),Te(this,"randomSessionIdentifier",Lc()),Te(this,"initialized",!1),Te(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Te(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Te(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Jl(i);return Xl(s.publicKey)}),Te(this,"generateKeyPair",()=>{this.isInitialized();const i=MI();return this.setPrivateKey(i.publicKey,i.privateKey)}),Te(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Jl(s),a=this.randomSessionIdentifier;return await Rm(a,i,e4,o)}),Te(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=jI(a,s);return this.setSymKey(c,o)}),Te(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||fo(i);return await this.keychain.set(o,i),o}),Te(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Te(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Jp(o),c=Gn(s);if(eg(a))return KI(c,o?.encoding);if(Qp(a)){const h=a.senderPublicKey,d=a.receiverPublicKey;i=await this.generateSharedKey(h,d)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return qI({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Te(this,"decode",async(i,s,o)=>{this.isInitialized();const a=HI(s,o);if(eg(a)){const c=VI(s,o?.encoding);return mr(c)}if(Qp(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=zI({symKey:c,encoded:s,encoding:o?.encoding});return mr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Te(this,"getPayloadType",(i,s=ot)=>{const o=ki({encoded:i,encoding:s});return dr(o.type)}),Te(this,"getPayloadSenderPublicKey",(i,s=ot)=>{const o=ki({encoded:i,encoding:s});return o.senderPublicKey?rt(o.senderPublicKey,Xe):void 0}),this.core=e,this.logger=We(n,this.name),this.keychain=r||new tA(this.core,this.logger)}get context(){return et(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Pg)}catch{e=Lc(),await this.keychain.set(Pg,e)}return JD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var sA=Object.defineProperty,oA=Object.defineProperties,aA=Object.getOwnPropertyDescriptors,e0=Object.getOwnPropertySymbols,cA=Object.prototype.hasOwnProperty,uA=Object.prototype.propertyIsEnumerable,tu=(t,e,n)=>e in t?sA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,lA=(t,e)=>{for(var n in e||(e={}))cA.call(e,n)&&tu(t,n,e[n]);if(e0)for(var n of e0(e))uA.call(e,n)&&tu(t,n,e[n]);return t},hA=(t,e)=>oA(t,aA(e)),bt=(t,e,n)=>tu(t,typeof e!="symbol"?e+"":e,n);class fA extends P1{constructor(e,n){super(e,n),this.logger=e,this.core=n,bt(this,"messages",new Map),bt(this,"messagesWithoutClientAck",new Map),bt(this,"name",r4),bt(this,"version",i4),bt(this,"initialized",!1),bt(this,"storagePrefix",Ht),bt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),bt(this,"set",async(r,i,s)=>{this.isInitialized();const o=St(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===mo.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,hA(lA({},c),{[o]:i}))}return await this.persist(),o}),bt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),bt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),bt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=St(i);return typeof s[o]<"u"}),bt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=St(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),bt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=We(e,this.name),this.core=n}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,sc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,sc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?oc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?oc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var dA=Object.defineProperty,pA=Object.defineProperties,gA=Object.getOwnPropertyDescriptors,t0=Object.getOwnPropertySymbols,yA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,nu=(t,e,n)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gr=(t,e)=>{for(var n in e||(e={}))yA.call(e,n)&&nu(t,n,e[n]);if(t0)for(var n of t0(e))wA.call(e,n)&&nu(t,n,e[n]);return t},n0=(t,e)=>pA(t,gA(e)),$t=(t,e,n)=>nu(t,typeof e!="symbol"?e+"":e,n);class bA extends R1{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,$t(this,"events",new He.exports.EventEmitter),$t(this,"name",o4),$t(this,"queue",new Map),$t(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),$t(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),$t(this,"needsTransportRestart",!1),$t(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const f=s?.ttl||s4,h=s?.prompt||!1,d=s?.tag||0,p=s?.id||jn().toString(),g=Vr(po().protocol),y={id:p,method:s?.publishMethod||g.publish,params:Gr({topic:r,message:i,ttl:f,prompt:h,tag:d,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),_e((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const D=new Promise(async E=>{const $=({id:C})=>{var U;((U=y.id)==null?void 0:U.toString())===C.toString()&&(this.removeRequestFromQueue(C),this.relayer.events.removeListener(pe.publish,$),E())};this.relayer.events.on(pe.publish,$);const R=zt(new Promise((C,U)=>{this.rpcPublish(y,s).then(C).catch(N=>{this.logger.warn(N,N?.message),U(N)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await R,this.events.removeListener(pe.publish,$)}catch(C){this.queue.set(p,{request:y,opts:s,attempt:1}),this.logger.warn(C,C?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await zt(D,this.publishTimeout,I)}catch(D){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(D),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw D}finally{this.queue.delete(p)}}),$t(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:l={}}=r,{attestation:f,tvf:h,publishMethod:d,prompt:p,tag:g,ttl:y=M.FIVE_MINUTES}=l,I=l.id||jn().toString(),D=Vr(po().protocol),E=d||D.publish,$={id:I,method:E,params:Gr(n0(Gr({},u),{ttl:y,prompt:p,tag:g,attestation:f}),h)},R=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((i=$.params)==null?void 0:i.prompt)&&((s=$.params)==null||delete s.prompt),_e((o=$.params)==null?void 0:o.tag)&&((a=$.params)==null||delete a.tag);const C=new Promise(async U=>{const N=({id:G})=>{var W;((W=$.id)==null?void 0:W.toString())===G.toString()&&(this.removeRequestFromQueue(G),this.relayer.events.removeListener(pe.publish,N),U())};this.relayer.events.on(pe.publish,N);const O=zt(new Promise((G,W)=>{this.rpcPublish($,l).then(G).catch(P=>{this.logger.warn(P,P?.message),W(P)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${E} id:${I} tag:${g}`);try{await O,this.events.removeListener(pe.publish,N)}catch(G){this.queue.set(I,{request:$,opts:l,attempt:1}),this.logger.warn(G,G?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:I,payload:u,opts:l}}),await zt(C,this.publishTimeout,R)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw C}finally{this.queue.delete(I)}}),$t(this,"on",(r,i)=>{this.events.on(r,i)}),$t(this,"once",(r,i)=>{this.events.once(r,i)}),$t(this,"off",(r,i)=>{this.events.off(r,i)}),$t(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=We(n,this.name),this.registerEventListeners()}get context(){return et(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(pe.publish,Gr(Gr({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,n0(Gr({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Hn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(pe.connection_stalled);return}this.checkQueue()}),this.relayer.on(pe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var mA=Object.defineProperty,vA=(t,e,n)=>e in t?mA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zr=(t,e,n)=>vA(t,typeof e!="symbol"?e+"":e,n);class EA{constructor(){Zr(this,"map",new Map),Zr(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Zr(this,"get",e=>this.map.get(e)||[]),Zr(this,"exists",(e,n)=>this.get(e).includes(n)),Zr(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),Zr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var _A=Object.defineProperty,xA=Object.defineProperties,IA=Object.getOwnPropertyDescriptors,r0=Object.getOwnPropertySymbols,SA=Object.prototype.hasOwnProperty,DA=Object.prototype.propertyIsEnumerable,ru=(t,e,n)=>e in t?_A(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Zi=(t,e)=>{for(var n in e||(e={}))SA.call(e,n)&&ru(t,n,e[n]);if(r0)for(var n of r0(e))DA.call(e,n)&&ru(t,n,e[n]);return t},iu=(t,e)=>xA(t,IA(e)),ae=(t,e,n)=>ru(t,typeof e!="symbol"?e+"":e,n);class AA extends U1{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,ae(this,"subscriptions",new Map),ae(this,"topicMap",new EA),ae(this,"events",new He.exports.EventEmitter),ae(this,"name",d4),ae(this,"version",p4),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",Ht),ae(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=po(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ae(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),ae(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),ae(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ae(this,"on",(r,i)=>{this.events.on(r,i)}),ae(this,"once",(r,i)=>{this.events.once(r,i)}),ae(this,"off",(r,i)=>{this.events.off(r,i)}),ae(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Hn.pulse,async()=>{await this.checkPending()}),this.events.on(wt.created,async r=>{const i=wt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(wt.deleted,async r=>{const i=wt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=We(n,this.name),this.clientId=""}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=po(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===le.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Vr(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===le.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async f=>{const h=d=>{d.topic===e&&(this.events.removeListener(wt.created,h),f(d.id))};this.events.on(wt.created,h);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(wt.created,h),f(d)}catch{}}),l=await zt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(pe.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Vr(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await zt(new Promise(i=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Vr(n.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await zt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(pe.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Vr(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,iu(Zi({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Zi({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,Zi({},n)),this.topicMap.set(n.topic,e),this.events.emit(wt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(wt.deleted,iu(Zi({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(wt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(wt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async n=>iu(Zi({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await cx(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return St(e+await this.getClientId())}}var OA=Object.defineProperty,i0=Object.getOwnPropertySymbols,$A=Object.prototype.hasOwnProperty,BA=Object.prototype.propertyIsEnumerable,su=(t,e,n)=>e in t?OA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,s0=(t,e)=>{for(var n in e||(e={}))$A.call(e,n)&&su(t,n,e[n]);if(i0)for(var n of i0(e))BA.call(e,n)&&su(t,n,e[n]);return t},re=(t,e,n)=>su(t,typeof e!="symbol"?e+"":e,n);class TA extends C1{constructor(e){super(e),re(this,"protocol","wc"),re(this,"version",2),re(this,"core"),re(this,"logger"),re(this,"events",new He.exports.EventEmitter),re(this,"provider"),re(this,"messages"),re(this,"subscriber"),re(this,"publisher"),re(this,"name",c4),re(this,"transportExplicitlyClosed",!1),re(this,"initialized",!1),re(this,"connectionAttemptInProgress",!1),re(this,"relayUrl"),re(this,"projectId"),re(this,"packageName"),re(this,"bundleId"),re(this,"hasExperiencedNetworkDisruption",!1),re(this,"pingTimeout"),re(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),re(this,"reconnectTimeout"),re(this,"connectPromise"),re(this,"reconnectInProgress",!1),re(this,"requestsInFlight",[]),re(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),re(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const s=n.id||jn().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${s}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),re(this,"resetPingTimeout",()=>{Hs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),re(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),re(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(pe.connect)}),re(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),re(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(pe.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),re(this,"registerProviderListeners",()=>{this.provider.on(At.payload,this.onPayloadHandler),this.provider.on(At.connect,this.onConnectHandler),this.provider.on(At.disconnect,this.onDisconnectHandler),this.provider.on(At.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?We(e.logger,this.name):Yt(Lo({level:e.logger||a4})),this.messages=new fA(this.logger,e.core),this.subscriber=new AA(this,this.logger),this.publisher=new bA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Cg,H_()?this.packageName=Ed():W_()&&(this.bundleId=Ed()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return et(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:le.relay},mo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(wt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(wt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,s0({internal:{throwOnFailedPublish:o}},n)).catch(h=>{o&&f(h)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await yg())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const i=ve(M.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(pe.message,e),await this.recordMessageEvent(e,mo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(At.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(At.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(At.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(At.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,M.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Hs())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new z6(new W6(J_({sdkVersion:Xc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Yc(e)){if(!e.method.endsWith(u4))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:le.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(s0({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else wo(e)&&this.events.emit(pe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,mo.inbound),this.events.emit(pe.message,e))}async acknowledgePayload(e){const n=yo(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(At.payload,this.onPayloadHandler),this.provider.off(At.connect,this.onConnectHandler),this.provider.off(At.disconnect,this.onDisconnectHandler),this.provider.off(At.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await yg();HS(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Hn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&ZS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(pe.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},M.toMiliseconds(l4)))))}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function PA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function o0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function a0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const RA="[object RegExp]",CA="[object String]",NA="[object Number]",UA="[object Boolean]",c0="[object Arguments]",FA="[object Symbol]",kA="[object Date]",LA="[object Map]",MA="[object Set]",jA="[object Array]",qA="[object Function]",zA="[object ArrayBuffer]",ou="[object Object]",KA="[object Error]",VA="[object DataView]",HA="[object Uint8Array]",WA="[object Uint8ClampedArray]",GA="[object Uint16Array]",ZA="[object Uint32Array]",YA="[object BigUint64Array]",XA="[object Int8Array]",JA="[object Int16Array]",QA="[object Int32Array]",eO="[object BigInt64Array]",tO="[object Float32Array]",nO="[object Float64Array]";function rO(){}function u0(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 iO(t,e,n){return Yi(t,e,void 0,void 0,void 0,void 0,n)}function Yi(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Xi(t,e,s,o)}return Xi(t,e,s,o)}function Xi(t,e,n,r){if(Object.is(t,e))return!0;let i=a0(t),s=a0(e);if(i===c0&&(i=ou),s===c0&&(s=ou),i!==s)return!1;switch(i){case CA:return t.toString()===e.toString();case NA:{const c=t.valueOf(),u=e.valueOf();return PA(c,u)}case UA:case kA:case FA:return Object.is(t.valueOf(),e.valueOf());case RA:return t.source===e.source&&t.flags===e.flags;case qA:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case LA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Yi(u,e.get(c),c,t,e,n,r))return!1;return!0}case MA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const f=c[l],h=u.findIndex(d=>Yi(f,d,void 0,t,e,n,r));if(h===-1)return!1;u.splice(h,1)}return!0}case jA:case HA:case WA:case GA:case ZA:case YA:case XA:case JA:case QA:case eO:case tO:case nO:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Yi(t[c],e[c],c,t,e,n,r))return!1;return!0}case zA:return t.byteLength!==e.byteLength?!1:Xi(new Uint8Array(t),new Uint8Array(e),n,r);case VA:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Xi(new Uint8Array(t),new Uint8Array(e),n,r);case KA:return t.name===e.name&&t.message===e.message;case ou:{if(!(Xi(t.constructor,e.constructor,n,r)||u0(t)&&u0(e)))return!1;const c=[...Object.keys(t),...o0(t)],u=[...Object.keys(e),...o0(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],h=t[f];if(!Object.hasOwn(e,f))return!1;const d=e[f];if(!Yi(h,d,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function sO(t,e){return iO(t,e,rO)}var oO=Object.defineProperty,l0=Object.getOwnPropertySymbols,aO=Object.prototype.hasOwnProperty,cO=Object.prototype.propertyIsEnumerable,au=(t,e,n)=>e in t?oO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,h0=(t,e)=>{for(var n in e||(e={}))aO.call(e,n)&&au(t,n,e[n]);if(l0)for(var n of l0(e))cO.call(e,n)&&au(t,n,e[n]);return t},ct=(t,e,n)=>au(t,typeof e!="symbol"?e+"":e,n);class yr extends N1{constructor(e,n,r,i=Ht,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,ct(this,"map",new Map),ct(this,"version",h4),ct(this,"cached",[]),ct(this,"initialized",!1),ct(this,"getKey"),ct(this,"storagePrefix",Ht),ct(this,"recentlyDeleted",[]),ct(this,"recentlyDeletedLimit",200),ct(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):xS(o)?this.map.set(o.id,o):IS(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),ct(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())}),ct(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),ct(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>sO(a[c],o[c]))):this.values)),ct(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=h0(h0({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),ct(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=We(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=j("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uO=Object.defineProperty,lO=(t,e,n)=>e in t?uO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Q=(t,e,n)=>lO(t,typeof e!="symbol"?e+"":e,n);class hO{constructor(e,n){this.core=e,this.logger=n,Q(this,"name",g4),Q(this,"version",y4),Q(this,"events",new He.exports),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",Ht),Q(this,"ignoredPayloadTypes",[ln]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),Q(this,"create",async r=>{this.isInitialized();const i=Lc(),s=await this.core.crypto.setSymKey(i),o=ve(M.FIVE_MINUTES),a={protocol:Rg},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=ig({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(pr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:u}}),Q(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Wt.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=rg(r.uri);i.props.properties.topic=s,i.addTrace(Wt.pairing_uri_validation_success),i.addTrace(Wt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Wt.existing_pairing),l.active)throw i.setError(pn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Wt.pairing_not_expired)}const f=c||ve(M.FIVE_MINUTES),h={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,h),i.addTrace(Wt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(pr.create,h),i.addTrace(Wt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(pn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw i.setError(pn.subscribe_pairing_topic_failure),d}return i.addTrace(Wt.subscribe_pairing_topic_success),h}),Q(this,"activate",async({topic:r})=>{this.isInitialized();const i=ve(M.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),Q(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=or();this.events.once(ie("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),Q(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),Q(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),Q(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return ig({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(r,i,s)=>{const o=dn(i,s),a=await this.core.crypto.encode(r,o),c=Ki[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),Q(this,"sendResult",async(r,i,s)=>{const o=yo(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ki[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"sendError",async(r,i,s)=>{const o=Zc(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Ki[c]?Ki[c].res:Ki.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),Q(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>Dn(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),Q(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),Q(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(pr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{Vt(i)?this.events.emit(ie("pairing_ping",s),{}):Dt(i)&&this.events.emit(ie("pairing_ping",s),{error:i.error})},500)}),Q(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(pr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),Q(this,"isValidPair",(r,i)=>{var s;if(!at(r)){const{message:a}=j("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(!_S(r.uri)){const{message:a}=j("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(pn.malformed_pairing_uri),new Error(a)}const o=rg(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=j("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(pn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(pn.pairing_expired);const{message:a}=j("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async r=>{if(!at(r)){const{message:s}=j("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),Q(this,"isValidDisconnect",async r=>{if(!at(r)){const{message:s}=j("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),Q(this,"isValidPairingTopic",async r=>{if(!ge(r,!1)){const{message:i}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(Dn(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=j("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=We(n,this.name),this.pairings=new yr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return et(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(pe.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==le.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Yc(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):wo(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(Ot.expired,async e=>{const{topic:n}=Sd(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(pr.expire,{topic:n}))})}}var fO=Object.defineProperty,dO=(t,e,n)=>e in t?fO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Pe=(t,e,n)=>dO(t,typeof e!="symbol"?e+"":e,n);class pO extends T1{constructor(e,n){super(e,n),this.core=e,this.logger=n,Pe(this,"records",new Map),Pe(this,"events",new He.exports.EventEmitter),Pe(this,"name",w4),Pe(this,"version",b4),Pe(this,"cached",[]),Pe(this,"initialized",!1),Pe(this,"storagePrefix",Ht),Pe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Pe(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:ve(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Ut.created,o)}),Pe(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=Dt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Ut.updated,i))}),Pe(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Pe(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Ut.deleted,s)}}),this.persist()}),Pe(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Pe(this,"on",(r,i)=>{this.events.on(r,i)}),Pe(this,"once",(r,i)=>{this.events.once(r,i)}),Pe(this,"off",(r,i)=>{this.events.off(r,i)}),Pe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=We(n,this.name)}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:dn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ut.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Ut.created,e=>{const n=Ut.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Ut.updated,e=>{const n=Ut.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Ut.deleted,e=>{const n=Ut.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Hn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{M.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(Ut.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gO=Object.defineProperty,yO=(t,e,n)=>e in t?gO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qe=(t,e,n)=>yO(t,typeof e!="symbol"?e+"":e,n);class wO extends F1{constructor(e,n){super(e,n),this.core=e,this.logger=n,qe(this,"expirations",new Map),qe(this,"events",new He.exports.EventEmitter),qe(this,"name",m4),qe(this,"version",v4),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"storagePrefix",Ht),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),qe(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),qe(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(Ot.created,{target:s,expiration:o})}),qe(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),qe(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(Ot.deleted,{target:i,expiration:s})}}),qe(this,"on",(r,i)=>{this.events.on(r,i)}),qe(this,"once",(r,i)=>{this.events.once(r,i)}),qe(this,"off",(r,i)=>{this.events.off(r,i)}),qe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=We(n,this.name)}get context(){return et(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Q_(e);if(typeof e=="number")return ex(e);const{message:n}=j("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=j("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=j("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;M.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Ot.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Hn.pulse,()=>this.checkExpirations()),this.events.on(Ot.created,e=>{const n=Ot.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Ot.expired,e=>{const n=Ot.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Ot.deleted,e=>{const n=Ot.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}}var bO=Object.defineProperty,mO=(t,e,n)=>e in t?bO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ye=(t,e,n)=>mO(t,typeof e!="symbol"?e+"":e,n);class vO extends k1{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,ye(this,"name",E4),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",x4),ye(this,"storagePrefix",Ht),ye(this,"version",Tg),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async i=>{if(!Fr()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=Xn(),l=this.startAbortTimer(M.ONE_SECOND*5),f=await new Promise((h,d)=>{const p=()=>{window.removeEventListener("message",y),u.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const y=I=>{if(I.data&&typeof I.data=="string")try{const D=JSON.parse(I.data);if(D.type==="verify_attestation"){if(oa(D.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",y),h(D.attestation===null?"":D.attestation)}}catch(D){this.logger.warn(D)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",f),f}catch(u){this.logger.warn(u)}return""}),ye(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(oa(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",i=>{let s=i||Vi;return I4.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Vi}`),s=Vi),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),ye(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),ye(this,"validateAttestation",(i,s)=>{const o=GI(i,s.publicKey),a={hasExpired:M.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=We(n,this.name),this.abortController=new AbortController,this.isDevEnv=ac(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return et(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var EO=Object.defineProperty,_O=(t,e,n)=>e in t?EO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,f0=(t,e,n)=>_O(t,typeof e!="symbol"?e+"":e,n);class xO extends L1{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,f0(this,"context",S4),f0(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${D4}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=We(n,this.context)}}var IO=Object.defineProperty,d0=Object.getOwnPropertySymbols,SO=Object.prototype.hasOwnProperty,DO=Object.prototype.propertyIsEnumerable,cu=(t,e,n)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ji=(t,e)=>{for(var n in e||(e={}))SO.call(e,n)&&cu(t,n,e[n]);if(d0)for(var n of d0(e))DO.call(e,n)&&cu(t,n,e[n]);return t},Se=(t,e,n)=>cu(t,typeof e!="symbol"?e+"":e,n);class AO extends M1{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Se(this,"context",O4),Se(this,"storagePrefix",Ht),Se(this,"storageVersion",A4),Se(this,"events",new Map),Se(this,"shouldPersist",!1),Se(this,"init",async()=>{if(!ac())try{const i={eventId:Ad(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:xd(this.core.relayer.protocol,this.core.relayer.version,Xc)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Se(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=Ad(),l=this.core.projectId||"",f=Date.now(),h=Ji({eventId:u,timestamp:f,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,h),this.shouldPersist=!0),h}),Se(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Ji(Ji({},a),this.setMethods(a.eventId))}),Se(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Se(this,"setEventListeners",()=>{this.core.heartbeat.on(Hn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>$4&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Se(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Se(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),Se(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Se(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Ji(Ji({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Se(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),Se(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${B4}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Xc}${s}`,{method:"POST",body:JSON.stringify(i)})}),Se(this,"getAppDomain",()=>_d().url),this.logger=We(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var OO=Object.defineProperty,p0=Object.getOwnPropertySymbols,$O=Object.prototype.hasOwnProperty,BO=Object.prototype.propertyIsEnumerable,uu=(t,e,n)=>e in t?OO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,g0=(t,e)=>{for(var n in e||(e={}))$O.call(e,n)&&uu(t,n,e[n]);if(p0)for(var n of p0(e))BO.call(e,n)&&uu(t,n,e[n]);return t},ue=(t,e,n)=>uu(t,typeof e!="symbol"?e+"":e,n);class lu extends A1{constructor(e){var n;super(e),ue(this,"protocol",Bg),ue(this,"version",Tg),ue(this,"name",bo),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"customStoragePrefix"),ue(this,"events",new He.exports.EventEmitter),ue(this,"logger"),ue(this,"heartbeat"),ue(this,"relayer"),ue(this,"crypto"),ue(this,"storage"),ue(this,"history"),ue(this,"expirer"),ue(this,"pairing"),ue(this,"verify"),ue(this,"echoClient"),ue(this,"linkModeSupportedApps"),ue(this,"eventClient"),ue(this,"initialized",!1),ue(this,"logChunkController"),ue(this,"on",(a,c)=>this.events.on(a,c)),ue(this,"once",(a,c)=>this.events.once(a,c)),ue(this,"off",(a,c)=>this.events.off(a,c)),ue(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ue(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:le.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Cg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Lo({level:typeof e?.logger=="string"&&e.logger?e.logger:X6.logger,name:bo}),{logger:s,chunkLoggerController:o}=I1({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=We(s,this.name),this.heartbeat=new Po,this.crypto=new iA(this,this.logger,e?.keychain),this.history=new pO(this,this.logger),this.expirer=new wO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Yy(g0(g0({},J6),e?.storageOptions)),this.relayer=new TA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new hO(this,this.logger),this.verify=new vO(this,this.logger,this.storage),this.echoClient=new xO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new AO(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new lu(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(f4,r),n}get context(){return et(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(Ng,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(Ng)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const TO=lu,y0="wc",w0=2,b0="client",hu=`${y0}@${w0}:${b0}:`,fu={name:b0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},m0="WALLETCONNECT_DEEPLINK_CHOICE",PO="proposal",v0="Proposal expired",RO="session",Yr=M.SEVEN_DAYS,CO="engine",Re={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},du={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Zt={idle:"IDLE",active:"ACTIVE"},NO={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:""}},UO="request",FO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],kO="wc",LO="auth",MO="authKeys",jO="pairingTopics",qO="requests",Eo=`${kO}@${1.5}:${LO}:`,_o=`${Eo}:PUB_KEY`;var zO=Object.defineProperty,KO=Object.defineProperties,VO=Object.getOwnPropertyDescriptors,E0=Object.getOwnPropertySymbols,HO=Object.prototype.hasOwnProperty,WO=Object.prototype.propertyIsEnumerable,pu=(t,e,n)=>e in t?zO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e)=>{for(var n in e||(e={}))HO.call(e,n)&&pu(t,n,e[n]);if(E0)for(var n of E0(e))WO.call(e,n)&&pu(t,n,e[n]);return t},ze=(t,e)=>KO(t,VO(e)),F=(t,e,n)=>pu(t,typeof e!="symbol"?e+"":e,n);class GO extends K1{constructor(e){super(e),F(this,"name",CO),F(this,"events",new He.exports),F(this,"initialized",!1),F(this,"requestQueue",{state:Zt.idle,queue:[]}),F(this,"sessionRequestQueue",{state:Zt.idle,queue:[]}),F(this,"emittedSessionRequests",new ux({limit:500})),F(this,"requestQueueDelay",M.ONE_SECOND),F(this,"expectedPairingMethodMap",new Map),F(this,"recentlyDeletedMap",new Map),F(this,"recentlyDeletedLimit",200),F(this,"relayMessageCache",[]),F(this,"pendingSessions",new Map),F(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Re)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),F(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=ze(se({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=wS(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=r;let l=i,f,h=!1;try{if(l){const C=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),h=C.active}}catch(C){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),C}if(!l||!h){const{topic:C,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=C,f=U}if(!l){const{message:C}=j("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(C)}const d=await this.client.core.crypto.generateKeyPair(),p=Re.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=ve(p),y=ze(se(se({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:Rg}],proposer:{publicKey:d,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:yt()}),I=ie("session_connect",y.id),{reject:D,resolve:E,done:$}=or(p,v0),R=({id:C})=>{C===y.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(y.id),this.events.emit(I,{error:{message:v0,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(I,({error:C,session:U})=>{this.client.events.off("proposal_expire",R),C?D(C):U&&E(U)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:f,approval:$}}),F(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),F(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[qn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(O){throw o.setError(Hi.no_internet_connection),O}try{await this.isValidProposalId(n?.id)}catch(O){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Hi.proposal_not_found),O}try{await this.isValidApprove(n)}catch(O){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Hi.session_approve_namespace_validation_failure),O}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=n,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:p,proposer:g,requiredNamespaces:y,optionalNamespaces:I}=d;let D=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:p});D||(D=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:qn.session_approve_started,properties:{topic:p,trace:[qn.session_approve_started,qn.session_namespaces_validation_success]}}));const E=await this.client.core.crypto.generateKeyPair(),$=g.publicKey,R=await this.client.core.crypto.generateSharedKey(E,$),C=se(se(se({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:E,metadata:this.client.metadata},expiry:ve(Yr)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),U=le.relay;D.addTrace(qn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(R,{transportType:U,internal:{skipSubscribe:!0}})}catch(O){throw D.setError(Hi.subscribe_session_topic_failure),O}D.addTrace(qn.subscribe_session_topic_success);const N=ze(se({},C),{topic:R,requiredNamespaces:y,optionalNamespaces:I,pairingTopic:p,acknowledged:!1,self:C.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:E,transportType:le.relay});await this.client.session.set(R,N),D.addTrace(qn.store_session);try{await this.sendApproveSession({sessionTopic:R,proposal:d,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:E},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),D.addTrace(qn.session_approve_publish_success)}catch(O){throw this.client.logger.error(O),this.client.session.delete(R,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(R),O}return this.client.core.eventClient.deleteEvent({eventId:D.eventId}),await this.client.core.pairing.updateMetadata({topic:p,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:p}),await this.setExpiry(R,ve(Yr)),{topic:R,acknowledged:()=>Promise.resolve(this.client.session.get(R))}}),F(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Re.wc_sessionPropose.reject}),await this.deleteProposal(r)}),F(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(f){throw this.client.logger.error("update() -> isValidUpdate() failed"),f}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=or(),c=yt(),u=jn().toString(),l=this.client.session.get(r).namespaces;return this.events.once(ie("session_update",c),({error:f})=>{f?a(f):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(f=>{this.client.logger.error(f),this.client.session.update(r,{namespaces:l}),a(f)}),{acknowledged:s}}),F(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=yt(),{done:s,resolve:o,reject:a}=or();return this.events.once(ie("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,ve(Yr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),F(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Re.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const c=yt(),u=jn().toString(),{done:l,resolve:f,reject:h}=or(o,"Request expired. Please try again.");this.events.once(ie("session_request",c),({error:y,result:I})=>{y?h(y):f(I)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:{request:ze(se({},i),{expiryTimestamp:ve(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(y=>h(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:ze(se({},i),{expiryTimestamp:ve(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(I=>h(I)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const D=await ix(this.client.core.storage,m0);await tx({id:c,topic:s,wcDeepLink:D})}y()}),l()]).then(y=>y[2])}),F(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:s}=i,o=this.client.session.get(r);o.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Vt(i)?await this.sendResult({id:s,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):Dt(i)&&await this.sendError({id:s,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(n)}),F(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=yt(),s=jn().toString(),{done:o,resolve:a,reject:c}=or();this.events.once(ie("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),F(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=jn().toString(),a=yt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),F(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=j("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),F(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>vS(r,n)))),F(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),F(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?le.link_mode:le.relay;o===le.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:h,exp:d,nbf:p,methods:g=[],expiry:y}=n,I=[...n.resources||[]],{topic:D,uri:E}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:D,uri:E}});const $=await this.client.core.crypto.generateKeyPair(),R=fo($);if(await Promise.all([this.client.auth.authKeys.set(_o,{responseTopic:R,publicKey:$}),this.client.auth.pairingTopics.set(R,{topic:R,pairingTopic:D})]),await this.client.core.relayer.subscribe(R,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${D}`),g.length>0){const{namespace:_}=ir(a[0]);let S=m8(_,"request",g);eo(I)&&(S=E8(S,I.pop())),I.push(S)}const C=y&&y>Re.wc_sessionAuthenticate.req.ttl?y:Re.wc_sessionAuthenticate.req.ttl,U={authPayload:{type:h??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:d,nbf:p,resources:I},requester:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:ve(C)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},O={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:D,proposer:{publicKey:$,metadata:this.client.metadata},expiryTimestamp:ve(Re.wc_sessionPropose.req.ttl),id:yt()},{done:G,resolve:W,reject:P}=or(C,"Request expired"),v=yt(),m=ie("session_connect",O.id),w=ie("session_request",v),b=async({error:_,session:S})=>{this.events.off(w,x),_?P(_):S&&W({session:S})},x=async _=>{var S,B,T;if(await this.deletePendingAuthRequest(v,{message:"fulfilled",code:0}),_.error){const V=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return _.error.code===V.code?void 0:(this.events.off(m,b),P(_.error.message))}await this.deleteProposal(O.id),this.events.off(m,b);const{cacaos:q,responder:L}=_.result,k=[],z=[];for(const V of q){await Jd({cacao:V,projectId:this.client.core.projectId})||(this.client.logger.error(V,"Signature verification failed"),P(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Y}=V,he=eo(Y.resources),Ke=[yc(Y.iss)],mt=Qs(Y.iss);if(he){const gn=tp(he),wu=np(he);k.push(...gn),Ke.push(...wu)}for(const gn of Ke)z.push(`${gn}:${mt}`)}const H=await this.client.core.crypto.generateSharedKey($,L.publicKey);let Z;k.length>0&&(Z={topic:H,acknowledged:!0,self:{publicKey:$,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:ve(Yr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:D,namespaces:ug([...new Set(k)],[...new Set(z)]),transportType:o},await this.client.core.relayer.subscribe(H,{transportType:o}),await this.client.session.set(H,Z),D&&await this.client.core.pairing.updateMetadata({topic:D,metadata:L.metadata}),Z=this.client.session.get(H)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(B=L.metadata.redirect)!=null&&B.linkMode&&(T=L.metadata.redirect)!=null&&T.universal&&r&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(H,{transportType:le.link_mode})),W({auths:q,session:Z})};this.events.once(m,b),this.events.once(w,x);let A;try{if(s){const _=dn("wc_sessionAuthenticate",U,v);this.client.core.history.set(D,_);const S=await this.client.core.crypto.encode("",_,{type:Ui,encoding:Mn});A=go(r,D,S)}else await Promise.all([this.sendRequest({topic:D,method:"wc_sessionAuthenticate",params:U,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:v}),this.sendRequest({topic:D,method:"wc_sessionPropose",params:O,expiry:Re.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:O.id})])}catch(_){throw this.events.off(m,b),this.events.off(w,x),_}return await this.setProposal(O.id,O),await this.setAuthRequest(v,{request:ze(se({},U),{verifyContext:{}}),pairingTopic:D,transportType:o}),{uri:A??E,response:G}}),F(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[gr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Wi.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Wi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||le.relay;a===le.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=fo(c),f={type:ln,receiverPublicKey:c,senderPublicKey:u},h=[],d=[];for(const y of i){if(!await Jd({cacao:y,projectId:this.client.core.projectId})){s.setError(Wi.invalid_cacao);const R=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:R,encodeOpts:f}),new Error(R.message)}s.addTrace(gr.cacaos_verified);const{p:I}=y,D=eo(I.resources),E=[yc(I.iss)],$=Qs(I.iss);if(D){const R=tp(D),C=np(D);h.push(...R),E.push(...C)}for(const R of E)d.push(`${R}:${$}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(gr.create_authenticated_session_topic);let g;if(h?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:ve(Yr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:ug([...new Set(h)],[...new Set(d)]),transportType:a},s.addTrace(gr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(y){throw s.setError(Wi.subscribe_authenticated_session_topic_failure),y}s.addTrace(gr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(gr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(gr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:f,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Wi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),F(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===le.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=fo(o),u={type:ln,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Re.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),F(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return Qd(r,i)}),F(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),F(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),F(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(m0).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Zt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),F(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n),s=this.client.core.eventClient.getEvent({topic:i.pairingTopic});s?.setError(Hi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),F(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=Zt.idle,this.client.events.emit("session_request_expire",{id:n}))}),F(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),F(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),F(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,ve(Re.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),F(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=le.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),F(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||ve(Re.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),F(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:h={}}=n,d=dn(i,s,c);let p;const g=!!l;try{const D=g?Mn:ot;p=await this.client.core.crypto.encode(r,d,{encoding:D})}catch(D){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),D}let y;if(FO.includes(i)){const D=St(JSON.stringify(d)),E=St(p);y=await this.client.core.verify.register({id:E,decryptedId:D})}const I=se(se({},Re[i].req),h);if(I.attestation=y,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(r,d),g){const D=go(l,r,p);await global.Linking.openURL(D,this.client.name)}else I.tvf=ze(se({},f),{correlationId:d.id}),u?(I.internal=ze(se({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,I)):this.client.core.relayer.publish(r,p,I).catch(D=>this.client.logger.error(D));return d.id}),F(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=dn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:ot}),a=St(JSON.stringify(s)),c=St(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:ze(se({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),F(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=yo(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:ot}),l=dn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:ot});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:ze(se({},a),{publishMethod:"wc_approveSession"})})}),F(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=yo(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Mn:ot;l=await this.client.core.crypto.encode(i,u,ze(se({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let h,d;try{h=await this.client.core.history.get(i,r);const p=h.request;try{d=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),p}if(f){const p=go(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=h.request.method,g=Re[p].res;g.tvf=ze(se({},d),{correlationId:r}),o?(g.internal=ze(se({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),F(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Zc(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=f?Mn:ot;l=await this.client.core.crypto.encode(i,u,ze(se({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),d}let h;try{h=await this.client.core.history.get(i,r)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),d}if(f){const d=go(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=h.request.method,p=a||Re[d].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),F(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;Dn(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{Dn(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),F(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),F(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),F(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Zt.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=Zt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Zt.idle}),F(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),F(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),F(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=j("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),F(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),F(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(pn.proposal_listener_not_found)),this.isValidConnect(se({},i.params));const l=a.expiryTimestamp||ve(Re.wc_sessionPropose.req.ttl),f=se({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const h=await this.getVerifyContext({attestationId:s,hash:St(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(Wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:h})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Re.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),F(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(Vt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const f=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:f}),await this.client.core.pairing.activate({topic:n})}else if(Dt(r)){await this.deleteProposal(s);const o=ie("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),F(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:h}=r.params,d=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!d)return this.client.logger.error(`Pending session not found for topic ${n}`);const p=this.client.proposal.get(d.proposalId),g=ze(se(se(se({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:p.requiredNamespaces,optionalNamespaces:p.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),h&&{sessionConfig:h}),{transportType:le.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ie("session_connect",d.proposalId),{session:g}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;Vt(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(ie("session_approve",i),{})):Dt(r)&&(await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.events.emit(ie("session_approve",i),{error:r.error}))}),F(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(se({topic:n},i));try{ji.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw ji.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),F(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=ie("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Vt(r)?this.events.emit(ie("session_update",i),{}):Dt(r)&&this.events.emit(ie("session_update",i),{error:r.error})}),F(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,ve(Yr)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),F(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=ie("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Vt(r)?this.events.emit(ie("session_extend",i),{}):Dt(r)&&this.events.emit(ie("session_extend",i),{error:r.error})}),F(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),F(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=ie("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Vt(r)?this.events.emit(ie("session_ping",i),{}):Dt(r)&&this.events.emit(ie("session_ping",i),{error:r.error})},500)}),F(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(pe.publish,async()=>{s(await this.deleteSession({topic:n,id:i}))})}),this.sendResult({id:i,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),F(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:h}=a;try{await this.isValidRequest(se({topic:o},h));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:St(JSON.stringify(dn("wc_sessionRequest",h,f))),encryptedId:u,metadata:d.peer.metadata,transportType:l}),g={id:f,topic:o,params:h,verifyContext:p};await this.setPendingSessionRequest(g),l===le.link_mode&&(r=d.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=d.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:f,topic:o,error:d}),this.client.logger.error(d)}}),F(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=ie("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Vt(r)?this.events.emit(ie("session_request",i),{result:r.result}):Dt(r)&&this.events.emit(ie("session_request",i),{error:r.error})}),F(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=ji.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(se({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),ji.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),F(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),Vt(r)?this.events.emit(ie("session_request",i),{result:r.result}):Dt(r)&&this.events.emit(ie("session_request",i),{error:r.error})}),F(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:f}=s.params,h=await this.getVerifyContext({attestationId:o,hash:St(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),d={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:h,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:d,pairingTopic:i,transportType:c}),c===le.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:h})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),h=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:ln,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:d,rpcOpts:Re.wc_sessionAuthenticate.autoReject,appLink:h})}}),F(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),F(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Zt.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),F(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=ie("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(ie("session_request",s.request.id),{error:r})})}),F(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Zt.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),F(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=Zt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),F(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:dn("wc_sessionPropose",ze(se({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),F(this,"isValidConnect",async n=>{if(!at(n)){const{message:u}=j("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(_e(r)||await this.isValidPairingTopic(r),!PS(c,!0)){const{message:u}=j("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!_e(i)&&Li(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!_e(s)&&Li(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),F(this,"validateNamespaces",(n,r)=>{const i=TS(n,"connect()",r);if(i)throw new Error(i.message)}),F(this,"isValidApprove",async n=>{if(!at(n))throw new Error(j("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=qc(i,"approve()");if(u)throw new Error(u.message);const l=pg(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!ge(s,!0)){const{message:f}=j("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(h=>f.has(h.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),F(this,"isValidReject",async n=>{if(!at(n)){const{message:s}=j("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!CS(i)){const{message:s}=j("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),F(this,"isValidSessionSettleRequest",n=>{if(!at(n)){const{message:u}=j("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!fg(r)){const{message:u}=j("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=SS(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=qc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(Dn(o)){const{message:u}=j("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),F(this,"isValidUpdate",async n=>{if(!at(n)){const{message:c}=j("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=qc(i,"update()");if(o)throw new Error(o.message);const a=pg(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),F(this,"isValidExtend",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),F(this,"isValidRequest",async n=>{if(!at(n)){const{message:c}=j("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!dg(a,s)){const{message:c}=j("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!NS(i)){const{message:c}=j("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!kS(a,s,i.method)){const{message:c}=j("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!qS(o,du)){const{message:c}=j("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${du.min} and ${du.max}`);throw new Error(c)}}),F(this,"isValidRespond",async n=>{var r;if(!at(n)){const{message:o}=j("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!US(s)){const{message:o}=j("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),F(this,"isValidPing",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidEmit",async n=>{if(!at(n)){const{message:a}=j("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!dg(o,s)){const{message:a}=j("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!FS(i)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!LS(o,s,i.name)){const{message:a}=j("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),F(this,"isValidDisconnect",async n=>{if(!at(n)){const{message:i}=j("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),F(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!ge(i,!1))throw new Error("uri is required parameter");if(!ge(s,!1))throw new Error("domain is required parameter");if(!ge(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>ir(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ir(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),F(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Vi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===le.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),F(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=j("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),F(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),F(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),F(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=j("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),F(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,h;return!n||r!==le.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((f=n?.redirect)==null?void 0:f.universal)!==""&&((h=n?.redirect)==null?void 0:h.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),F(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),F(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=Dd(n,"topic")||"",i=decodeURIComponent(Dd(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:le.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),F(this,"registerLinkModeListeners",async()=>{var n;if(ac()||Sn()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),F(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),F(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),F(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=NO[s];if(s==="sui_signTransaction")return[n8(r.transactionBytes)];if(s==="near_signTransaction")return[Gd(r)];if(s==="near_signTransactions")return r.map(c=>Gd(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[r6({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Wr(r)?r.map(c=>Zd(c)):[Zd(r)];if(s==="cosmos_signDirect")return[i8(r)];if(s==="wallet_sendCalls")return s8(r);if(typeof r=="string")return[r];const a=r[o.key];if(Wr(a))return s==="solana_signAllTransactions"?a.map(c=>t8(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=j("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(pe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(_o)?this.client.auth.authKeys.get(_o):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===le.link_mode?Mn:ot});Yc(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:St(r)})):wo(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Ot.expired,async e=>{const{topic:n,id:r}=Sd(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,j("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,j("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(pr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(pr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ge(e,!1)){const{message:n}=j("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=j("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!ge(e,!1)){const{message:n}=j("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=j("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=j("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ge(e,!1)){const{message:n}=j("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=j("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!RS(e)){const{message:n}=j("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=j("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(Dn(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=j("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class ZO extends yr{constructor(e,n){super(e,n,PO,hu),this.core=e,this.logger=n}}class YO extends yr{constructor(e,n){super(e,n,RO,hu),this.core=e,this.logger=n}}class XO extends yr{constructor(e,n){super(e,n,UO,hu,r=>r.id),this.core=e,this.logger=n}}class JO extends yr{constructor(e,n){super(e,n,MO,Eo,()=>_o),this.core=e,this.logger=n}}class QO extends yr{constructor(e,n){super(e,n,jO,Eo),this.core=e,this.logger=n}}class e$ extends yr{constructor(e,n){super(e,n,qO,Eo,r=>r.id),this.core=e,this.logger=n}}var t$=Object.defineProperty,n$=(t,e,n)=>e in t?t$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gu=(t,e,n)=>n$(t,typeof e!="symbol"?e+"":e,n);class r${constructor(e,n){this.core=e,this.logger=n,gu(this,"authKeys"),gu(this,"pairingTopics"),gu(this,"requests"),this.authKeys=new JO(this.core,this.logger),this.pairingTopics=new QO(this.core,this.logger),this.requests=new e$(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var i$=Object.defineProperty,s$=(t,e,n)=>e in t?i$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ee=(t,e,n)=>s$(t,typeof e!="symbol"?e+"":e,n);class yu extends z1{constructor(e){super(e),ee(this,"protocol",y0),ee(this,"version",w0),ee(this,"name",fu.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new He.exports.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(r,i)=>this.events.on(r,i)),ee(this,"once",(r,i)=>this.events.once(r,i)),ee(this,"off",(r,i)=>this.events.off(r,i)),ee(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),ee(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),ee(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),ee(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),ee(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||fu.name,this.metadata=Z_(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:Yt(Lo({level:e?.logger||fu.logger}));this.core=e?.core||new TO(e),this.logger=We(n,this.name),this.session=new YO(this.core,this.logger),this.proposal=new ZO(this.core,this.logger),this.pendingRequest=new XO(this.core,this.logger),this.engine=new GO(this),this.auth=new r$(this.core,this.logger)}static async init(e){const n=new yu(e);return await n.initialize(),n}get context(){return et(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const o$=yu;class _0{constructor(e){this.opts=e}}class x0{constructor(e){this.client=e}}const a$=["eip155","solana"],c$={eip155:"eth_sendTransaction",solana:"solana_sendTransaction"},I0=t=>{const{network:e,symbol:n,standard:r,address:i}=t;if(!e||!n||!r||!i||!Mi(e?.chainId))return!1;const{namespace:s}=ir(e.chainId);if(!a$.includes(s))throw new Error(`Unsupported token namespace: ${s}`);return!0},u$=t=>{const{token:e,amount:n,recipient:r}=t;return!(!e||!n||!r||!I0(e))};var l$=Object.defineProperty,h$=(t,e,n)=>e in t?l$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,we=(t,e,n)=>h$(t,typeof e!="symbol"?e+"":e,n);class f$ extends x0{constructor(e){super(e),we(this,"signClient"),we(this,"tokens",[]),we(this,"paymentIntentsMap",new Map),we(this,"paymentIntentToTransactionIdMap",new Map),we(this,"init",async()=>{var n;this.signClient=await o$.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:((n=this.client.opts.storageOptions)==null?void 0:n.databaseName)||Tu.database}})}),we(this,"setTokens",async n=>{const{tokens:r}=n;r.forEach(i=>{if(!I0(i))throw new Error(`Invalid token: ${JSON.stringify(i)}`)}),await new Promise(i=>{this.tokens=r,i()})}),we(this,"createPaymentIntent",async n=>{const{paymentIntents:r}=n;if(console.log("create payment intent",r),r.length===0)throw new Error("No payment intents provided");r.forEach(c=>{if(!u$(c))throw new Error(`Invalid payment intent: ${JSON.stringify(c)}`)}),console.log("create payment intent validation success");const i=this.composeNamespaces(r);console.log("namespaces",i);const{uri:s,approval:o}=await this.signClient.connect({optionalNamespaces:i});if(!s)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001}}),new Error("Failed to connect to the WalletConnect network");const a=yt();this.paymentIntentsMap.set(a,r),this.emit("await_approval",{approval:o,intentId:a}),this.emit("qr_ready",{uri:s})}),we(this,"restart",async n=>{if(console.log("restart",n),n!=null&&n.reinit){this.tokens=[],this.paymentIntentsMap.clear(),this.paymentIntentToTransactionIdMap.clear();return}const r=Array.from(this.paymentIntentsMap.values()).flat();await this.createPaymentIntent({paymentIntents:r})}),we(this,"emit",(n,r)=>(console.log("emit",n,r),this.client.events.emit(n,r))),we(this,"on",(n,r)=>(console.log("on",n,r),this.client.events.on(n,r))),we(this,"once",(n,r)=>(console.log("once",n,r),this.client.events.once(n,r))),we(this,"off",(n,r)=>(console.log("off",n,r),this.client.events.off(n,r))),we(this,"removeListener",(n,r)=>(console.log("removeListener",n,r),this.client.events.removeListener(n,r))),we(this,"prepareTransactionsFromPaymentIntents",async n=>{console.log("prepareTransactionsFromPaymentIntents",n.intentId,n.session.topic);const{intentId:r,session:i}=n,s=this.paymentIntentsMap.get(r);if(!s)throw new Error(`Payment intents not found for id: ${r}`);const o=[];for(const a of s){const{token:c,amount:u,recipient:l}=a,{namespace:f}=ir(c.network.chainId),h=i.namespaces[f].accounts.find(g=>g.includes(`${c.network.chainId}:`));if(!h)throw new Error(`Address not found in session for chain id: ${c.network.chainId}, approved addresses: ${i.namespaces[f].accounts.join(", ")}`);const d={id:yt(),jsonrpc:"2.0",method:"reown_pos_buildTransaction",params:{asset:`${c.network.chainId}/${c.standard.toLowerCase()}:${c.address}`,recipient:l,amount:u,sender:h}},p=await this.fetchRpcRequest(JSON.stringify(d));console.log("rpcTransaction",JSON.stringify(p,null,2)),o.push(p.result.transactionRpc),this.paymentIntentToTransactionIdMap.set(r,p.result.id)}return o}),we(this,"onSessionConnected",async n=>{const{intentId:r,session:i}=n;console.log("onSessionConnected",r,i.topic),this.emit("connected",{});const s=await this.prepareTransactionsFromPaymentIntents({intentId:r,session:i});console.log("transactions",JSON.stringify(s,null,2)),this.sendTransactionsToWallet({transactions:s,session:i,intentId:r})}),we(this,"sendTransactionsToWallet",async n=>{const{transactions:r,session:i,intentId:s}=n;console.log("sendTransactionsToWallet",r,i.topic);const o=this.paymentIntentsMap.get(s);if(!o)throw new Error(`Payment intents not found for id: ${s}`);const{token:a}=o[0];try{this.emit("payment_requested",{});let c;try{c=await this.signClient.request({topic:i.topic,request:r[0],chainId:a.network.chainId})}catch(u){throw console.error("error",u),this.emit("payment_rejected",{error:{message:u?.message,code:4001}}),u}this.emit("payment_broadcasted",c),await this.awaitPaymentConfirmed({intentId:s,result:c})}catch(c){console.error("error",c)}}),we(this,"awaitPaymentConfirmed",async n=>{const{intentId:r,result:i}=n;if(!this.paymentIntentsMap.get(r))throw new Error(`Payment intents not found for id: ${r}`);const s=this.paymentIntentToTransactionIdMap.get(r);if(!s)throw new Error(`Transaction id not found for intent id: ${r}`);const o={id:yt(),jsonrpc:"2.0",method:"reown_pos_checkTransaction",params:{id:s,sendResult:i}};let a;for(;!a;){const c=await this.fetchRpcRequest(JSON.stringify(o));if(c.result.status==="CONFIRMED"){console.log("payment_successful",c.result),this.emit("payment_successful",{}),a=c.result;break}else if(c.result.status==="FAILED"){console.log("payment_failed",c.result),this.emit("payment_failed",{error:{message:c.result.error,code:4001}}),a=c.result;break}else c.result.status==="PENDING"&&(console.log("payment_pending",c.result),await new Promise(u=>setTimeout(u,c.result.checkIn||1e3)))}console.log("awaitPaymentConfirmed",r,s)}),we(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:n,intentId:r})=>{try{console.log("await_approval",r);const i=await n();this.onSessionConnected({intentId:r,session:i})}catch(i){console.error("error",i),this.emit("connection_rejected",{error:{message:i?.message,code:4001}})}})}),we(this,"fetchRpcRequest",async n=>{var r,i;const s=await fetch(this.getRpcUrl(),{method:"POST",body:n}),o=await s.json();if(!s.ok||o.error)throw this.emit("payment_failed",{error:{message:(r=o.error)==null?void 0:r.message,code:4001}}),new Error(`Failed to fetch RPC request: ${(i=o.error)==null?void 0:i.message}`);return o}),we(this,"getRpcUrl",()=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${this.client.opts.projectId}&st=node&sv=js-pos-${Pu}`),this.signClient={},this.setupEventHandlers()}composeNamespaces(e){const n={};return e.forEach(r=>{const{token:{network:i}}=r,{namespace:s}=ir(i.chainId);n[s]={methods:[c$[s]],chains:[i.chainId],events:[]}}),n}}var d$=Object.defineProperty,p$=(t,e,n)=>e in t?d$(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ft=(t,e,n)=>p$(t,typeof e!="symbol"?e+"":e,n);class xo extends _0{constructor(e){super(e),Ft(this,"name"),Ft(this,"events",new He.exports),Ft(this,"engine"),Ft(this,"metadata"),Ft(this,"on",(n,r)=>this.engine.on(n,r)),Ft(this,"once",(n,r)=>this.engine.once(n,r)),Ft(this,"off",(n,r)=>this.engine.off(n,r)),Ft(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),Ft(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ft(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ft(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=Io,this.engine=new f$(this)}static async init(e){const n=new xo(e);return await n.initialize(),n}async initialize(){try{await this.engine.init(),this.engine.signClient.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.signClient.logger.info("POSClient Initialization Failure"),this.engine.signClient.logger.error(e.message),e}}}const g$=xo;Ve.CLIENT_CONTEXT=Io,Ve.CLIENT_STORAGE_OPTIONS=Tu,Ve.CLIENT_STORAGE_PREFIX=L0,Ve.IPOSClient=_0,Ve.IPOSClientEngine=x0,Ve.POSClient=g$,Ve.POS_CLIENT_VERSION=Pu,Ve.PROTOCOL=Bu,Ve.PROTOCOL_VERSION=k0,Ve.default=xo,Object.defineProperty(Ve,"__esModule",{value:!0})});
42
+ //# sourceMappingURL=index.umd.js.map