@walletconnect/pos-client 0.0.0-canary.0 → 0.0.0-canary.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -0
- package/dist/index.umd.js +15 -15
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/types/constants/chains.d.ts +2 -5
- package/dist/types/constants/chains.d.ts.map +1 -1
- package/dist/types/constants/client.d.ts +1 -0
- package/dist/types/constants/client.d.ts.map +1 -1
- package/dist/types/constants/index.d.ts +3 -0
- package/dist/types/constants/index.d.ts.map +1 -1
- package/dist/types/constants/rpc.d.ts +19 -0
- package/dist/types/constants/rpc.d.ts.map +1 -0
- package/dist/types/controllers/engine.d.ts +3 -1
- package/dist/types/controllers/engine.d.ts.map +1 -1
- package/dist/types/types/client.d.ts +36 -7
- package/dist/types/types/client.d.ts.map +1 -1
- package/dist/types/types/engine.d.ts +27 -3
- package/dist/types/types/engine.d.ts.map +1 -1
- package/dist/types/types/index.d.ts +1 -0
- package/dist/types/types/index.d.ts.map +1 -1
- package/dist/types/types/utils.d.ts +20 -0
- package/dist/types/types/utils.d.ts.map +1 -0
- package/dist/types/utils/validator.d.ts +3 -3
- package/dist/types/utils/validator.d.ts.map +1 -1
- package/package.json +11 -3
- package/dist/index.cjs.js +0 -2
- package/dist/index.cjs.js.map +0 -1
- package/dist/index.es.js +0 -2
- package/dist/index.es.js.map +0 -1
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(be,Ft){typeof exports=="object"&&typeof module<"u"?Ft(exports):typeof define=="function"&&define.amd?define(["exports"],Ft):(be=typeof globalThis<"u"?globalThis:be||self,Ft(be["@walletconnect/pos-client"]={}))})(this,function(be){"use strict";var Ft=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function fu(t){var e=t.default;if(typeof e=="function"){var n=function(){return e.apply(this,arguments)};n.prototype=e.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(t).forEach(function(r){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(n,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}),n}var Ve={exports:{}},dr=typeof Reflect=="object"?Reflect:null,du=dr&&typeof dr.apply=="function"?dr.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},Zi;dr&&typeof dr.ownKeys=="function"?Zi=dr.ownKeys:Object.getOwnPropertySymbols?Zi=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Zi=function(e){return Object.getOwnPropertyNames(e)};function c0(t){console&&console.warn&&console.warn(t)}var pu=Number.isNaN||function(e){return e!==e};function se(){se.init.call(this)}Ve.exports=se,Ve.exports.once=f0,se.EventEmitter=se,se.prototype._events=void 0,se.prototype._eventsCount=0,se.prototype._maxListeners=void 0;var gu=10;function Ji(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(se,"defaultMaxListeners",{enumerable:!0,get:function(){return gu},set:function(t){if(typeof t!="number"||t<0||pu(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");gu=t}}),se.init=function(){(this._events===void 0||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},se.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||pu(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function yu(t){return t._maxListeners===void 0?se.defaultMaxListeners:t._maxListeners}se.prototype.getMaxListeners=function(){return yu(this)},se.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e==="error",s=this._events;if(s!==void 0)i=i&&s.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(c===void 0)return!1;if(typeof c=="function")du(c,this,n);else for(var u=c.length,l=Eu(c,u),r=0;r<u;++r)du(l[r],this,n);return!0};function wu(t,e,n,r){var i,s,o;if(Ji(n),s=t._events,s===void 0?(s=t._events=Object.create(null),t._eventsCount=0):(s.newListener!==void 0&&(t.emit("newListener",e,n.listener?n.listener:n),s=t._events),o=s[e]),o===void 0)o=s[e]=n,++t._eventsCount;else if(typeof o=="function"?o=s[e]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),i=yu(t),i>0&&o.length>i&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=t,a.type=e,a.count=o.length,c0(a)}return t}se.prototype.addListener=function(e,n){return wu(this,e,n,!1)},se.prototype.on=se.prototype.addListener,se.prototype.prependListener=function(e,n){return wu(this,e,n,!0)};function u0(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function mu(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=u0.bind(r);return i.listener=n,r.wrapFn=i,i}se.prototype.once=function(e,n){return Ji(n),this.on(e,mu(this,e,n)),this},se.prototype.prependOnceListener=function(e,n){return Ji(n),this.prependListener(e,mu(this,e,n)),this},se.prototype.removeListener=function(e,n){var r,i,s,o,a;if(Ji(n),i=this._events,i===void 0)return this;if(r=i[e],r===void 0)return this;if(r===n||r.listener===n)--this._eventsCount===0?this._events=Object.create(null):(delete i[e],i.removeListener&&this.emit("removeListener",e,r.listener||n));else if(typeof r!="function"){for(s=-1,o=r.length-1;o>=0;o--)if(r[o]===n||r[o].listener===n){a=r[o].listener,s=o;break}if(s<0)return this;s===0?r.shift():l0(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},se.prototype.off=se.prototype.removeListener,se.prototype.removeAllListeners=function(e){var n,r,i;if(r=this._events,r===void 0)return this;if(r.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):r[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete r[e]),this;if(arguments.length===0){var s=Object.keys(r),o;for(i=0;i<s.length;++i)o=s[i],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(n=r[e],typeof n=="function")this.removeListener(e,n);else if(n!==void 0)for(i=n.length-1;i>=0;i--)this.removeListener(e,n[i]);return this};function bu(t,e,n){var r=t._events;if(r===void 0)return[];var i=r[e];return i===void 0?[]:typeof i=="function"?n?[i.listener||i]:[i]:n?h0(i):Eu(i,i.length)}se.prototype.listeners=function(e){return bu(this,e,!0)},se.prototype.rawListeners=function(e){return bu(this,e,!1)},se.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):vu.call(t,e)},se.prototype.listenerCount=vu;function vu(t){var e=this._events;if(e!==void 0){var n=e[t];if(typeof n=="function")return 1;if(n!==void 0)return n.length}return 0}se.prototype.eventNames=function(){return this._eventsCount>0?Zi(this._events):[]};function Eu(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function l0(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function h0(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function f0(t,e){return new Promise(function(n,r){function i(o){t.removeListener(e,s),r(o)}function s(){typeof t.removeListener=="function"&&t.removeListener("error",i),n([].slice.call(arguments))}xu(t,e,s,{once:!0}),e!=="error"&&d0(t,i,{once:!0})})}function d0(t,e,n){typeof t.on=="function"&&xu(t,"error",e,n)}function xu(t,e,n,r){if(typeof t.on=="function")r.once?t.once(e,n):t.on(e,n);else if(typeof t.addEventListener=="function")t.addEventListener(e,function i(s){r.once&&t.removeEventListener(e,i),n(s)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof t)}const _u="wc",p0=2,yo="POSClient",g0=`${_u}@2:${yo}:`,Iu={database:":memory:"},Su="1.0.0",Au=10,Du=[{assetNamespaces:["erc20","slip44"],capabilities:null,events:[],methods:["eth_sendTransaction"],name:"eip155"},{assetNamespaces:["token","slip44"],capabilities:null,events:[],methods:["solana_signAndSendTransaction"],name:"solana"},{assetNamespaces:["trc20","slip44"],capabilities:null,events:[],methods:["tron_signTransaction"],name:"tron"}],Ou=({projectId:t})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${t}&st=node&sv=js-pos-${Su}`,wo={"-18901":"ValidationError.InvalidAsset","-18902":"ValidationError.InvalidRecipient","-18903":"ValidationError.InvalidSender","-18904":"ValidationError.InvalidAmount","-18905":"ValidationError.InvalidAddress","-18906":"ValidationError.InvalidWalletResponse","-18907":"ValidationError.InvalidTransactionId","-18920":"ExecutionError.GasEstimation","-18940":"InternalError.InvalidProviderUrl","-18941":"InternalError.RpcError","-18942":"InternalError.Internal","-18970":"TransactionIdError.InvalidFormat","-18971":"TransactionIdError.InvalidChainId"};var M={};/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -11,21 +11,21 @@
|
|
|
11
11
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
12
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
13
|
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
-
***************************************************************************** */var So=function(t,e){return So=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},So(t,e)};function 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@${
|
|
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+=
|
|
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(
|
|
21
|
-
- ${g}`).join("")}`:void 0,
|
|
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.
|
|
14
|
+
***************************************************************************** */var mo=function(t,e){return mo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},mo(t,e)};function y0(t,e){mo(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var bo=function(){return bo=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},bo.apply(this,arguments)};function w0(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function m0(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function b0(t,e){return function(n,r){e(n,r,t)}}function v0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function E0(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function x0(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function _0(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function I0(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function vo(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function $u(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function S0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat($u(arguments[e]));return t}function A0(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Mr(t){return this instanceof Mr?(this.v=t,this):new Mr(t)}function D0(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){r[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Mr?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function O0(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Mr(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function $0(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof vo=="function"?vo(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function T0(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function B0(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function P0(t){return t&&t.__esModule?t:{default:t}}function C0(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function R0(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var N0=Object.freeze({__proto__:null,__extends:y0,get __assign(){return bo},__rest:w0,__decorate:m0,__param:b0,__metadata:v0,__awaiter:E0,__generator:x0,__createBinding:_0,__exportStar:I0,__values:vo,__read:$u,__spread:S0,__spreadArrays:A0,__await:Mr,__asyncGenerator:D0,__asyncDelegator:O0,__asyncValues:$0,__makeTemplateObject:T0,__importStar:B0,__importDefault:P0,__classPrivateFieldGet:C0,__classPrivateFieldSet:R0}),Xi=fu(N0),Eo={},zr={},Tu;function U0(){if(Tu)return zr;Tu=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return zr.delay=t,zr}var zn={},xo={},qn={},Bu;function F0(){return Bu||(Bu=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.ONE_THOUSAND=qn.ONE_HUNDRED=void 0,qn.ONE_HUNDRED=100,qn.ONE_THOUSAND=1e3),qn}var _o={},Pu;function k0(){return Pu||(Pu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.ONE_YEAR=t.FOUR_WEEKS=t.THREE_WEEKS=t.TWO_WEEKS=t.ONE_WEEK=t.THIRTY_DAYS=t.SEVEN_DAYS=t.FIVE_DAYS=t.THREE_DAYS=t.ONE_DAY=t.TWENTY_FOUR_HOURS=t.TWELVE_HOURS=t.SIX_HOURS=t.THREE_HOURS=t.ONE_HOUR=t.SIXTY_MINUTES=t.THIRTY_MINUTES=t.TEN_MINUTES=t.FIVE_MINUTES=t.ONE_MINUTE=t.SIXTY_SECONDS=t.THIRTY_SECONDS=t.TEN_SECONDS=t.FIVE_SECONDS=t.ONE_SECOND=void 0,t.ONE_SECOND=1,t.FIVE_SECONDS=5,t.TEN_SECONDS=10,t.THIRTY_SECONDS=30,t.SIXTY_SECONDS=60,t.ONE_MINUTE=t.SIXTY_SECONDS,t.FIVE_MINUTES=t.ONE_MINUTE*5,t.TEN_MINUTES=t.ONE_MINUTE*10,t.THIRTY_MINUTES=t.ONE_MINUTE*30,t.SIXTY_MINUTES=t.ONE_MINUTE*60,t.ONE_HOUR=t.SIXTY_MINUTES,t.THREE_HOURS=t.ONE_HOUR*3,t.SIX_HOURS=t.ONE_HOUR*6,t.TWELVE_HOURS=t.ONE_HOUR*12,t.TWENTY_FOUR_HOURS=t.ONE_HOUR*24,t.ONE_DAY=t.TWENTY_FOUR_HOURS,t.THREE_DAYS=t.ONE_DAY*3,t.FIVE_DAYS=t.ONE_DAY*5,t.SEVEN_DAYS=t.ONE_DAY*7,t.THIRTY_DAYS=t.ONE_DAY*30,t.ONE_WEEK=t.SEVEN_DAYS,t.TWO_WEEKS=t.ONE_WEEK*2,t.THREE_WEEKS=t.ONE_WEEK*3,t.FOUR_WEEKS=t.ONE_WEEK*4,t.ONE_YEAR=t.ONE_DAY*365}(_o)),_o}var Cu;function Ru(){return Cu||(Cu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(F0(),t),e.__exportStar(k0(),t)}(xo)),xo}var Nu;function L0(){if(Nu)return zn;Nu=1,Object.defineProperty(zn,"__esModule",{value:!0}),zn.fromMiliseconds=zn.toMiliseconds=void 0;const t=Ru();function e(r){return r*t.ONE_THOUSAND}zn.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return zn.fromMiliseconds=n,zn}var Uu;function M0(){return Uu||(Uu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(U0(),t),e.__exportStar(L0(),t)}(Eo)),Eo}var pr={},Fu;function z0(){if(Fu)return pr;Fu=1,Object.defineProperty(pr,"__esModule",{value:!0}),pr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(n){if(this.timestamps.has(n))throw new Error(`Watch already started for label: ${n}`);this.timestamps.set(n,{started:Date.now()})}stop(n){const r=this.get(n);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${n}`);const i=Date.now()-r.started;this.timestamps.set(n,{started:r.started,elapsed:i})}get(n){const r=this.timestamps.get(n);if(typeof r>"u")throw new Error(`No timestamp found for label: ${n}`);return r}elapsed(n){const r=this.get(n);return r.elapsed||Date.now()-r.started}}return pr.Watch=t,pr.default=t,pr}var Io={},qr={},ku;function q0(){if(ku)return qr;ku=1,Object.defineProperty(qr,"__esModule",{value:!0}),qr.IWatch=void 0;class t{}return qr.IWatch=t,qr}var Lu;function j0(){return Lu||(Lu=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Xi.__exportStar(q0(),t)}(Io)),Io}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Xi;e.__exportStar(M0(),t),e.__exportStar(z0(),t),e.__exportStar(j0(),t),e.__exportStar(Ru(),t)})(M);class jn{}class V0 extends jn{constructor(e){super()}}const Mu=M.FIVE_SECONDS,Vn={pulse:"heartbeat_pulse"};class So extends V0{constructor(e){super(e),this.events=new Ve.exports.EventEmitter,this.interval=Mu,this.interval=e?.interval||Mu}static async init(e){const n=new So(e);return await n.init(),n}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),M.toMiliseconds(this.interval))}pulse(){this.events.emit(Vn.pulse)}}const K0=/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,H0=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,W0=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function G0(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Y0(t);return}return e}function Y0(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Qi(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const n=t.trim();if(n.length<=9)switch(n.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!W0.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(K0.test(t)||H0.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,G0)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Z0(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ie(t,...e){try{return Z0(t(...e))}catch(n){return Promise.reject(n)}}function J0(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function X0(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function es(t){if(J0(t))return String(t);if(X0(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return es(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ao="base64:";function Q0(t){return typeof t=="string"?t:Ao+ny(t)}function ey(t){return typeof t!="string"||!t.startsWith(Ao)?t:ty(t.slice(Ao.length))}function ty(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function ny(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Ze(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function ry(...t){return Ze(t.join(":"))}function ts(t){return t=Ze(t),t?t+":":""}function iy(t,e){if(e===void 0)return!0;let n=0,r=t.indexOf(":");for(;r>-1;)n++,r=t.indexOf(":",r+1);return n<=e}function sy(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function C5(t){return t}const oy="memory",ay=()=>{const t=new Map;return{name:oy,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,n){t.set(e,n)},setItemRaw(e,n){t.set(e,n)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function cy(t={}){const e={mounts:{"":t.driver||ay()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},n=u=>{for(const l of e.mountpoints)if(u.startsWith(l))return{base:l,relativeKey:u.slice(l.length),driver:e.mounts[l]};return{base:"",relativeKey:u,driver:e.mounts[""]}},r=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),i=(u,l)=>{if(e.watching){l=Ze(l);for(const h of e.watchListeners)h(u,l)}},s=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await zu(e.mounts[u],i,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,p=d=>{let g=f.get(d.base);return g||(g={driver:d.driver,base:d.base,items:[]},f.set(d.base,g)),g};for(const d of u){const g=typeof d=="string",y=Ze(g?d:d.key),_=g?void 0:d.value,A=g||!d.options?l:{...l,...d.options},b=n(y);p(b).items.push({key:y,value:_,relativeKey:b.relativeKey,options:A})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return Ie(f.hasItem,h,l)},getItem(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return Ie(f.getItem,h,l).then(p=>Qi(p))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?Ie(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:ry(h.base,p.key),value:Qi(p.value)}))):Promise.all(h.items.map(f=>Ie(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:Qi(p)})))))},getItemRaw(u,l={}){u=Ze(u);const{relativeKey:h,driver:f}=n(u);return f.getItemRaw?Ie(f.getItemRaw,h,l):Ie(f.getItem,h,l).then(p=>ey(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=Ze(u);const{relativeKey:f,driver:p}=n(u);p.setItem&&(await Ie(p.setItem,f,es(l),h),p.watch||i("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return Ie(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:es(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>Ie(h.driver.setItem,f.relativeKey,es(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=Ze(u);const{relativeKey:f,driver:p}=n(u);if(p.setItemRaw)await Ie(p.setItemRaw,f,l,h);else if(p.setItem)await Ie(p.setItem,f,Q0(l),h);else return;p.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=Ze(u);const{relativeKey:h,driver:f}=n(u);f.removeItem&&(await Ie(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await Ie(f.removeItem,h+"$",l),f.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=Ze(u);const{relativeKey:h,driver:f}=n(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await Ie(f.getMeta,h,l)),!l.nativeOnly){const d=await Ie(f.getItem,h+"$",l).then(g=>Qi(g));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=ts(u);const h=r(u,!0);let f=[];const p=[];let d=!0;for(const y of h){y.driver.flags?.maxDepth||(d=!1);const _=await Ie(y.driver.getKeys,y.relativeBase,l);for(const A of _){const b=y.mountpoint+Ze(A);f.some(v=>b.startsWith(v))||p.push(b)}f=[y.mountpoint,...f.filter(A=>!A.startsWith(y.mountpoint))]}const g=l.maxDepth!==void 0&&!d;return p.filter(y=>(!g||iy(y,l.maxDepth))&&sy(y,u))},async clear(u,l={}){u=ts(u),await Promise.all(r(u,!1).map(async h=>{if(h.driver.clear)return Ie(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>qu(u)))},async watch(u){return await s(),e.watchListeners.push(u),async()=>{e.watchListeners=e.watchListeners.filter(l=>l!==u),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(u,l){if(u=ts(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve(zu(l,i,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=ts(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await qu(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=Ze(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=Ze(u),r(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function zu(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function qu(t){typeof t.dispose=="function"&&await Ie(t.dispose)}function Kn(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function ju(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Kn(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let Do;function jr(){return Do||(Do=ju("keyval-store","keyval")),Do}function Vu(t,e=jr()){return e("readonly",n=>Kn(n.get(t)))}function uy(t,e,n=jr()){return n("readwrite",r=>(r.put(e,t),Kn(r.transaction)))}function ly(t,e=jr()){return e("readwrite",n=>(n.delete(t),Kn(n.transaction)))}function hy(t=jr()){return t("readwrite",e=>(e.clear(),Kn(e.transaction)))}function fy(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Kn(t.transaction)}function dy(t=jr()){return t("readonly",e=>{if(e.getAllKeys)return Kn(e.getAllKeys());const n=[];return fy(e,r=>n.push(r.key)).then(()=>n)})}const py=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),gy=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,n=t.replace(e,'$1"$2n"$3');return JSON.parse(n,(r,i)=>typeof i=="string"&&i.match(/^\d+n$/)?BigInt(i.substring(0,i.length-1)):i)};function gr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return gy(t)}catch{return t}}function Hn(t){return typeof t=="string"?t:py(t)||""}const yy="idb-keyval";var wy=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=ju(t.dbName,t.storeName)),{name:yy,options:t,async hasItem(i){return!(typeof await Vu(n(i),r)>"u")},async getItem(i){return await Vu(n(i),r)??null},setItem(i,s){return uy(n(i),s,r)},removeItem(i){return ly(n(i),r)},getKeys(){return dy(r)},clear(){return hy(r)}}};const my="WALLET_CONNECT_V2_INDEXED_DB",by="keyvaluestorage";class vy{constructor(){this.indexedDb=cy({driver:wy({dbName:my,storeName:by})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const n=await this.indexedDb.getItem(e);if(n!==null)return n}async setItem(e,n){await this.indexedDb.setItem(e,Hn(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var Oo=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},ns={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(n){return this.hasOwnProperty(n)?String(this[n]):null},t.prototype.setItem=function(n,r){this[n]=String(r)},t.prototype.removeItem=function(n){delete this[n]},t.prototype.clear=function(){const n=this;Object.keys(n).forEach(function(r){n[r]=void 0,delete n[r]})},t.prototype.key=function(n){return n=n||0,Object.keys(this)[n]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof Oo<"u"&&Oo.localStorage?ns.exports=Oo.localStorage:typeof window<"u"&&window.localStorage?ns.exports=window.localStorage:ns.exports=new e})();function Ey(t){var e;return[t[0],gr((e=t[1])!=null?e:"")]}class xy{constructor(){this.localStorage=ns.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(Ey)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return gr(n)}async setItem(e,n){this.localStorage.setItem(e,Hn(n))}async removeItem(e){this.localStorage.removeItem(e)}}const _y="wc_storage_version",Ku=1,Iy=async(t,e,n)=>{const r=_y,i=await e.getItem(r);if(i&&i>=Ku){n(e);return}const s=await t.getKeys();if(!s.length){n(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const u=await t.getItem(a);await e.setItem(a,u),o.push(a)}}await e.setItem(r,Ku),n(e),Sy(t,o)},Sy=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class Ay{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new xy;this.storage=e;try{const n=new vy;Iy(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}function Dy(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var Oy=$y;function $y(t,e,n){var r=n&&n.stringify||Dy,i=1;if(typeof t=="object"&&t!==null){var s=e.length+i;if(s===1)return t;var o=new Array(s);o[0]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var u="",l=1-i,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=r(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const Hu=Oy;var kt=Lt;const Vr=Ly().console||{},Ty={mapHttpRequest:is,mapHttpResponse:is,wrapRequestSerializer:To,wrapResponseSerializer:To,wrapErrorSerializer:To,req:is,res:is,err:Ny};function By(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function Lt(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const n=t.browser.write||Vr;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=By(t.browser.serialize,r);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=["error","fatal","warn","info","debug","trace"];typeof n=="function"&&(n.error=n.fatal=n.warn=n.info=n.debug=n.trace=n),t.enabled===!1&&(t.level="silent");const a=t.level||"info",c=Object.create(n);c.log||(c.log=Kr),Object.defineProperty(c,"levelVal",{get:l}),Object.defineProperty(c,"level",{get:h,set:f});const u={transmit:e,serialize:i,asObject:t.browser.asObject,levels:o,timestamp:Uy(t)};c.levels=Lt.levels,c.level=a,c.setMaxListeners=c.getMaxListeners=c.emit=c.addListener=c.on=c.prependListener=c.once=c.prependOnceListener=c.removeListener=c.removeAllListeners=c.listeners=c.listenerCount=c.eventNames=c.write=c.flush=Kr,c.serializers=r,c._serialize=i,c._stdErrSerialize=s,c.child=p,e&&(c._logEvent=$o());function l(){return this.level==="silent"?1/0:this.levels.values[this.level]}function h(){return this._level}function f(d){if(d!=="silent"&&!this.levels.values[d])throw Error("unknown level "+d);this._level=d,yr(u,c,"error","log"),yr(u,c,"fatal","error"),yr(u,c,"warn","error"),yr(u,c,"info","log"),yr(u,c,"debug","log"),yr(u,c,"trace","log")}function p(d,g){if(!d)throw new Error("missing bindings for child Pino");g=g||{},i&&d.serializers&&(g.serializers=d.serializers);const y=g.serializers;if(i&&y){var _=Object.assign({},r,y),A=t.browser.serialize===!0?Object.keys(_):i;delete d.serializers,rs([d],A,_,this._stdErrSerialize)}function b(v){this._childLevel=(v._childLevel|0)+1,this.error=wr(v,d,"error"),this.fatal=wr(v,d,"fatal"),this.warn=wr(v,d,"warn"),this.info=wr(v,d,"info"),this.debug=wr(v,d,"debug"),this.trace=wr(v,d,"trace"),_&&(this.serializers=_,this._serialize=A),e&&(this._logEvent=$o([].concat(v._logEvent.bindings,d)))}return b.prototype=this,new b(this)}return c}Lt.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},Lt.stdSerializers=Ty,Lt.stdTimeFunctions=Object.assign({},{nullTime:Wu,epochTime:Gu,unixTime:Fy,isoTime:ky});function yr(t,e,n,r){const i=Object.getPrototypeOf(e);e[n]=e.levelVal>e.levels.values[n]?Kr:i[n]?i[n]:Vr[n]||Vr[r]||Kr,Py(t,e,n)}function Py(t,e,n){!t.transmit&&e[n]===Kr||(e[n]=function(r){return function(){const s=t.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Vr?Vr:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];if(t.serialize&&!t.asObject&&rs(o,this._serialize,this.serializers,this._stdErrSerialize),t.asObject?r.call(a,Cy(this,n,o,s)):r.apply(a,o),t.transmit){const u=t.transmit.level||e.level,l=Lt.levels.values[u],h=Lt.levels.values[n];if(h<l)return;Ry(this,{ts:s,methodLevel:n,methodValue:h,transmitLevel:u,transmitValue:Lt.levels.values[t.transmit.level||e.level],send:t.transmit.send,val:e.levelVal},o)}}}(e[n]))}function Cy(t,e,n,r){t._serialize&&rs(n,t._serialize,t.serializers,t._stdErrSerialize);const i=n.slice();let s=i[0];const o={};r&&(o.time=r),o.level=Lt.levels.values[e];let a=(t._childLevel|0)+1;if(a<1&&(a=1),s!==null&&typeof s=="object"){for(;a--&&typeof i[0]=="object";)Object.assign(o,i.shift());s=i.length?Hu(i.shift(),i):void 0}else typeof s=="string"&&(s=Hu(i.shift(),i));return s!==void 0&&(o.msg=s),o}function rs(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=Lt.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i]))for(const s in t[i])e&&e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function wr(t,e,n){return function(){const r=new Array(1+arguments.length);r[0]=e;for(var i=1;i<r.length;i++)r[i]=arguments[i-1];return t[n].apply(this,r)}}function Ry(t,e,n){const r=e.send,i=e.ts,s=e.methodLevel,o=e.methodValue,a=e.val,c=t._logEvent.bindings;rs(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=i,t._logEvent.messages=n.filter(function(u){return c.indexOf(u)===-1}),t._logEvent.level.label=s,t._logEvent.level.value=o,r(s,t._logEvent,a),t._logEvent=$o(c)}function $o(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Ny(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function Uy(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Wu:Gu}function is(){return{}}function To(t){return t}function Kr(){}function Wu(){return!1}function Gu(){return Date.now()}function Fy(){return Math.round(Date.now()/1e3)}function ky(){return new Date(Date.now()).toISOString()}function Ly(){function t(e){return typeof e<"u"&&e}try{return typeof globalThis<"u"||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch{return t(self)||t(window)||t(this)||{}}}const My={level:"info"},Hr="custom_context",Bo=1e3*1024;class zy{constructor(e){this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class Yu{constructor(e){this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new zy(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}class Zu{constructor(e,n=Bo){this.level=e??"error",this.levelValue=kt.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Yu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===kt.levels.values.error?console.error(e):n===kt.levels.values.warn?console.warn(e):n===kt.levels.values.debug?console.debug(e):n===kt.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Hn({timestamp:new Date().toISOString(),log:e}));const n=typeof e=="string"?JSON.parse(e).level:e.level;n>=this.levelValue&&this.forwardToConsole(e,n)}getLogs(){return this.logs}clearLogs(){this.logs=new Yu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Hn({extraMetadata:e})),new Blob(n,{type:"application/json"})}}class qy{constructor(e,n=Bo){this.baseChunkLogger=new Zu(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}class jy{constructor(e,n=Bo){this.baseChunkLogger=new Zu(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}}var Vy=Object.defineProperty,Ky=Object.defineProperties,Hy=Object.getOwnPropertyDescriptors,Ju=Object.getOwnPropertySymbols,Wy=Object.prototype.hasOwnProperty,Gy=Object.prototype.propertyIsEnumerable,Xu=(t,e,n)=>e in t?Vy(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ss=(t,e)=>{for(var n in e||(e={}))Wy.call(e,n)&&Xu(t,n,e[n]);if(Ju)for(var n of Ju(e))Gy.call(e,n)&&Xu(t,n,e[n]);return t},os=(t,e)=>Ky(t,Hy(e));function Po(t){return os(ss({},t),{level:t?.level||My.level})}function Yy(t,e=Hr){return t[e]||""}function Zy(t,e,n=Hr){return t[n]=e,t}function Je(t,e=Hr){let n="";return typeof t.bindings>"u"?n=Yy(t,e):n=t.bindings().context||"",n}function Jy(t,e,n=Hr){const r=Je(t,n);return r.trim()?`${r}/${e}`:e}function Ke(t,e,n=Hr){const r=Jy(t,e,n),i=t.child({context:r});return Zy(i,r,n)}function Xy(t){var e,n;const r=new qy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt(os(ss({},t.opts),{level:"trace",browser:os(ss({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function Qy(t){var e;const n=new jy((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:kt(os(ss({},t.opts),{level:"trace"})),chunkLoggerController:n}}function ew(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?Xy(t):Qy(t)}var tw=Object.defineProperty,nw=(t,e,n)=>e in t?tw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Qu=(t,e,n)=>nw(t,typeof e!="symbol"?e+"":e,n);class rw extends jn{constructor(e){super(),this.opts=e,Qu(this,"protocol","wc"),Qu(this,"version",2)}}var iw=Object.defineProperty,sw=(t,e,n)=>e in t?iw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ow=(t,e,n)=>sw(t,typeof e!="symbol"?e+"":e,n);class aw extends jn{constructor(e,n){super(),this.core=e,this.logger=n,ow(this,"records",new Map)}}class cw{constructor(e,n){this.logger=e,this.core=n}}class uw extends jn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class lw extends jn{constructor(e){super()}}class hw{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class fw extends jn{constructor(e,n){super(),this.relayer=e,this.logger=n}}class dw extends jn{constructor(e,n){super(),this.core=e,this.logger=n}}class pw{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class gw{constructor(e,n){this.projectId=e,this.logger=n}}class yw{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var ww=Object.defineProperty,mw=(t,e,n)=>e in t?ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,el=(t,e,n)=>mw(t,typeof e!="symbol"?e+"":e,n);class bw{constructor(e){this.opts=e,el(this,"protocol","wc"),el(this,"version",2)}}class vw{constructor(e){this.client=e}}function Ew(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function tl(t,...e){if(!Ew(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function nl(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function xw(t,e){tl(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const mr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Co=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function _w(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function rl(t){return typeof t=="string"&&(t=_w(t)),tl(t),t}class Iw{clone(){return this._cloneInto()}}function Sw(t){const e=r=>t().update(rl(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function il(t=32){if(mr&&typeof mr.getRandomValues=="function")return mr.getRandomValues(new Uint8Array(t));if(mr&&typeof mr.randomBytes=="function")return mr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Aw(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}class Dw extends Iw{constructor(e,n,r,i){super(),this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Co(this.buffer)}update(e){nl(this);const{view:n,buffer:r,blockLen:i}=this;e=rl(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=Co(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){nl(this),xw(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;Aw(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Co(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.length=i,e.pos=a,e.finished=s,e.destroyed=o,i%n&&e.buffer.set(r),e}}const as=BigInt(2**32-1),Ro=BigInt(32);function sl(t,e=!1){return e?{h:Number(t&as),l:Number(t>>Ro&as)}:{h:Number(t>>Ro&as)|0,l:Number(t&as)|0}}function Ow(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let i=0;i<t.length;i++){const{h:s,l:o}=sl(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const $w=(t,e)=>BigInt(t>>>0)<<Ro|BigInt(e>>>0),Tw=(t,e,n)=>t>>>n,Bw=(t,e,n)=>t<<32-n|e>>>n,Pw=(t,e,n)=>t>>>n|e<<32-n,Cw=(t,e,n)=>t<<32-n|e>>>n,Rw=(t,e,n)=>t<<64-n|e>>>n-32,Nw=(t,e,n)=>t>>>n-32|e<<64-n,Uw=(t,e)=>e,Fw=(t,e)=>t,kw=(t,e,n)=>t<<n|e>>>32-n,Lw=(t,e,n)=>e<<n|t>>>32-n,Mw=(t,e,n)=>e<<n-32|t>>>64-n,zw=(t,e,n)=>t<<n-32|e>>>64-n;function qw(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const jw=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Vw=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Kw=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Hw=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ww=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Gw=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Y={fromBig:sl,split:Ow,toBig:$w,shrSH:Tw,shrSL:Bw,rotrSH:Pw,rotrSL:Cw,rotrBH:Rw,rotrBL:Nw,rotr32H:Uw,rotr32L:Fw,rotlSH:kw,rotlSL:Lw,rotlBH:Mw,rotlBL:zw,add:qw,add3L:jw,add3H:Vw,add4L:Kw,add4H:Hw,add5H:Gw,add5L:Ww},[Yw,Zw]=Y.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),dn=new Uint32Array(80),pn=new Uint32Array(80);class Jw extends Dw{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let b=0;b<16;b++,n+=4)dn[b]=e.getUint32(n),pn[b]=e.getUint32(n+=4);for(let b=16;b<80;b++){const v=dn[b-15]|0,x=pn[b-15]|0,T=Y.rotrSH(v,x,1)^Y.rotrSH(v,x,8)^Y.shrSH(v,x,7),R=Y.rotrSL(v,x,1)^Y.rotrSL(v,x,8)^Y.shrSL(v,x,7),C=dn[b-2]|0,m=pn[b-2]|0,B=Y.rotrSH(C,m,19)^Y.rotrBH(C,m,61)^Y.shrSH(C,m,6),S=Y.rotrSL(C,m,19)^Y.rotrBL(C,m,61)^Y.shrSL(C,m,6),O=Y.add4L(R,S,pn[b-7],pn[b-16]),P=Y.add4H(O,T,B,dn[b-7],dn[b-16]);dn[b]=P|0,pn[b]=O|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let b=0;b<80;b++){const v=Y.rotrSH(h,f,14)^Y.rotrSH(h,f,18)^Y.rotrBH(h,f,41),x=Y.rotrSL(h,f,14)^Y.rotrSL(h,f,18)^Y.rotrBL(h,f,41),T=h&p^~h&g,R=f&d^~f&y,C=Y.add5L(A,x,R,Zw[b],pn[b]),m=Y.add5H(C,_,v,T,Yw[b],dn[b]),B=C|0,S=Y.rotrSH(r,i,28)^Y.rotrBH(r,i,34)^Y.rotrBH(r,i,39),O=Y.rotrSL(r,i,28)^Y.rotrBL(r,i,34)^Y.rotrBL(r,i,39),P=r&s^r&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Y.add(u|0,l|0,m|0,B|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const E=Y.add3L(B,O,F);r=Y.add3H(E,m,S,P),i=E|0}({h:r,l:i}=Y.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Y.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Y.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Y.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Y.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Y.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Y.add(this.Gh|0,this.Gl|0,g|0,y|0),{h:_,l:A}=Y.add(this.Hh|0,this.Hl|0,_|0,A|0),this.set(r,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){dn.fill(0),pn.fill(0)}destroy(){this.buffer.fill(0),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Xw=Sw(()=>new Jw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const No=BigInt(0),ol=BigInt(1),Qw=BigInt(2);function Uo(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Fo(t){if(!Uo(t))throw new Error("Uint8Array expected")}function ko(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const e1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Lo(t){Fo(t);let e="";for(let n=0;n<t.length;n++)e+=e1[t[n]];return e}function al(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?No:BigInt("0x"+t)}const Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function cl(t){if(t>=Jt._0&&t<=Jt._9)return t-Jt._0;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function ul(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=cl(t.charCodeAt(s)),a=cl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function t1(t){return al(Lo(t))}function cs(t){return Fo(t),al(Lo(Uint8Array.from(t).reverse()))}function ll(t,e){return ul(t.toString(16).padStart(e*2,"0"))}function Mo(t,e){return ll(t,e).reverse()}function Xt(t,e,n){let r;if(typeof e=="string")try{r=ul(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Uo(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function hl(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Fo(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}const zo=t=>typeof t=="bigint"&&No<=t;function n1(t,e,n){return zo(t)&&zo(e)&&zo(n)&&e<=t&&t<n}function Wr(t,e,n,r){if(!n1(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function r1(t){let e;for(e=0;t>No;t>>=ol,e+=1);return e}const i1=t=>(Qw<<BigInt(t-1))-ol,s1={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Uo(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function qo(t,e,n={}){const r=(i,s,o)=>{const a=s1[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function fl(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Se=BigInt(0),pe=BigInt(1),Wn=BigInt(2),o1=BigInt(3),jo=BigInt(4),dl=BigInt(5),pl=BigInt(8);function ve(t,e){const n=t%e;return n>=Se?n:e+n}function a1(t,e,n){if(e<Se)throw new Error("invalid exponent, negatives unsupported");if(n<=Se)throw new Error("invalid modulus");if(n===pe)return Se;let r=pe;for(;e>Se;)e&pe&&(r=r*t%n),t=t*t%n,e>>=pe;return r}function Mt(t,e,n){let r=t;for(;e-- >Se;)r*=r,r%=n;return r}function gl(t,e){if(t===Se)throw new Error("invert: expected non-zero number");if(e<=Se)throw new Error("invert: expected positive modulus, got "+e);let n=ve(t,e),r=e,i=Se,s=pe;for(;n!==Se;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==pe)throw new Error("invert: does not exist");return ve(i,e)}function c1(t){const e=(t-pe)/Wn;let n,r,i;for(n=t-pe,r=0;n%Wn===Se;n/=Wn,r++);for(i=Wn;i<t&&a1(i,e,t)!==t-pe;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+pe)/jo;return function(a,c){const u=a.pow(c,o);if(!a.eql(a.sqr(u),c))throw new Error("Cannot find square root");return u}}const s=(n+pe)/Wn;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,u=o.pow(o.mul(o.ONE,i),n),l=o.pow(a,s),h=o.pow(a,n);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,pe<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function u1(t){if(t%jo===o1){const e=(t+pe)/jo;return function(n,r){const i=n.pow(r,e);if(!n.eql(n.sqr(i),r))throw new Error("Cannot find square root");return i}}if(t%pl===dl){const e=(t-dl)/pl;return function(n,r){const i=n.mul(r,Wn),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Wn),s),c=n.mul(o,n.sub(a,n.ONE));if(!n.eql(n.sqr(c),r))throw new Error("Cannot find square root");return c}}return c1(t)}const l1=(t,e)=>(ve(t,e)&pe)===pe,h1=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function f1(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=h1.reduce((r,i)=>(r[i]="function",r),e);return qo(t,n)}function d1(t,e,n){if(n<Se)throw new Error("invalid exponent, negatives unsupported");if(n===Se)return t.ONE;if(n===pe)return e;let r=t.ONE,i=e;for(;n>Se;)n&pe&&(r=t.mul(r,i)),i=t.sqr(i),n>>=pe;return r}function p1(t,e){const n=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(n[a]=s,t.mul(s,o)),t.ONE),i=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(n[a]=t.mul(s,n[a]),t.mul(s,o)),i),n}function yl(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function wl(t,e,n=!1,r={}){if(t<=Se)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=yl(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:i1(i),ZERO:Se,ONE:pe,create:c=>ve(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Se<=c&&c<t},is0:c=>c===Se,isOdd:c=>(c&pe)===pe,neg:c=>ve(-c,t),eql:(c,u)=>c===u,sqr:c=>ve(c*c,t),add:(c,u)=>ve(c+u,t),sub:(c,u)=>ve(c-u,t),mul:(c,u)=>ve(c*u,t),pow:(c,u)=>d1(a,c,u),div:(c,u)=>ve(c*gl(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>gl(c,t),sqrt:r.sqrt||(c=>(o||(o=u1(t)),o(a,c))),invertBatch:c=>p1(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?Mo(c,s):ll(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?cs(c):t1(c)}});return Object.freeze(a)}const ml=BigInt(0),us=BigInt(1);function Vo(t,e){const n=e.negate();return t?n:e}function bl(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ko(t,e){bl(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function g1(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function y1(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Ho=new WeakMap,vl=new WeakMap;function Wo(t){return vl.get(t)||1}function w1(t,e){return{constTimeNegate:Vo,hasPrecomputes(n){return Wo(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>ml;)r&us&&(i=i.add(s)),s=s.double(),r>>=us;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Ko(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){const{windows:s,windowSize:o}=Ko(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,h=BigInt(n);for(let f=0;f<s;f++){const p=f*o;let d=Number(i&u);i>>=h,d>o&&(d-=l,i+=us);const g=p,y=p+Math.abs(d)-1,_=f%2!==0,A=d<0;d===0?c=c.add(Vo(_,r[g])):a=a.add(Vo(A,r[y]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=Ko(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let h=0;h<o;h++){const f=h*a;if(i===ml)break;let p=Number(i&c);if(i>>=l,p>a&&(p-=u,i+=us),p===0)continue;let d=r[f+Math.abs(p)-1];p<0&&(d=d.negate()),s=s.add(d)}return s},getPrecomputes(n,r,i){let s=Ho.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Ho.set(r,i(s))),s},wNAFCached(n,r,i){const s=Wo(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Wo(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){bl(r,e),vl.set(n,r),Ho.delete(n)}}}function m1(t,e,n,r){if(g1(n,t),y1(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=r1(BigInt(n.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(i),u=Math.floor((e.BITS-1)/o)*o;let l=i;for(let h=u;h>=0;h-=o){c.fill(i);for(let p=0;p<r.length;p++){const d=r[p],g=Number(d>>BigInt(h)&BigInt(a));c[g]=c[g].add(n[p])}let f=i;for(let p=c.length-1,d=i;p>0;p--)d=d.add(c[p]),f=f.add(d);if(l=l.add(f),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function b1(t){return f1(t.Fp),qo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yl(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Tt=BigInt(0),Xe=BigInt(1),ls=BigInt(2),v1=BigInt(8),E1={zip215:!0};function x1(t){const e=b1(t);return qo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function _1(t){const e=x1(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=ls<<BigInt(a*8)-Xe,l=n.create,h=wl(e.n,e.nBitLength),f=e.uvRatio||((E,w)=>{try{return{isValid:!0,value:n.sqrt(E*n.inv(w))}}catch{return{isValid:!1,value:Tt}}}),p=e.adjustScalarBytes||(E=>E),d=e.domain||((E,w,I)=>{if(ko("phflag",I),w.length||I)throw new Error("Contexts/pre-hash are not supported");return E});function g(E,w){Wr("coordinate "+E,w,Tt,u)}function y(E){if(!(E instanceof b))throw new Error("ExtendedPoint expected")}const _=fl((E,w)=>{const{ex:I,ey:$,ez:D}=E,N=E.is0();w==null&&(w=N?v1:n.inv(D));const U=l(I*w),L=l($*w),j=l(D*w);if(N)return{x:Tt,y:Xe};if(j!==Xe)throw new Error("invZ was invalid");return{x:U,y:L}}),A=fl(E=>{const{a:w,d:I}=e;if(E.is0())throw new Error("bad point: ZERO");const{ex:$,ey:D,ez:N,et:U}=E,L=l($*$),j=l(D*D),V=l(N*N),K=l(V*V),H=l(L*w),Z=l(V*l(H+j)),Q=l(K+l(I*l(L*j)));if(Z!==Q)throw new Error("bad point: equation left != right (1)");const W=l($*D),ae=l(N*U);if(W!==ae)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(w,I,$,D){this.ex=w,this.ey=I,this.ez=$,this.et=D,g("x",w),g("y",I),g("z",$),g("t",D),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof b)throw new Error("extended point not allowed");const{x:I,y:$}=w||{};return g("x",I),g("y",$),new b(I,$,Xe,l(I*$))}static normalizeZ(w){const I=n.invertBatch(w.map($=>$.ez));return w.map(($,D)=>$.toAffine(I[D])).map(b.fromAffine)}static msm(w,I){return m1(b,h,w,I)}_setWindowSize(w){T.setWindowSize(this,w)}assertValidity(){A(this)}equals(w){y(w);const{ex:I,ey:$,ez:D}=this,{ex:N,ey:U,ez:L}=w,j=l(I*L),V=l(N*D),K=l($*L),H=l(U*D);return j===V&&K===H}is0(){return this.equals(b.ZERO)}negate(){return new b(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:I,ey:$,ez:D}=this,N=l(I*I),U=l($*$),L=l(ls*l(D*D)),j=l(w*N),V=I+$,K=l(l(V*V)-N-U),H=j+U,Z=H-L,Q=j-U,W=l(K*Z),ae=l(H*Q),ye=l(K*Q),gt=l(Z*H);return new b(W,ae,gt,ye)}add(w){y(w);const{a:I,d:$}=e,{ex:D,ey:N,ez:U,et:L}=this,{ex:j,ey:V,ez:K,et:H}=w;if(I===BigInt(-1)){const t0=l((N-D)*(V+j)),n0=l((N+D)*(V-j)),hu=l(n0-t0);if(hu===Tt)return this.double();const r0=l(U*ls*H),i0=l(L*ls*K),s0=i0+r0,o0=n0+t0,a0=i0-r0,$5=l(s0*hu),T5=l(o0*a0),B5=l(s0*a0),P5=l(hu*o0);return new b($5,T5,P5,B5)}const Z=l(D*j),Q=l(N*V),W=l(L*$*H),ae=l(U*K),ye=l((D+N)*(j+V)-Z-Q),gt=ae-W,Ot=ae+W,$t=l(Q-I*Z),Zt=l(ye*gt),go=l(Ot*$t),D5=l(ye*$t),O5=l(gt*Ot);return new b(Zt,go,O5,D5)}subtract(w){return this.add(w.negate())}wNAF(w){return T.wNAFCached(this,w,b.normalizeZ)}multiply(w){const I=w;Wr("scalar",I,Xe,r);const{p:$,f:D}=this.wNAF(I);return b.normalizeZ([$,D])[0]}multiplyUnsafe(w,I=b.ZERO){const $=w;return Wr("scalar",$,Tt,r),$===Tt?x:this.is0()||$===Xe?this:T.wNAFCachedUnsafe(this,$,b.normalizeZ,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,r).is0()}toAffine(w){return _(this,w)}clearCofactor(){const{h:w}=e;return w===Xe?this:this.multiplyUnsafe(w)}static fromHex(w,I=!1){const{d:$,a:D}=e,N=n.BYTES;w=Xt("pointHex",w,N),ko("zip215",I);const U=w.slice(),L=w[N-1];U[N-1]=L&-129;const j=cs(U),V=I?u:n.ORDER;Wr("pointHex.y",j,Tt,V);const K=l(j*j),H=l(K-Xe),Z=l($*K-D);let{isValid:Q,value:W}=f(H,Z);if(!Q)throw new Error("Point.fromHex: invalid y coordinate");const ae=(W&Xe)===Xe,ye=(L&128)!==0;if(!I&&W===Tt&&ye)throw new Error("Point.fromHex: x=0 and x_0=1");return ye!==ae&&(W=l(-W)),b.fromAffine({x:W,y:j})}static fromPrivateKey(w){return m(w).point}toRawBytes(){const{x:w,y:I}=this.toAffine(),$=Mo(I,n.BYTES);return $[$.length-1]|=w&Xe?128:0,$}toHex(){return Lo(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,Xe,l(e.Gx*e.Gy)),b.ZERO=new b(Tt,Xe,Xe,Tt);const{BASE:v,ZERO:x}=b,T=w1(b,a*8);function R(E){return ve(E,r)}function C(E){return R(cs(E))}function m(E){const w=n.BYTES;E=Xt("private key",E,w);const I=Xt("hashed private key",s(E),2*w),$=p(I.slice(0,w)),D=I.slice(w,2*w),N=C($),U=v.multiply(N),L=U.toRawBytes();return{head:$,prefix:D,scalar:N,point:U,pointBytes:L}}function B(E){return m(E).pointBytes}function S(E=new Uint8Array,...w){const I=hl(...w);return C(s(d(I,Xt("context",E),!!i)))}function O(E,w,I={}){E=Xt("message",E),i&&(E=i(E));const{prefix:$,scalar:D,pointBytes:N}=m(w),U=S(I.context,$,E),L=v.multiply(U).toRawBytes(),j=S(I.context,L,N,E),V=R(U+j*D);Wr("signature.s",V,Tt,r);const K=hl(L,Mo(V,n.BYTES));return Xt("result",K,n.BYTES*2)}const P=E1;function F(E,w,I,$=P){const{context:D,zip215:N}=$,U=n.BYTES;E=Xt("signature",E,2*U),w=Xt("message",w),I=Xt("publicKey",I,U),N!==void 0&&ko("zip215",N),i&&(w=i(w));const L=cs(E.slice(U,2*U));let j,V,K;try{j=b.fromHex(I,N),V=b.fromHex(E.slice(0,U),N),K=v.multiplyUnsafe(L)}catch{return!1}if(!N&&j.isSmallOrder())return!1;const H=S(D,V.toRawBytes(),j.toRawBytes(),w);return V.add(j.multiplyUnsafe(H)).subtract(K).clearCofactor().equals(b.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:B,sign:O,verify:F,ExtendedPoint:b,utils:{getExtendedPublicKey:m,randomPrivateKey:()=>o(n.BYTES),precompute(E=8,w=b.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const Go=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),El=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const I1=BigInt(1),xl=BigInt(2);BigInt(3);const S1=BigInt(5),A1=BigInt(8);function D1(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Go,o=t*t%s*t%s,a=Mt(o,xl,s)*o%s,c=Mt(a,I1,s)*t%s,u=Mt(c,S1,s)*c%s,l=Mt(u,e,s)*u%s,h=Mt(l,n,s)*l%s,f=Mt(h,r,s)*h%s,p=Mt(f,i,s)*f%s,d=Mt(p,i,s)*f%s,g=Mt(d,e,s)*u%s;return{pow_p_5_8:Mt(g,xl,s)*t%s,b2:o}}function O1(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function $1(t,e){const n=Go,r=ve(e*e*e,n),i=ve(r*r*e,n),s=D1(t*i).pow_p_5_8;let o=ve(t*r*s,n);const a=ve(e*o*o,n),c=o,u=ve(o*El,n),l=a===t,h=a===ve(-t,n),f=a===ve(-t*El,n);return l&&(o=c),(h||f)&&(o=u),l1(o,n)&&(o=ve(-o,n)),{isValid:l||h,value:o}}const T1=wl(Go,void 0,!0),B1={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:T1,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:A1,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Xw,randomBytes:il,adjustScalarBytes:O1,uvRatio:$1},_l=_1(B1),P1="EdDSA",C1="JWT",hs=".",fs="base64url",Il="utf8",Sl="utf8",R1=":",N1="did",U1="key",Al="base58btc",F1="z",k1="K36",L1=32;function Yo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Dl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Yo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ol(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Dl(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Yo(n)}function M1(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var z1=M1,q1=z1;const $l=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},j1=t=>new TextEncoder().encode(t),V1=t=>new TextDecoder().decode(t);class K1{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class H1{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Tl(this,e)}}class W1{constructor(e){this.decoders=e}or(e){return Tl(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Tl=(t,e)=>new W1({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class G1{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new K1(e,n,r),this.decoder=new H1(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const ds=({name:t,prefix:e,encode:n,decode:r})=>new G1(t,e,n,r),Gr=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=q1(n,e);return ds({prefix:t,name:e,encode:r,decode:s=>$l(i(s))})},Y1=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Z1=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Oe=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>ds({prefix:e,name:t,encode(i){return Z1(i,r,n)},decode(i){return Y1(i,r,n,t)}}),J1=ds({prefix:"\0",name:"identity",encode:t=>V1(t),decode:t=>j1(t)});var X1=Object.freeze({__proto__:null,identity:J1});const Q1=Oe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var em=Object.freeze({__proto__:null,base2:Q1});const tm=Oe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var nm=Object.freeze({__proto__:null,base8:tm});const rm=Gr({prefix:"9",name:"base10",alphabet:"0123456789"});var im=Object.freeze({__proto__:null,base10:rm});const sm=Oe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),om=Oe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var am=Object.freeze({__proto__:null,base16:sm,base16upper:om});const cm=Oe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),um=Oe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),lm=Oe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),hm=Oe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),fm=Oe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),dm=Oe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),pm=Oe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),gm=Oe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),ym=Oe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var wm=Object.freeze({__proto__:null,base32:cm,base32upper:um,base32pad:lm,base32padupper:hm,base32hex:fm,base32hexupper:dm,base32hexpad:pm,base32hexpadupper:gm,base32z:ym});const mm=Gr({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),bm=Gr({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var vm=Object.freeze({__proto__:null,base36:mm,base36upper:bm});const Em=Gr({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),xm=Gr({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var _m=Object.freeze({__proto__:null,base58btc:Em,base58flickr:xm});const Im=Oe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Sm=Oe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Am=Oe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Dm=Oe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Om=Object.freeze({__proto__:null,base64:Im,base64pad:Sm,base64url:Am,base64urlpad:Dm});const Bl=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),$m=Bl.reduce((t,e,n)=>(t[n]=e,t),[]),Tm=Bl.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Bm(t){return t.reduce((e,n)=>(e+=$m[n],e),"")}function Pm(t){const e=[];for(const n of t){const r=Tm[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Cm=ds({prefix:"\u{1F680}",name:"base256emoji",encode:Bm,decode:Pm});var Rm=Object.freeze({__proto__:null,base256emoji:Cm}),Nm=Cl,Pl=128,Um=127,Fm=~Um,km=Math.pow(2,31);function Cl(t,e,n){e=e||[],n=n||0;for(var r=n;t>=km;)e[n++]=t&255|Pl,t/=128;for(;t&Fm;)e[n++]=t&255|Pl,t>>>=7;return e[n]=t|0,Cl.bytes=n-r+1,e}var Lm=Zo,Mm=128,Rl=127;function Zo(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Zo.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Rl)<<i:(o&Rl)*Math.pow(2,i),i+=7}while(o>=Mm);return Zo.bytes=s-r,n}var zm=Math.pow(2,7),qm=Math.pow(2,14),jm=Math.pow(2,21),Vm=Math.pow(2,28),Km=Math.pow(2,35),Hm=Math.pow(2,42),Wm=Math.pow(2,49),Gm=Math.pow(2,56),Ym=Math.pow(2,63),Zm=function(t){return t<zm?1:t<qm?2:t<jm?3:t<Vm?4:t<Km?5:t<Hm?6:t<Wm?7:t<Gm?8:t<Ym?9:10},Jm={encode:Nm,decode:Lm,encodingLength:Zm},Nl=Jm;const Ul=(t,e,n=0)=>(Nl.encode(t,e,n),e),Fl=t=>Nl.encodingLength(t),Jo=(t,e)=>{const n=e.byteLength,r=Fl(t),i=r+Fl(n),s=new Uint8Array(i+n);return Ul(t,s,0),Ul(n,s,r),s.set(e,i),new Xm(t,n,e,s)};class Xm{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const kl=({name:t,code:e,encode:n})=>new Qm(t,e,n);class Qm{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Jo(this.code,n):n.then(r=>Jo(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ll=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),eb=kl({name:"sha2-256",code:18,encode:Ll("SHA-256")}),tb=kl({name:"sha2-512",code:19,encode:Ll("SHA-512")});var nb=Object.freeze({__proto__:null,sha256:eb,sha512:tb});const Ml=0,rb="identity",zl=$l;var ib=Object.freeze({__proto__:null,identity:{code:Ml,name:rb,encode:zl,digest:t=>Jo(Ml,zl(t))}});new TextEncoder,new TextDecoder;const ql={...X1,...em,...nm,...im,...am,...wm,...vm,..._m,...Om,...Rm};({...nb,...ib});function jl(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Vl=jl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Xo=jl("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Dl(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),Kl={utf8:Vl,"utf-8":Vl,hex:ql.base16,latin1:Xo,ascii:Xo,binary:Xo,...ql};function ps(t,e="utf8"){const n=Kl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}function br(t,e="utf8"){const n=Kl[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Yo(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Hl(t){return gr(ps(br(t,fs),Il))}function gs(t){return ps(br(Hn(t),Il),fs)}function Wl(t){const e=br(k1,Al),n=F1+ps(Ol([e,t]),Al);return[N1,U1,n].join(R1)}function sb(t){return ps(t,fs)}function ob(t){return br(t,fs)}function ab(t){return br([gs(t.header),gs(t.payload)].join(hs),Sl)}function cb(t){return[gs(t.header),gs(t.payload),sb(t.signature)].join(hs)}function Qo(t){const e=t.split(hs),n=Hl(e[0]),r=Hl(e[1]),i=ob(e[2]),s=br(e.slice(0,2).join(hs),Sl);return{header:n,payload:r,signature:i,data:s}}function Gl(t=il(L1)){const e=_l.getPublicKey(t);return{secretKey:Ol([t,e]),publicKey:e}}async function ub(t,e,n,r,i=M.fromMiliseconds(Date.now())){const s={alg:P1,typ:C1},o=Wl(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=ab({header:s,payload:c}),l=_l.sign(u,r.secretKey.slice(0,32));return cb({header:s,payload:c,signature:l})}var Yl=function(t,e,n){if(n||arguments.length===2)for(var r=0,i=e.length,s;r<i;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},lb=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),hb=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),fb=function(){function t(e,n,r,i){this.name=e,this.version=n,this.os=r,this.bot=i,this.type="bot-device"}return t}(),db=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),pb=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),gb=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,yb=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Zl=3,wb=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",gb]],Jl=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];function mb(t){return t?Xl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new pb:typeof navigator<"u"?Xl(navigator.userAgent):Eb()}function bb(t){return t!==""&&wb.reduce(function(e,n){var r=n[0],i=n[1];if(e)return e;var s=i.exec(t);return!!s&&[r,s]},!1)}function Xl(t){var e=bb(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new db;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<Zl&&(i=Yl(Yl([],i,!0),xb(Zl-i.length),!0)):i=[];var s=i.join("."),o=vb(t),a=yb.exec(t);return a&&a[1]?new fb(n,s,o,a[1]):new lb(n,s,o)}function vb(t){for(var e=0,n=Jl.length;e<n;e++){var r=Jl[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function Eb(){var t=typeof process<"u"&&process.version;return t?new hb(process.version.slice(1)):null}function xb(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var ue={};Object.defineProperty(ue,"__esModule",{value:!0}),ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=Ql=ue.getLocation=ue.getLocationOrThrow=ea=ue.getNavigator=ue.getNavigatorOrThrow=Yn=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function Gn(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=Gn;function vr(t){const e=Gn(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=vr;function _b(){return vr("document")}ue.getDocumentOrThrow=_b;function Ib(){return Gn("document")}var Yn=ue.getDocument=Ib;function Sb(){return vr("navigator")}ue.getNavigatorOrThrow=Sb;function Ab(){return Gn("navigator")}var ea=ue.getNavigator=Ab;function Db(){return vr("location")}ue.getLocationOrThrow=Db;function Ob(){return Gn("location")}var Ql=ue.getLocation=Ob;function $b(){return vr("crypto")}ue.getCryptoOrThrow=$b;function Tb(){return Gn("crypto")}ue.getCrypto=Tb;function Bb(){return vr("localStorage")}ue.getLocalStorageOrThrow=Bb;function Pb(){return Gn("localStorage")}ue.getLocalStorage=Pb;var ta={};Object.defineProperty(ta,"__esModule",{value:!0});var eh=ta.getWindowMetadata=void 0;const th=ue;function Cb(){let t,e;try{t=th.getDocumentOrThrow(),e=th.getLocationOrThrow()}catch{return null}function n(){const h=t.getElementsByTagName("link"),f=[];for(let p=0;p<h.length;p++){const d=h[p],g=d.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const y=d.getAttribute("href");if(y)if(y.toLowerCase().indexOf("https:")===-1&&y.toLowerCase().indexOf("http:")===-1&&y.indexOf("//")!==0){let _=e.protocol+"//"+e.host;if(y.indexOf("/")===0)_+=y;else{const A=e.pathname.split("/");A.pop();const b=A.join("/");_+=b+"/"+y}f.push(_)}else if(y.indexOf("//")===0){const _=e.protocol+y;f.push(_)}else f.push(y)}}return f}function r(...h){const f=t.getElementsByTagName("meta");for(let p=0;p<f.length;p++){const d=f[p],g=["itemprop","property","name"].map(y=>d.getAttribute(y)).filter(y=>y?h.includes(y):!1);if(g.length&&g){const y=d.getAttribute("content");if(y)return y}}return""}function i(){let h=r("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return r("description","og:description","twitter:description","keywords")}const o=i(),a=s(),c=e.origin,u=n();return{description:a,url:c,icons:u,name:o}}eh=ta.getWindowMetadata=Cb;function Yr(t,{strict:e=!0}={}){return!t||typeof t!="string"?!1:e?/^0x[0-9a-fA-F]*$/.test(t):t.startsWith("0x")}function na(t){return Yr(t,{strict:!1})?Math.ceil((t.length-2)/2):t.length}const nh="2.31.0";let ra={getDocsUrl:({docsBaseUrl:t,docsPath:e="",docsSlug:n})=>e?`${t??"https://viem.sh"}${e}${n?`#${n}`:""}`:void 0,version:`viem@${nh}`};class Zn extends Error{constructor(e,n={}){const r=n.cause instanceof Zn?n.cause.details:n.cause?.message?n.cause.message:n.details,i=n.cause instanceof Zn&&n.cause.docsPath||n.docsPath,s=ra.getDocsUrl?.({...n,docsPath:i}),o=[e||"An error occurred.","",...n.metaMessages?[...n.metaMessages,""]:[],...s?[`Docs: ${s}`]:[],...r?[`Details: ${r}`]:[],...ra.version?[`Version: ${ra.version}`]:[]].join(`
|
|
15
|
+
`);super(o,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=r,this.docsPath=i,this.metaMessages=n.metaMessages,this.name=n.name??this.name,this.shortMessage=e,this.version=nh}walk(e){return rh(this,e)}}function rh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause!==void 0?rh(t.cause,e):e?null:t}class ih extends Zn{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (${e}) exceeds padding size (${n}).`,{name:"SizeExceedsPaddingSizeError"})}}function Er(t,{dir:e,size:n=32}={}){return typeof t=="string"?Rb(t,{dir:e,size:n}):Nb(t,{dir:e,size:n})}function Rb(t,{dir:e,size:n=32}={}){if(n===null)return t;const r=t.replace("0x","");if(r.length>n*2)throw new ih({size:Math.ceil(r.length/2),targetSize:n,type:"hex"});return`0x${r[e==="right"?"padEnd":"padStart"](n*2,"0")}`}function Nb(t,{dir:e,size:n=32}={}){if(n===null)return t;if(t.length>n)throw new ih({size:t.length,targetSize:n,type:"bytes"});const r=new Uint8Array(n);for(let i=0;i<n;i++){const s=e==="right";r[s?i:n-i-1]=t[s?i:t.length-i-1]}return r}class Ub extends Zn{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number "${s}" is not in safe ${i?`${i*8}-bit ${r?"signed":"unsigned"} `:""}integer range ${e?`(${n} to ${e})`:`(above ${n})`}`,{name:"IntegerOutOfRangeError"})}}class Fb extends Zn{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed ${n} bytes. Given size: ${e} bytes.`,{name:"SizeOverflowError"})}}function xr(t,{size:e}){if(na(t)>e)throw new Fb({givenSize:na(t),maxSize:e})}function ia(t,e={}){const{signed:n}=e;e.size&&xr(t,{size:e.size});const r=BigInt(t);if(!n)return r;const i=(t.length-2)/2,s=(1n<<BigInt(i)*8n-1n)-1n;return r<=s?r:r-BigInt(`0x${"f".padStart(i*2,"f")}`)-1n}function kb(t,e={}){return Number(ia(t,e))}const Lb=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function sa(t,e={}){return typeof t=="number"||typeof t=="bigint"?oa(t,e):typeof t=="string"?qb(t,e):typeof t=="boolean"?Mb(t,e):sh(t,e)}function Mb(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{size:e.size})):n}function sh(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=Lb[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(xr(r,{size:e.size}),Er(r,{dir:"right",size:e.size})):r}function oa(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const c=typeof t=="bigint"?"n":"";throw new Ub({max:s?`${s}${c}`:void 0,min:`${o}${c}`,signed:n,size:r,value:`${t}${c}`})}const a=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?Er(a,{size:r}):a}const zb=new TextEncoder;function qb(t,e={}){const n=zb.encode(t);return sh(n,e)}const jb=new TextEncoder;function Vb(t,e={}){return typeof t=="number"||typeof t=="bigint"?Hb(t,e):typeof t=="boolean"?Kb(t,e):Yr(t)?ah(t,e):ch(t,e)}function Kb(t,e={}){const n=new Uint8Array(1);return n[0]=Number(t),typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{size:e.size})):n}const Qt={zero:48,nine:57,A:65,F:70,a:97,f:102};function oh(t){if(t>=Qt.zero&&t<=Qt.nine)return t-Qt.zero;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function ah(t,e={}){let n=t;e.size&&(xr(n,{size:e.size}),n=Er(n,{dir:"right",size:e.size}));let r=n.slice(2);r.length%2&&(r=`0${r}`);const i=r.length/2,s=new Uint8Array(i);for(let o=0,a=0;o<i;o++){const c=oh(r.charCodeAt(a++)),u=oh(r.charCodeAt(a++));if(c===void 0||u===void 0)throw new Zn(`Invalid byte sequence ("${r[a-2]}${r[a-1]}" in "${r}").`);s[o]=c*16+u}return s}function Hb(t,e){const n=oa(t,e);return ah(n)}function ch(t,e={}){const n=jb.encode(t);return typeof e.size=="number"?(xr(n,{size:e.size}),Er(n,{dir:"right",size:e.size})):n}const ys=BigInt(2**32-1),uh=BigInt(32);function Wb(t,e=!1){return e?{h:Number(t&ys),l:Number(t>>uh&ys)}:{h:Number(t>>uh&ys)|0,l:Number(t&ys)|0}}function Gb(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=Wb(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Yb=(t,e,n)=>t<<n|e>>>32-n,Zb=(t,e,n)=>e<<n|t>>>32-n,Jb=(t,e,n)=>e<<n-32|t>>>64-n,Xb=(t,e,n)=>t<<n-32|e>>>64-n,_r=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Qb(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Zr(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Jn(t,...e){if(!Qb(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function e2(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Zr(t.outputLen),Zr(t.blockLen)}function Ir(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function lh(t,e){Jn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function t2(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Sr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function aa(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function zt(t,e){return t<<32-e|t>>>e}const n2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function r2(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function i2(t){for(let e=0;e<t.length;e++)t[e]=r2(t[e]);return t}const hh=n2?t=>t:i2;function s2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ws(t){return typeof t=="string"&&(t=s2(t)),Jn(t),t}function o2(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Jn(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class ca{}function fh(t){const e=r=>t().update(ws(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function dh(t=32){if(_r&&typeof _r.getRandomValues=="function")return _r.getRandomValues(new Uint8Array(t));if(_r&&typeof _r.randomBytes=="function")return Uint8Array.from(_r.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const a2=BigInt(0),Jr=BigInt(1),c2=BigInt(2),u2=BigInt(7),l2=BigInt(256),h2=BigInt(113),ph=[],gh=[],yh=[];for(let t=0,e=Jr,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],ph.push(2*(5*r+n)),gh.push((t+1)*(t+2)/2%64);let i=a2;for(let s=0;s<7;s++)e=(e<<Jr^(e>>u2)*h2)%l2,e&c2&&(i^=Jr<<(Jr<<BigInt(s))-Jr);yh.push(i)}const wh=Gb(yh,!0),f2=wh[0],d2=wh[1],mh=(t,e,n)=>n>32?Jb(t,e,n):Yb(t,e,n),bh=(t,e,n)=>n>32?Xb(t,e,n):Zb(t,e,n);function p2(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],h=mh(u,l,1)^n[a],f=bh(u,l,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=gh[o],c=mh(i,s,a),u=bh(i,s,a),l=ph[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=f2[r],t[1]^=d2[r]}Sr(n)}class ua extends ca{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,Zr(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=t2(this.state)}clone(){return this._cloneInto()}keccak(){hh(this.state32),p2(this.state32,this.rounds),hh(this.state32),this.posOut=0,this.pos=0}update(e){Ir(this),e=ws(e),Jn(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){Ir(this,!1),Jn(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Zr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(lh(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Sr(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ua(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const g2=(t,e,n)=>fh(()=>new ua(e,t,n)),vh=g2(1,136,256/8);function Eh(t,e){const n=e||"hex",r=vh(Yr(t,{strict:!1})?Vb(t):t);return n==="bytes"?r:sa(r)}class xh extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const la=new xh(8192);function y2(t,e){if(la.has(`${t}.${e}`))return la.get(`${t}.${e}`);const n=e?`${e}${t.toLowerCase()}`:t.substring(2).toLowerCase(),r=Eh(ch(n),"bytes"),i=(e?n.substring(`${e}0x`.length):n).split("");for(let o=0;o<40;o+=2)r[o>>1]>>4>=8&&i[o]&&(i[o]=i[o].toUpperCase()),(r[o>>1]&15)>=8&&i[o+1]&&(i[o+1]=i[o+1].toUpperCase());const s=`0x${i.join("")}`;return la.set(`${t}.${e}`,s),s}function w2(t){const e=Eh(`0x${t.substring(4)}`).substring(26);return y2(`0x${e}`)}async function m2({hash:t,signature:e}){const n=Yr(t)?t:sa(t),{secp256k1:r}=await Promise.resolve().then(function(){return Mv});return`0x${(()=>{if(typeof e=="object"&&"r"in e&&"s"in e){const{r:u,s:l,v:h,yParity:f}=e,p=Number(f??h),d=_h(p);return new r.Signature(ia(u),ia(l)).addRecoveryBit(d)}const o=Yr(e)?e:sa(e);if(na(o)!==65)throw new Error("invalid signature length");const a=kb(`0x${o.slice(130)}`),c=_h(a);return r.Signature.fromCompact(o.substring(2,130)).addRecoveryBit(c)})().recoverPublicKey(n.substring(2)).toHex(!1)}`}function _h(t){if(t===0||t===1)return t;if(t===27)return 0;if(t===28)return 1;throw new Error("Invalid yParityOrV value")}async function b2({hash:t,signature:e}){return w2(await m2({hash:t,signature:e}))}function v2(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function E2(t,e,n){return t&e^~t&n}function x2(t,e,n){return t&e^t&n^e&n}class _2 extends ca{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=aa(this.buffer)}update(e){Ir(this),e=ws(e),Jn(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=aa(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ir(this),lh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Sr(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;v2(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=aa(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const gn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),I2=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),yn=new Uint32Array(64);class S2 extends _2{constructor(e=32){super(64,e,8,!1),this.A=gn[0]|0,this.B=gn[1]|0,this.C=gn[2]|0,this.D=gn[3]|0,this.E=gn[4]|0,this.F=gn[5]|0,this.G=gn[6]|0,this.H=gn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)yn[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=yn[h-15],p=yn[h-2],d=zt(f,7)^zt(f,18)^f>>>3,g=zt(p,17)^zt(p,19)^p>>>10;yn[h]=g+yn[h-7]+d+yn[h-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=zt(a,6)^zt(a,11)^zt(a,25),p=l+f+E2(a,c,u)+I2[h]+yn[h]|0,g=(zt(r,2)^zt(r,13)^zt(r,22))+x2(r,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+g|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){Sr(yn)}destroy(){this.set(0,0,0,0,0,0,0,0),Sr(this.buffer)}}const ms=fh(()=>new S2),A2="0.1.1";function D2(){return A2}class He extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof He){if(n.cause.details)return n.cause.details;if(n.cause.shortMessage)return n.cause.shortMessage}return n.cause&&"details"in n.cause&&typeof n.cause.details=="string"?n.cause.details:n.cause?.message?n.cause.message:n.details})(),i=n.cause instanceof He&&n.cause.docsPath||n.docsPath,o=`https://oxlib.sh${i??""}`,a=[e||"An error occurred.",...n.metaMessages?["",...n.metaMessages]:[],...r||i?["",r?`Details: ${r}`:void 0,i?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
16
|
+
`);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${D2()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Ih(this,e)}}function Ih(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Ih(t.cause,e):e?null:t}function O2(t,e){if(Dh(t)>e)throw new U2({givenSize:Dh(t),maxSize:e})}const en={zero:48,nine:57,A:65,F:70,a:97,f:102};function Sh(t){if(t>=en.zero&&t<=en.nine)return t-en.zero;if(t>=en.A&&t<=en.F)return t-(en.A-10);if(t>=en.a&&t<=en.f)return t-(en.a-10)}function $2(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new F2({size:t.length,targetSize:r,type:"Bytes"});const i=new Uint8Array(r);for(let s=0;s<r;s++){const o=n==="right";i[o?s:r-s-1]=t[o?s:t.length-s-1]}return i}function ha(t,e){if(da(t)>e)throw new V2({givenSize:da(t),maxSize:e})}function Ah(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;const i=t.replace("0x","");if(i.length>r*2)throw new K2({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const T2=new TextEncoder;function B2(t){return t instanceof Uint8Array?t:typeof t=="string"?C2(t):P2(t)}function P2(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function C2(t,e={}){const{size:n}=e;let r=t;n&&(ha(t,n),r=fa(t,n));let i=r.slice(2);i.length%2&&(i=`0${i}`);const s=i.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const u=Sh(i.charCodeAt(c++)),l=Sh(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new He(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function R2(t,e={}){const{size:n}=e,r=T2.encode(t);return typeof n=="number"?(O2(r,n),N2(r,n)):r}function N2(t,e){return $2(t,{dir:"right",size:e})}function Dh(t){return t.length}class U2 extends He{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class F2 extends He{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}const k2=new TextEncoder,L2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oh(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function M2(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(ha(n,e.size),bs(n,e.size)):n}function $h(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=L2[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(ha(r,e.size),fa(r,e.size)):r}function z2(t,e={}){const{signed:n,size:r}=e,i=BigInt(t);let s;r?n?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&n?-s-1n:0;if(s&&i>s||i<o){const u=typeof t=="bigint"?"n":"";throw new j2({max:s?`${s}${u}`:void 0,min:`${o}${u}`,signed:n,size:r,value:`${t}${u}`})}const c=`0x${(n&&i<0?(1n<<BigInt(r*8))+BigInt(i):i).toString(16)}`;return r?bs(c,r):c}function q2(t,e={}){return $h(k2.encode(t),e)}function bs(t,e){return Ah(t,{dir:"left",size:e})}function fa(t,e){return Ah(t,{dir:"right",size:e})}function da(t){return Math.ceil((t.length-2)/2)}class j2 extends He{constructor({max:e,min:n,signed:r,size:i,value:s}){super(`Number \`${s}\` is not in safe${i?` ${i*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${n}\` to \`${e}\`)`:`(above \`${n}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class V2 extends He{constructor({givenSize:e,maxSize:n}){super(`Size cannot exceed \`${n}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}}class K2 extends He{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}new xh(128),oa(0,{size:32});function H2(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=vh(B2(t));return n==="Bytes"?r:$h(r)}class W2 extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const n=super.get(e);return super.has(e)&&n!==void 0&&(this.delete(e),super.set(e,n)),n}set(e,n){if(super.set(e,n),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const pa={checksum:new W2(8192)}.checksum,G2=/^0x[a-fA-F0-9]{40}$/;function Th(t,e={}){const{strict:n=!0}=e;if(!G2.test(t))throw new Bh({address:t,cause:new Z2});if(n){if(t.toLowerCase()===t)return;if(Y2(t)!==t)throw new Bh({address:t,cause:new J2})}}function Y2(t){if(pa.has(t))return pa.get(t);Th(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=H2(R2(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)n[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(n[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const i=`0x${r.join("")}`;return pa.set(t,i),i}class Bh extends He{constructor({address:e,cause:n}){super(`Address "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Z2 extends He{constructor(){super("Address is not a 20 byte (40 hexadecimal character) value."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidInputError"})}}class J2 extends He{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const X2=/^(.*)\[([0-9]*)\]$/,Q2=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,ev=/^(u?int)(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;function ga(t,e){if(t.length!==e.length)throw new nv({expectedLength:t.length,givenLength:e.length});const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r];n.push(ga.encode(i,s))}return Oh(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return Th(c),bs(c.toLowerCase(),i?32:0)}if(n==="string")return q2(r);if(n==="bytes")return r;if(n==="bool")return bs(M2(r),i?32:1);const s=n.match(ev);if(s){const[c,u,l="256"]=s,h=Number.parseInt(l)/8;return z2(r,{size:i?32:h,signed:u==="int"})}const o=n.match(Q2);if(o){const[c,u]=o;if(Number.parseInt(u)!==(r.length-2)/2)throw new tv({expectedSize:Number.parseInt(u),value:r});return fa(r,i?32:0)}const a=n.match(X2);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let h=0;h<r.length;h++)l.push(e(u,r[h],!0));return l.length===0?"0x":Oh(...l)}throw new rv(n)}t.encode=e})(ga||(ga={}));class tv extends He{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${da(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class nv extends He{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
|
|
17
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class rv extends He{constructor(e){super(`Type \`${e}\` is not a valid ABI Type.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.InvalidTypeError"})}}class Ph extends ca{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,e2(e);const r=ws(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Sr(s)}update(e){return Ir(this),this.iHash.update(e),this}digestInto(e){Ir(this),Jn(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ch=(t,e,n)=>new Ph(t,e).update(n).digest();Ch.create=(t,e)=>new Ph(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ya=BigInt(0),wa=BigInt(1);function Xr(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function wn(t){if(!Xr(t))throw new Error("Uint8Array expected")}function Qr(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function vs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Rh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?ya:BigInt("0x"+t)}const Nh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",iv=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ei(t){if(wn(t),Nh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=iv[t[n]];return e}const tn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Uh(t){if(t>=tn._0&&t<=tn._9)return t-tn._0;if(t>=tn.A&&t<=tn.F)return t-(tn.A-10);if(t>=tn.a&&t<=tn.f)return t-(tn.a-10)}function Es(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Nh)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Uh(t.charCodeAt(s)),a=Uh(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function qt(t){return Rh(ei(t))}function Fh(t){return wn(t),Rh(ei(Uint8Array.from(t).reverse()))}function Xn(t,e){return Es(t.toString(16).padStart(e*2,"0"))}function kh(t,e){return Xn(t,e).reverse()}function $e(t,e,n){let r;if(typeof e=="string")try{r=Es(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Xr(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}function yt(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];wn(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}function ma(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const ba=t=>typeof t=="bigint"&&ya<=t;function ti(t,e,n){return ba(t)&&ba(e)&&ba(n)&&e<=t&&t<n}function Qn(t,e,n,r){if(!ti(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function sv(t){let e;for(e=0;t>ya;t>>=wa,e+=1);return e}const xs=t=>(wa<<BigInt(t))-wa,va=t=>new Uint8Array(t),Lh=t=>Uint8Array.from(t);function ov(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");let r=va(t),i=va(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...h)=>n(i,r,...h),c=(h=va(0))=>{i=a(Lh([0]),h),r=a(),h.length!==0&&(i=a(Lh([1]),h),r=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){r=a();const p=r.slice();f.push(p),h+=r.length}return yt(...f)};return(h,f)=>{o(),c(h);let p;for(;!(p=f(u()));)c();return o(),p}}const av={bigint:t=>typeof t=="bigint",function:t=>typeof t=="function",boolean:t=>typeof t=="boolean",string:t=>typeof t=="string",stringOrUint8Array:t=>typeof t=="string"||Xr(t),isSafeInteger:t=>Number.isSafeInteger(t),array:t=>Array.isArray(t),field:(t,e)=>e.Fp.isValid(t),hash:t=>typeof t=="function"&&Number.isSafeInteger(t.outputLen)};function ni(t,e,n={}){const r=(i,s,o)=>{const a=av[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[i];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(i)+" is invalid. Expected "+s+", got "+c)};for(const[i,s]of Object.entries(e))r(i,s,!1);for(const[i,s]of Object.entries(n))r(i,s,!0);return t}function Mh(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const Qe=BigInt(0),We=BigInt(1),er=BigInt(2),cv=BigInt(3),zh=BigInt(4),qh=BigInt(5),jh=BigInt(8);function Ae(t,e){const n=t%e;return n>=Qe?n:e+n}function wt(t,e,n){let r=t;for(;e-- >Qe;)r*=r,r%=n;return r}function Ea(t,e){if(t===Qe)throw new Error("invert: expected non-zero number");if(e<=Qe)throw new Error("invert: expected positive modulus, got "+e);let n=Ae(t,e),r=e,i=Qe,s=We;for(;n!==Qe;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==We)throw new Error("invert: does not exist");return Ae(i,e)}function Vh(t,e){const n=(t.ORDER+We)/zh,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function uv(t,e){const n=(t.ORDER-qh)/jh,r=t.mul(e,er),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,er),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function lv(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-We,n=0;for(;e%er===Qe;)e/=er,n++;let r=er;const i=xa(t);for(;Hh(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Vh;let s=i.pow(r,e);const o=(e+We)/er;return function(c,u){if(c.is0(u))return u;if(Hh(c,u)!==1)throw new Error("Cannot find square root");let l=n,h=c.mul(c.ONE,s),f=c.pow(u,e),p=c.pow(u,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let d=1,g=c.sqr(f);for(;!c.eql(g,c.ONE);)if(d++,g=c.sqr(g),d===l)throw new Error("Cannot find square root");const y=We<<BigInt(l-d-1),_=c.pow(h,y);l=d,h=c.sqr(_),f=c.mul(f,h),p=c.mul(p,_)}return p}}function hv(t){return t%zh===cv?Vh:t%jh===qh?uv:lv(t)}const fv=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Kh(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=fv.reduce((r,i)=>(r[i]="function",r),e);return ni(t,n)}function dv(t,e,n){if(n<Qe)throw new Error("invalid exponent, negatives unsupported");if(n===Qe)return t.ONE;if(n===We)return e;let r=t.ONE,i=e;for(;n>Qe;)n&We&&(r=t.mul(r,i)),i=t.sqr(i),n>>=We;return r}function _s(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Hh(t,e){const n=(t.ORDER-We)/er,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function Wh(t,e){e!==void 0&&Zr(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function xa(t,e,n=!1,r={}){if(t<=Qe)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Wh(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:n,BITS:i,BYTES:s,MASK:xs(i),ZERO:Qe,ONE:We,create:c=>Ae(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Qe<=c&&c<t},is0:c=>c===Qe,isOdd:c=>(c&We)===We,neg:c=>Ae(-c,t),eql:(c,u)=>c===u,sqr:c=>Ae(c*c,t),add:(c,u)=>Ae(c+u,t),sub:(c,u)=>Ae(c-u,t),mul:(c,u)=>Ae(c*u,t),pow:(c,u)=>dv(a,c,u),div:(c,u)=>Ae(c*Ea(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ea(c,t),sqrt:r.sqrt||(c=>(o||(o=hv(t)),o(a,c))),toBytes:c=>n?kh(c,s):Xn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?Fh(c):qt(c)},invertBatch:c=>_s(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function Gh(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function Yh(t){const e=Gh(t);return e+Math.ceil(e/2)}function pv(t,e,n=!1){const r=t.length,i=Gh(e),s=Yh(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Fh(t):qt(t),a=Ae(o,e-We)+We;return n?kh(a,i):Xn(a,i)}const Zh=BigInt(0),_a=BigInt(1);function Ia(t,e){const n=e.negate();return t?n:e}function Jh(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Sa(t,e){Jh(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=xs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Xh(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=_a);const u=e*r,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function gv(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function yv(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const Aa=new WeakMap,Qh=new WeakMap;function Da(t){return Qh.get(t)||1}function wv(t,e){return{constTimeNegate:Ia,hasPrecomputes(n){return Da(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Zh;)r&_a&&(i=i.add(s)),s=s.double(),r>>=_a;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Sa(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){let s=t.ZERO,o=t.BASE;const a=Sa(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=Xh(i,c,a);i=u,h?o=o.add(Ia(p,r[d])):s=s.add(Ia(f,r[l]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=Sa(n,e);for(let a=0;a<o.windows&&i!==Zh;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=Xh(i,a,o);if(i=c,!l){const f=r[u];s=s.add(h?f.negate():f)}}return s},getPrecomputes(n,r,i){let s=Aa.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&Aa.set(r,i(s))),s},wNAFCached(n,r,i){const s=Da(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Da(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Jh(r,e),Qh.set(n,r),Aa.delete(n)}}}function mv(t,e,n,r){gv(n,t),yv(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=sv(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=xs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(n[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),d=d.add(y);if(f=f.add(d),p!==0)for(let g=0;g<c;g++)f=f.double()}return f}function ef(t){return Kh(t.Fp),ni(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Wh(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function tf(t){t.lowS!==void 0&&Qr("lowS",t.lowS),t.prehash!==void 0&&Qr("prehash",t.prehash)}function bv(t){const e=ef(t);ni(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:n,Fp:r,a:i}=e;if(n){if(!r.eql(i,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof n!="object"||typeof n.beta!="bigint"||typeof n.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class vv extends Error{constructor(e=""){super(e)}}const nn={Err:vv,_tlv:{encode:(t,e)=>{const{Err:n}=nn;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=vs(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?vs(i.length/2|128):"";return vs(t)+s+i+e},decode(t,e){const{Err:n}=nn;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=nn;if(t<Bt)throw new e("integer: negative integers are not allowed");let n=vs(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=nn;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return qt(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=nn,i=$e("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=nn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}};function Oa(t,e){return ei(Xn(t,e))}const Bt=BigInt(0),oe=BigInt(1),mn=BigInt(2),ri=BigInt(3),$a=BigInt(4);function Ev(t){const e=bv(t),{Fp:n}=e,r=xa(e.n,e.nBitLength),i=e.toBytes||((b,v,x)=>{const T=v.toAffine();return yt(Uint8Array.from([4]),n.toBytes(T.x),n.toBytes(T.y))}),s=e.fromBytes||(b=>{const v=b.subarray(1),x=n.fromBytes(v.subarray(0,n.BYTES)),T=n.fromBytes(v.subarray(n.BYTES,2*n.BYTES));return{x,y:T}});function o(b){const{a:v,b:x}=e,T=n.sqr(b),R=n.mul(T,b);return n.add(n.add(R,n.mul(b,v)),x)}function a(b,v){const x=n.sqr(v),T=o(b);return n.eql(x,T)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,ri),$a),u=n.mul(n.sqr(e.b),BigInt(27));if(n.is0(n.add(c,u)))throw new Error("bad curve params: a or b");function l(b){return ti(b,oe,e.n)}function h(b){const{allowedPrivateKeyLengths:v,nByteLength:x,wrapPrivateKey:T,n:R}=e;if(v&&typeof b!="bigint"){if(Xr(b)&&(b=ei(b)),typeof b!="string"||!v.includes(b.length))throw new Error("invalid private key");b=b.padStart(x*2,"0")}let C;try{C=typeof b=="bigint"?b:qt($e("private key",b,x))}catch{throw new Error("invalid private key, expected hex or "+x+" bytes, got "+typeof b)}return T&&(C=Ae(C,R)),Qn("private key",C,oe,R),C}function f(b){if(!(b instanceof g))throw new Error("ProjectivePoint expected")}const p=Mh((b,v)=>{const{px:x,py:T,pz:R}=b;if(n.eql(R,n.ONE))return{x,y:T};const C=b.is0();v==null&&(v=C?n.ONE:n.inv(R));const m=n.mul(x,v),B=n.mul(T,v),S=n.mul(R,v);if(C)return{x:n.ZERO,y:n.ZERO};if(!n.eql(S,n.ONE))throw new Error("invZ was invalid");return{x:m,y:B}}),d=Mh(b=>{if(b.is0()){if(e.allowInfinityPoint&&!n.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:v,y:x}=b.toAffine();if(!n.isValid(v)||!n.isValid(x))throw new Error("bad point: x or y not FE");if(!a(v,x))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,x,T){if(v==null||!n.isValid(v))throw new Error("x required");if(x==null||!n.isValid(x)||n.is0(x))throw new Error("y required");if(T==null||!n.isValid(T))throw new Error("z required");this.px=v,this.py=x,this.pz=T,Object.freeze(this)}static fromAffine(v){const{x,y:T}=v||{};if(!v||!n.isValid(x)||!n.isValid(T))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const R=C=>n.eql(C,n.ZERO);return R(x)&&R(T)?g.ZERO:new g(x,T,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const x=_s(n,v.map(T=>T.pz));return v.map((T,R)=>T.toAffine(x[R])).map(g.fromAffine)}static fromHex(v){const x=g.fromAffine(s($e("pointHex",v)));return x.assertValidity(),x}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,x){return mv(g,r,v,x)}_setWindowSize(v){A.setWindowSize(this,v)}assertValidity(){d(this)}hasEvenY(){const{y:v}=this.toAffine();if(n.isOdd)return!n.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:x,py:T,pz:R}=this,{px:C,py:m,pz:B}=v,S=n.eql(n.mul(x,B),n.mul(C,R)),O=n.eql(n.mul(T,B),n.mul(m,R));return S&&O}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:v,b:x}=e,T=n.mul(x,ri),{px:R,py:C,pz:m}=this;let B=n.ZERO,S=n.ZERO,O=n.ZERO,P=n.mul(R,R),F=n.mul(C,C),E=n.mul(m,m),w=n.mul(R,C);return w=n.add(w,w),O=n.mul(R,m),O=n.add(O,O),B=n.mul(v,O),S=n.mul(T,E),S=n.add(B,S),B=n.sub(F,S),S=n.add(F,S),S=n.mul(B,S),B=n.mul(w,B),O=n.mul(T,O),E=n.mul(v,E),w=n.sub(P,E),w=n.mul(v,w),w=n.add(w,O),O=n.add(P,P),P=n.add(O,P),P=n.add(P,E),P=n.mul(P,w),S=n.add(S,P),E=n.mul(C,m),E=n.add(E,E),P=n.mul(E,w),B=n.sub(B,P),O=n.mul(E,F),O=n.add(O,O),O=n.add(O,O),new g(B,S,O)}add(v){f(v);const{px:x,py:T,pz:R}=this,{px:C,py:m,pz:B}=v;let S=n.ZERO,O=n.ZERO,P=n.ZERO;const F=e.a,E=n.mul(e.b,ri);let w=n.mul(x,C),I=n.mul(T,m),$=n.mul(R,B),D=n.add(x,T),N=n.add(C,m);D=n.mul(D,N),N=n.add(w,I),D=n.sub(D,N),N=n.add(x,R);let U=n.add(C,B);return N=n.mul(N,U),U=n.add(w,$),N=n.sub(N,U),U=n.add(T,R),S=n.add(m,B),U=n.mul(U,S),S=n.add(I,$),U=n.sub(U,S),P=n.mul(F,N),S=n.mul(E,$),P=n.add(S,P),S=n.sub(I,P),P=n.add(I,P),O=n.mul(S,P),I=n.add(w,w),I=n.add(I,w),$=n.mul(F,$),N=n.mul(E,N),I=n.add(I,$),$=n.sub(w,$),$=n.mul(F,$),N=n.add(N,$),w=n.mul(I,N),O=n.add(O,w),w=n.mul(U,N),S=n.mul(D,S),S=n.sub(S,w),w=n.mul(D,I),P=n.mul(U,P),P=n.add(P,w),new g(S,O,P)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return A.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:x,n:T}=e;Qn("scalar",v,Bt,T);const R=g.ZERO;if(v===Bt)return R;if(this.is0()||v===oe)return this;if(!x||A.hasPrecomputes(this))return A.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:C,k1:m,k2neg:B,k2:S}=x.splitScalar(v),O=R,P=R,F=this;for(;m>Bt||S>Bt;)m&oe&&(O=O.add(F)),S&oe&&(P=P.add(F)),F=F.double(),m>>=oe,S>>=oe;return C&&(O=O.negate()),B&&(P=P.negate()),P=new g(n.mul(P.px,x.beta),P.py,P.pz),O.add(P)}multiply(v){const{endo:x,n:T}=e;Qn("scalar",v,oe,T);let R,C;if(x){const{k1neg:m,k1:B,k2neg:S,k2:O}=x.splitScalar(v);let{p:P,f:F}=this.wNAF(B),{p:E,f:w}=this.wNAF(O);P=A.constTimeNegate(m,P),E=A.constTimeNegate(S,E),E=new g(n.mul(E.px,x.beta),E.py,E.pz),R=P.add(E),C=F.add(w)}else{const{p:m,f:B}=this.wNAF(v);R=m,C=B}return g.normalizeZ([R,C])[0]}multiplyAndAddUnsafe(v,x,T){const R=g.BASE,C=(B,S)=>S===Bt||S===oe||!B.equals(R)?B.multiplyUnsafe(S):B.multiply(S),m=C(this,x).add(C(v,T));return m.is0()?void 0:m}toAffine(v){return p(this,v)}isTorsionFree(){const{h:v,isTorsionFree:x}=e;if(v===oe)return!0;if(x)return x(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:x}=e;return v===oe?this:x?x(g,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return Qr("isCompressed",v),this.assertValidity(),i(g,this,v)}toHex(v=!0){return Qr("isCompressed",v),ei(this.toRawBytes(v))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:y,nBitLength:_}=e,A=wv(g,y?Math.ceil(_/2):_);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:l}}function xv(t){const e=ef(t);return ni(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function _v(t){const e=xv(t),{Fp:n,n:r,nByteLength:i,nBitLength:s}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(E){return Ae(E,r)}function u(E){return Ea(E,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:p}=Ev({...e,toBytes(E,w,I){const $=w.toAffine(),D=n.toBytes($.x),N=yt;return Qr("isCompressed",I),I?N(Uint8Array.from([w.hasEvenY()?2:3]),D):N(Uint8Array.from([4]),D,n.toBytes($.y))},fromBytes(E){const w=E.length,I=E[0],$=E.subarray(1);if(w===o&&(I===2||I===3)){const D=qt($);if(!ti(D,oe,n.ORDER))throw new Error("Point is not on curve");const N=f(D);let U;try{U=n.sqrt(N)}catch(V){const K=V instanceof Error?": "+V.message:"";throw new Error("Point is not on curve"+K)}const L=(U&oe)===oe;return(I&1)===1!==L&&(U=n.neg(U)),{x:D,y:U}}else if(w===a&&I===4){const D=n.fromBytes($.subarray(0,n.BYTES)),N=n.fromBytes($.subarray(n.BYTES,2*n.BYTES));return{x:D,y:N}}else{const D=o,N=a;throw new Error("invalid Point, expected length of "+D+", or uncompressed "+N+", got "+w)}}});function d(E){const w=r>>oe;return E>w}function g(E){return d(E)?c(-E):E}const y=(E,w,I)=>qt(E.slice(w,I));class _{constructor(w,I,$){Qn("r",w,oe,r),Qn("s",I,oe,r),this.r=w,this.s=I,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(w){const I=i;return w=$e("compactSignature",w,I*2),new _(y(w,0,I),y(w,I,2*I))}static fromDER(w){const{r:I,s:$}=nn.toSig($e("DER",w));return new _(I,$)}assertValidity(){}addRecoveryBit(w){return new _(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:$,recovery:D}=this,N=R($e("msgHash",w));if(D==null||![0,1,2,3].includes(D))throw new Error("recovery id invalid");const U=D===2||D===3?I+e.n:I;if(U>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(D&1)===0?"02":"03",j=l.fromHex(L+Oa(U,n.BYTES)),V=u(U),K=c(-N*V),H=c($*V),Z=l.BASE.multiplyAndAddUnsafe(j,K,H);if(!Z)throw new Error("point at infinify");return Z.assertValidity(),Z}hasHighS(){return d(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return Es(this.toDERHex())}toDERHex(){return nn.hexFromSig(this)}toCompactRawBytes(){return Es(this.toCompactHex())}toCompactHex(){const w=i;return Oa(this.r,w)+Oa(this.s,w)}}const A={isValidPrivateKey(E){try{return h(E),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const E=Yh(e.n);return pv(e.randomBytes(E),e.n)},precompute(E=8,w=l.BASE){return w._setWindowSize(E),w.multiply(BigInt(3)),w}};function b(E,w=!0){return l.fromPrivateKey(E).toRawBytes(w)}function v(E){if(typeof E=="bigint")return!1;if(E instanceof l)return!0;const I=$e("key",E).length,$=n.BYTES,D=$+1,N=2*$+1;if(!(e.allowedPrivateKeyLengths||i===D))return I===D||I===N}function x(E,w,I=!0){if(v(E)===!0)throw new Error("first arg must be private key");if(v(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(h(E)).toRawBytes(I)}const T=e.bits2int||function(E){if(E.length>8192)throw new Error("input is too large");const w=qt(E),I=E.length*8-s;return I>0?w>>BigInt(I):w},R=e.bits2int_modN||function(E){return c(T(E))},C=xs(s);function m(E){return Qn("num < 2^"+s,E,Bt,C),Xn(E,i)}function B(E,w,I=S){if(["recovered","canonical"].some(W=>W in I))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:D}=e;let{lowS:N,prehash:U,extraEntropy:L}=I;N==null&&(N=!0),E=$e("msgHash",E),tf(I),U&&(E=$e("prehashed msgHash",$(E)));const j=R(E),V=h(w),K=[m(V),m(j)];if(L!=null&&L!==!1){const W=L===!0?D(n.BYTES):L;K.push($e("extraEntropy",W))}const H=yt(...K),Z=j;function Q(W){const ae=T(W);if(!p(ae))return;const ye=u(ae),gt=l.BASE.multiply(ae).toAffine(),Ot=c(gt.x);if(Ot===Bt)return;const $t=c(ye*c(Z+Ot*V));if($t===Bt)return;let Zt=(gt.x===Ot?0:2)|Number(gt.y&oe),go=$t;return N&&d($t)&&(go=g($t),Zt^=1),new _(Ot,go,Zt)}return{seed:H,k2sig:Q}}const S={lowS:e.lowS,prehash:!1},O={lowS:e.lowS,prehash:!1};function P(E,w,I=S){const{seed:$,k2sig:D}=B(E,w,I),N=e;return ov(N.hash.outputLen,N.nByteLength,N.hmac)($,D)}l.BASE._setWindowSize(8);function F(E,w,I,$=O){const D=E;w=$e("msgHash",w),I=$e("publicKey",I);const{lowS:N,prehash:U,format:L}=$;if(tf($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(L!==void 0&&L!=="compact"&&L!=="der")throw new Error("format must be compact or der");const j=typeof D=="string"||Xr(D),V=!j&&!L&&typeof D=="object"&&D!==null&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!j&&!V)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let K,H;try{if(V&&(K=new _(D.r,D.s)),j){try{L!=="compact"&&(K=_.fromDER(D))}catch(Zt){if(!(Zt instanceof nn.Err))throw Zt}!K&&L!=="der"&&(K=_.fromCompact(D))}H=l.fromHex(I)}catch{return!1}if(!K||N&&K.hasHighS())return!1;U&&(w=e.hash(w));const{r:Z,s:Q}=K,W=R(w),ae=u(Q),ye=c(W*ae),gt=c(Z*ae),Ot=l.BASE.multiplyAndAddUnsafe(H,ye,gt)?.toAffine();return Ot?c(Ot.x)===Z:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:x,sign:P,verify:F,ProjectivePoint:l,Signature:_,utils:A}}function Iv(t,e){const n=t.ORDER;let r=Bt;for(let d=n-oe;d%mn===Bt;d/=mn)r+=oe;const i=r,s=mn<<i-oe-oe,o=s*mn,a=(n-oe)/o,c=(a-oe)/mn,u=o-oe,l=s,h=t.pow(e,a),f=t.pow(e,(a+oe)/mn);let p=(d,g)=>{let y=h,_=t.pow(g,u),A=t.sqr(_);A=t.mul(A,g);let b=t.mul(d,A);b=t.pow(b,c),b=t.mul(b,_),_=t.mul(b,g),A=t.mul(b,d);let v=t.mul(A,_);b=t.pow(v,l);let x=t.eql(b,t.ONE);_=t.mul(A,f),b=t.mul(v,y),A=t.cmov(_,A,x),v=t.cmov(b,v,x);for(let T=i;T>oe;T--){let R=T-mn;R=mn<<R-oe;let C=t.pow(v,R);const m=t.eql(C,t.ONE);_=t.mul(A,y),y=t.mul(y,y),C=t.mul(v,y),A=t.cmov(_,A,m),v=t.cmov(C,v,m)}return{isValid:x,value:A}};if(t.ORDER%$a===ri){const d=(t.ORDER-ri)/$a,g=t.sqrt(t.neg(e));p=(y,_)=>{let A=t.sqr(_);const b=t.mul(y,_);A=t.mul(A,b);let v=t.pow(A,d);v=t.mul(v,b);const x=t.mul(v,g),T=t.mul(t.sqr(v),_),R=t.eql(T,y);let C=t.cmov(x,v,R);return{isValid:R,value:C}}}return p}function Sv(t,e){if(Kh(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=Iv(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,u,l,h;i=t.sqr(r),i=t.mul(i,e.Z),s=t.sqr(i),s=t.add(s,i),o=t.add(s,t.ONE),o=t.mul(o,e.B),a=t.cmov(e.Z,t.neg(s),!t.eql(s,t.ZERO)),a=t.mul(a,e.A),s=t.sqr(o),u=t.sqr(a),c=t.mul(u,e.A),s=t.add(s,c),s=t.mul(s,o),u=t.mul(u,a),c=t.mul(u,e.B),s=t.add(s,c),l=t.mul(i,o);const{isValid:f,value:p}=n(s,u);h=t.mul(i,r),h=t.mul(h,p),l=t.cmov(l,o,f),h=t.cmov(h,p,f);const d=t.isOdd(r)===t.isOdd(h);h=t.cmov(t.neg(h),h,d);const g=_s(t,[a],!0)[0];return l=t.mul(l,g),{x:l,y:h}}}function Av(t){return{hash:t,hmac:(e,...n)=>Ch(t,e,o2(...n)),randomBytes:dh}}function Dv(t,e){const n=r=>_v({...t,...Av(r)});return{...n(e),create:n}}const Ov=qt;function bn(t,e){if(ii(t),ii(e),t<0||t>=1<<8*e)throw new Error("invalid I2OSP input: "+t);const n=Array.from({length:e}).fill(0);for(let r=e-1;r>=0;r--)n[r]=t&255,t>>>=8;return new Uint8Array(n)}function $v(t,e){const n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t[r]^e[r];return n}function ii(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function Tv(t,e,n,r){wn(t),wn(e),ii(n),e.length>255&&(e=r(yt(ma("H2C-OVERSIZE-DST-"),e)));const{outputLen:i,blockLen:s}=r,o=Math.ceil(n/i);if(n>65535||o>255)throw new Error("expand_message_xmd: invalid lenInBytes");const a=yt(e,bn(e.length,1)),c=bn(0,s),u=bn(n,2),l=new Array(o),h=r(yt(c,t,u,bn(0,1),a));l[0]=r(yt(h,bn(1,1),a));for(let p=1;p<=o;p++){const d=[$v(h,l[p-1]),bn(p+1,1),a];l[p]=r(yt(...d))}return yt(...l).slice(0,n)}function Bv(t,e,n,r,i){if(wn(t),wn(e),ii(n),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(ma("H2C-OVERSIZE-DST-")).update(e).digest()}if(n>65535||e.length>255)throw new Error("expand_message_xof: invalid lenInBytes");return i.create({dkLen:n}).update(t).update(bn(n,2)).update(e).update(bn(e.length,1)).digest()}function nf(t,e,n){ni(n,{DST:"stringOrUint8Array",p:"bigint",m:"isSafeInteger",k:"isSafeInteger",hash:"hash"});const{p:r,k:i,m:s,hash:o,expand:a,DST:c}=n;wn(t),ii(e);const u=typeof c=="string"?ma(c):c,l=r.toString(2).length,h=Math.ceil((l+i)/8),f=e*s*h;let p;if(a==="xmd")p=Tv(t,u,f,o);else if(a==="xof")p=Bv(t,u,f,i,o);else if(a==="_internal_pass")p=t;else throw new Error('expand must be "xmd" or "xof"');const d=new Array(e);for(let g=0;g<e;g++){const y=new Array(s);for(let _=0;_<s;_++){const A=h*(_+g*s),b=p.subarray(A,A+h);y[_]=Ae(Ov(b),r)}d[g]=y}return d}function Pv(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(h=>h.reduce((f,p)=>t.add(t.mul(f,r),p))),[u,l]=_s(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}function Cv(t,e,n){if(typeof e!="function")throw new Error("mapToCurve() must be defined");function r(s){return t.fromAffine(e(s))}function i(s){const o=s.clearCofactor();return o.equals(t.ZERO)?t.ZERO:(o.assertValidity(),o)}return{defaults:n,hashToCurve(s,o){const a=nf(s,2,{...n,DST:n.DST,...o}),c=r(a[0]),u=r(a[1]);return i(c.add(u))},encodeToCurve(s,o){const a=nf(s,1,{...n,DST:n.encodeDST,...o});return i(r(a[0]))},mapToCurve(s){if(!Array.isArray(s))throw new Error("expected array of bigints");for(const o of s)if(typeof o!="bigint")throw new Error("expected array of bigints");return i(r(s))}}}const si=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Is=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ta=BigInt(0),oi=BigInt(1),Ss=BigInt(2),rf=(t,e)=>(t+e/Ss)/e;function sf(t){const e=si,n=BigInt(3),r=BigInt(6),i=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),u=t*t*t%e,l=u*u*t%e,h=wt(l,n,e)*l%e,f=wt(h,n,e)*l%e,p=wt(f,Ss,e)*u%e,d=wt(p,i,e)*p%e,g=wt(d,s,e)*d%e,y=wt(g,a,e)*g%e,_=wt(y,c,e)*y%e,A=wt(_,a,e)*g%e,b=wt(A,n,e)*l%e,v=wt(b,o,e)*d%e,x=wt(v,r,e)*u%e,T=wt(x,Ss,e);if(!vn.eql(vn.sqr(T),t))throw new Error("Cannot find square root");return T}const vn=xa(si,void 0,void 0,{sqrt:sf}),ai=Dv({a:Ta,b:BigInt(7),Fp:vn,n:Is,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Is,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-oi*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=rf(s*t,e),c=rf(-r*t,e);let u=Ae(t-a*n-c*i,e),l=Ae(-a*r-c*s,e);const h=u>o,f=l>o;if(h&&(u=e-u),f&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}}},ms),of={};function As(t,...e){let n=of[t];if(n===void 0){const r=ms(Uint8Array.from(t,i=>i.charCodeAt(0)));n=yt(r,r),of[t]=n}return ms(yt(n,...e))}const Ba=t=>t.toRawBytes(!0).slice(1),Pa=t=>Xn(t,32),Ca=t=>Ae(t,si),ci=t=>Ae(t,Is),Ra=ai.ProjectivePoint,Rv=(t,e,n)=>Ra.BASE.multiplyAndAddUnsafe(t,e,n);function Na(t){let e=ai.utils.normPrivateKeyToScalar(t),n=Ra.fromPrivateKey(e);return{scalar:n.hasEvenY()?e:ci(-e),bytes:Ba(n)}}function af(t){Qn("x",t,oi,si);const e=Ca(t*t),n=Ca(e*t+BigInt(7));let r=sf(n);r%Ss!==Ta&&(r=Ca(-r));const i=new Ra(t,r,oi);return i.assertValidity(),i}const Ar=qt;function cf(...t){return ci(Ar(As("BIP0340/challenge",...t)))}function Nv(t){return Na(t).bytes}function Uv(t,e,n=dh(32)){const r=$e("message",t),{bytes:i,scalar:s}=Na(e),o=$e("auxRand",n,32),a=Pa(s^Ar(As("BIP0340/aux",o))),c=As("BIP0340/nonce",a,i,r),u=ci(Ar(c));if(u===Ta)throw new Error("sign failed: k is zero");const{bytes:l,scalar:h}=Na(u),f=cf(l,i,r),p=new Uint8Array(64);if(p.set(l,0),p.set(Pa(ci(h+f*s)),32),!uf(p,r,i))throw new Error("sign: Invalid signature produced");return p}function uf(t,e,n){const r=$e("signature",t,64),i=$e("message",e),s=$e("publicKey",n,32);try{const o=af(Ar(s)),a=Ar(r.subarray(0,32));if(!ti(a,oi,si))return!1;const c=Ar(r.subarray(32,64));if(!ti(c,oi,Is))return!1;const u=cf(Pa(a),Ba(o),i),l=Rv(o,c,ci(-u));return!(!l||!l.hasEvenY()||l.toAffine().x!==a)}catch{return!1}}const Fv={getPublicKey:Nv,sign:Uv,verify:uf,utils:{randomPrivateKey:ai.utils.randomPrivateKey,lift_x:af,pointToBytes:Ba,numberToBytesBE:Xn,bytesToNumberBE:qt,taggedHash:As,mod:Ae}},kv=Pv(vn,[["0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7","0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581","0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262","0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c"],["0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b","0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14","0x0000000000000000000000000000000000000000000000000000000000000001"],["0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c","0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3","0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931","0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84"],["0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b","0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573","0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f","0x0000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),Lv=Sv(vn,{A:BigInt("0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533"),B:BigInt("1771"),Z:vn.create(BigInt("-11"))}),Ua=Cv(ai.ProjectivePoint,t=>{const{x:e,y:n}=Lv(vn.create(t[0]));return kv(e,n)},{DST:"secp256k1_XMD:SHA-256_SSWU_RO_",encodeDST:"secp256k1_XMD:SHA-256_SSWU_NU_",p:vn.ORDER,m:1,k:128,expand:"xmd",hash:ms});var Mv=Object.freeze({__proto__:null,secp256k1:ai,schnorr:Fv,secp256k1_hasher:Ua,hashToCurve:Ua.hashToCurve,encodeToCurve:Ua.encodeToCurve});function zv(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let u=0;u<e.length;u++)e[u]=255;for(let u=0;u<t.length;u++){const l=t.charAt(u),h=l.charCodeAt(0);if(e[h]!==255)throw new TypeError(l+" is ambiguous");e[h]=u}const n=t.length,r=t.charAt(0),i=Math.log(n)/Math.log(256),s=Math.log(256)/Math.log(n);function o(u){if(u instanceof Uint8Array||(ArrayBuffer.isView(u)?u=new Uint8Array(u.buffer,u.byteOffset,u.byteLength):Array.isArray(u)&&(u=Uint8Array.from(u))),!(u instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(u.length===0)return"";let l=0,h=0,f=0;const p=u.length;for(;f!==p&&u[f]===0;)f++,l++;const d=(p-f)*s+1>>>0,g=new Uint8Array(d);for(;f!==p;){let A=u[f],b=0;for(let v=d-1;(A!==0||b<h)&&v!==-1;v--,b++)A+=256*g[v]>>>0,g[v]=A%n>>>0,A=A/n>>>0;if(A!==0)throw new Error("Non-zero carry");h=b,f++}let y=d-h;for(;y!==d&&g[y]===0;)y++;let _=r.repeat(l);for(;y<d;++y)_+=t.charAt(g[y]);return _}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,h=0,f=0;for(;u[l]===r;)h++,l++;const p=(u.length-l)*i+1>>>0,d=new Uint8Array(p);for(;l<u.length;){const A=u.charCodeAt(l);if(A>255)return;let b=e[A];if(b===255)return;let v=0;for(let x=p-1;(b!==0||v<f)&&x!==-1;x--,v++)b+=n*d[x]>>>0,d[x]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=v,l++}let g=p-f;for(;g!==p&&d[g]===0;)g++;const y=new Uint8Array(h+(p-g));let _=h;for(;g!==p;)y[_++]=d[g++];return y}function c(u){const l=a(u);if(l)return l;throw new Error("Non-base"+n+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var qv="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ui=zv(qv);function jv(t){const e=t.length;let n=0,r=0;for(;r<e;){let i=t.charCodeAt(r++);if((i&4294967168)===0){n++;continue}else if((i&4294965248)===0)n+=2;else{if(i>=55296&&i<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,i=((i&1023)<<10)+(s&1023)+65536)}(i&4294901760)===0?n+=3:n+=4}}return n}function Vv(t,e,n){const r=t.length;let i=n,s=0;for(;s<r;){let o=t.charCodeAt(s++);if((o&4294967168)===0){e[i++]=o;continue}else if((o&4294965248)===0)e[i++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[i++]=o>>12&15|224,e[i++]=o>>6&63|128):(e[i++]=o>>18&7|240,e[i++]=o>>12&63|128,e[i++]=o>>6&63|128)}e[i++]=o&63|128}}const Kv=new TextEncoder,Hv=50;function Wv(t,e,n){Kv.encodeInto(t,e.subarray(n))}function Gv(t,e,n){t.length>Hv?Wv(t,e,n):Vv(t,e,n)}const Yv=4096;function lf(t,e,n){let r=e;const i=r+n,s=[];let o="";for(;r<i;){const a=t[r++];if((a&128)===0)s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,u=t[r++]&63;s.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[r++]&63,u=t[r++]&63,l=t[r++]&63;let h=(a&7)<<18|c<<12|u<<6|l;h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|h&1023),s.push(h)}else s.push(a);s.length>=Yv&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Zv=new TextDecoder,Jv=200;function Xv(t,e,n){const r=t.subarray(e,e+n);return Zv.decode(r)}function Qv(t,e,n){return n>Jv?Xv(t,e,n):lf(t,e,n)}class Ds{constructor(e,n){this.type=e,this.data=n}}class ct extends Error{constructor(e){super(e);const n=Object.create(ct.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ct.name})}}const li=4294967295;function eE(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function hf(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function ff(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function tE(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const nE=-1,rE=4294967296-1,iE=17179869184-1;function sE({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=iE)if(e===0&&t<=rE){const n=new Uint8Array(4);return new DataView(n.buffer).setUint32(0,t),n}else{const n=t/4294967296,r=t&4294967295,i=new Uint8Array(8),s=new DataView(i.buffer);return s.setUint32(0,e<<2|n&3),s.setUint32(4,r),i}else{const n=new Uint8Array(12),r=new DataView(n.buffer);return r.setUint32(0,e),hf(r,4,t),n}}function oE(t){const e=t.getTime(),n=Math.floor(e/1e3),r=(e-n*1e3)*1e6,i=Math.floor(r/1e9);return{sec:n+i,nsec:r-i*1e9}}function aE(t){if(t instanceof Date){const e=oE(t);return sE(e)}else return null}function cE(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const n=e.getUint32(0),r=e.getUint32(4),i=(n&3)*4294967296+r,s=n>>>2;return{sec:i,nsec:s}}case 12:{const n=ff(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new ct(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function uE(t){const e=cE(t);return new Date(e.sec*1e3+e.nsec/1e6)}const lE={type:nE,encode:aE,decode:uE};class Os{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(lE)}register({type:e,encode:n,decode:r}){if(e>=0)this.encoders[e]=n,this.decoders[e]=r;else{const i=-1-e;this.builtInEncoders[i]=n,this.builtInDecoders[i]=r}}tryToEncode(e,n){for(let r=0;r<this.builtInEncoders.length;r++){const i=this.builtInEncoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=-1-r;return new Ds(o,s)}}}for(let r=0;r<this.encoders.length;r++){const i=this.encoders[r];if(i!=null){const s=i(e,n);if(s!=null){const o=r;return new Ds(o,s)}}}return e instanceof Ds?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new Ds(n,e)}}Os.defaultCodec=new Os;function hE(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Fa(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):hE(t)?new Uint8Array(t):Uint8Array.from(t)}const fE=100,dE=2048;class ka{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Os.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??fE,this.initialBufferSize=e?.initialBufferSize??dE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new ka({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,n){if(n>this.maxDepth)throw new Error(`Too deep objects in depth ${n}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,n)}ensureBufferSizeToWrite(e){const n=this.pos+e;this.view.byteLength<n&&this.resizeBuffer(n*2)}resizeBuffer(e){const n=new ArrayBuffer(e),r=new Uint8Array(n),i=new DataView(n);r.set(this.bytes),this.view=i,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=jv(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Gv(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,n){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,n);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,n);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const n=e.byteLength;if(n<256)this.writeU8(196),this.writeU8(n);else if(n<65536)this.writeU8(197),this.writeU16(n);else if(n<4294967296)this.writeU8(198),this.writeU32(n);else throw new Error(`Too large binary: ${n}`);const r=Fa(e);this.writeU8a(r)}encodeArray(e,n){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const i of e)this.doEncode(i,n+1)}countWithoutUndefined(e,n){let r=0;for(const i of n)e[i]!==void 0&&r++;return r}encodeMap(e,n){const r=Object.keys(e);this.sortKeys&&r.sort();const i=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(i<16)this.writeU8(128+i);else if(i<65536)this.writeU8(222),this.writeU16(i);else if(i<4294967296)this.writeU8(223),this.writeU32(i);else throw new Error(`Too large map object: ${i}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,n+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),i=r.length;if(i>=4294967296)throw new Error(`Too large extension object: ${i}`);this.writeU8(201),this.writeU32(i),this.writeI8(e.type),this.writeU8a(r);return}const n=e.data.length;if(n===1)this.writeU8(212);else if(n===2)this.writeU8(213);else if(n===4)this.writeU8(214);else if(n===8)this.writeU8(215);else if(n===16)this.writeU8(216);else if(n<256)this.writeU8(199),this.writeU8(n);else if(n<65536)this.writeU8(200),this.writeU16(n);else if(n<4294967296)this.writeU8(201),this.writeU32(n);else throw new Error(`Too large extension object: ${n}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const n=e.length;this.ensureBufferSizeToWrite(n),this.bytes.set(e,this.pos),this.pos+=n}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),eE(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),hf(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}}function pE(t,e){return new ka(e).encodeSharedRef(t)}function La(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const gE=16,yE=16;class wE{constructor(e=gE,n=yE){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=n,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,n,r){const i=this.caches[r-1];e:for(const s of i){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[n+a])continue e;return s.str}return null}store(e,n){const r=this.caches[e.length-1],i={bytes:e,str:n};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=i:r.push(i)}decode(e,n,r){const i=this.find(e,n,r);if(i!=null)return this.hit++,i;this.miss++;const s=lf(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Ma="array",hi="map_key",df="map_value",mE=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ct("The type of key must be string or number but "+typeof t)};class bE{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const n=this.getUninitializedStateFromPool();n.type=Ma,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=hi,n.readCount=0,n.size=e,n.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ma){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===hi||e.type===df){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const fi=-1,za=new DataView(new ArrayBuffer(0)),vE=new Uint8Array(za.buffer);try{za.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}const pf=new RangeError("Insufficient data"),EE=new wE;class qa{constructor(e){this.totalPos=0,this.pos=0,this.view=za,this.bytes=vE,this.headByte=fi,this.stack=new bE,this.entered=!1,this.extensionCodec=e?.extensionCodec??Os.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??li,this.maxBinLength=e?.maxBinLength??li,this.maxArrayLength=e?.maxArrayLength??li,this.maxMapLength=e?.maxMapLength??li,this.maxExtLength=e?.maxExtLength??li,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:EE,this.mapKeyConverter=e?.mapKeyConverter??mE}clone(){return new qa({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=fi,this.stack.reset()}setBuffer(e){const n=Fa(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===fi&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=Fa(e),i=new Uint8Array(n.length+r.length);i.set(n),i.set(r,n.length),this.setBuffer(i)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:n,pos:r}=this;return new RangeError(`Extra ${n.byteLength-r} of ${n.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const n=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return n}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let n=!1,r;for await(const a of e){if(n)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),n=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(n){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:i,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${La(i)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,n){if(this.entered){yield*this.clone().decodeMultiAsync(e,n);return}try{this.entered=!0;let r=n,i=-1;for await(const s of e){if(n&&i===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(i=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--i!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let n;if(e>=224)n=e-256;else if(e<192)if(e<128)n=e;else if(e<144){const i=e-128;if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e<160){const i=e-144;if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else{const i=e-160;n=this.decodeString(i,0)}else if(e===192)n=null;else if(e===194)n=!1;else if(e===195)n=!0;else if(e===202)n=this.readF32();else if(e===203)n=this.readF64();else if(e===204)n=this.readU8();else if(e===205)n=this.readU16();else if(e===206)n=this.readU32();else if(e===207)this.useBigInt64?n=this.readU64AsBigInt():n=this.readU64();else if(e===208)n=this.readI8();else if(e===209)n=this.readI16();else if(e===210)n=this.readI32();else if(e===211)this.useBigInt64?n=this.readI64AsBigInt():n=this.readI64();else if(e===217){const i=this.lookU8();n=this.decodeString(i,1)}else if(e===218){const i=this.lookU16();n=this.decodeString(i,2)}else if(e===219){const i=this.lookU32();n=this.decodeString(i,4)}else if(e===220){const i=this.readU16();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===221){const i=this.readU32();if(i!==0){this.pushArrayState(i),this.complete();continue e}else n=[]}else if(e===222){const i=this.readU16();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===223){const i=this.readU32();if(i!==0){this.pushMapState(i),this.complete();continue e}else n={}}else if(e===196){const i=this.lookU8();n=this.decodeBinary(i,1)}else if(e===197){const i=this.lookU16();n=this.decodeBinary(i,2)}else if(e===198){const i=this.lookU32();n=this.decodeBinary(i,4)}else if(e===212)n=this.decodeExtension(1,0);else if(e===213)n=this.decodeExtension(2,0);else if(e===214)n=this.decodeExtension(4,0);else if(e===215)n=this.decodeExtension(8,0);else if(e===216)n=this.decodeExtension(16,0);else if(e===199){const i=this.lookU8();n=this.decodeExtension(i,1)}else if(e===200){const i=this.lookU16();n=this.decodeExtension(i,2)}else if(e===201){const i=this.lookU32();n=this.decodeExtension(i,4)}else throw new ct(`Unrecognized type byte: ${La(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Ma)if(i.array[i.position]=n,i.position++,i.position===i.size)n=i.array,r.release(i);else continue e;else if(i.type===hi){if(n==="__proto__")throw new ct("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=df;continue e}else if(i.map[i.key]=n,i.readCount++,i.readCount===i.size)n=i.map,r.release(i);else{i.key=null,i.type=hi;continue e}}return n}}readHeadByte(){return this.headByte===fi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=fi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ct(`Unrecognized array type byte: ${La(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ct(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ct(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,n){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,n):this.decodeBinary(e,n)}decodeUtf8String(e,n){if(e>this.maxStrLength)throw new ct(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw pf;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=Qv(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hi:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new ct(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw pf;const r=this.pos+n,i=this.bytes.subarray(r,r+e);return this.pos+=n+e,i}decodeExtension(e,n){if(e>this.maxExtLength)throw new ct(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+n),i=this.decodeBinary(e,n+1);return this.extensionCodec.decode(i,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=tE(this.view,this.pos);return this.pos+=8,e}readI64(){const e=ff(this.view,this.pos);return this.pos+=8,e}readU64AsBigInt(){const e=this.view.getBigUint64(this.pos);return this.pos+=8,e}readI64AsBigInt(){const e=this.view.getBigInt64(this.pos);return this.pos+=8,e}readF32(){const e=this.view.getFloat32(this.pos);return this.pos+=4,e}readF64(){const e=this.view.getFloat64(this.pos);return this.pos+=8,e}}function xE(t,e){return new qa(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function $s(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ja(t,...e){if(!$s(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function gf(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(n=>typeof n=="string"):e.every(n=>Number.isSafeInteger(n)):!1}function yf(t){if(typeof t!="function")throw new Error("function expected");return!0}function En(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function di(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ts(t){if(!Array.isArray(t))throw new Error("array expected")}function Bs(t,e){if(!gf(!0,e))throw new Error(`${t}: array of strings expected`)}function Va(t,e){if(!gf(!1,e))throw new Error(`${t}: array of numbers expected`)}function ut(...t){const e=s=>s,n=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(n,e),i=t.map(s=>s.decode).reduce(n,e);return{encode:r,decode:i}}function lt(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Bs("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Ts(i),i.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=n)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:i=>(Ts(i),i.map(s=>{En("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function ht(t=""){return En("join",t),{encode:e=>(Bs("join.decode",e),e.join(t)),decode:e=>(En("join.decode",e),e.split(t))}}function Ps(t,e="="){return di(t),En("padding",e),{encode(n){for(Bs("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Bs("padding.decode",n);let r=n.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&n[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return n.slice(0,r)}}}function wf(t){return yf(t),{encode:e=>e,decode:e=>t(e)}}function mf(t,e,n){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(n<2)throw new Error(`convertRadix: invalid to=${n}, base cannot be less than 2`);if(Ts(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(di(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=s.length;for(;;){let a=0,c=!0;for(let u=r;u<o;u++){const l=s[u],h=e*a,f=h+l;if(!Number.isSafeInteger(f)||h/e!==a||f-l!==h)throw new Error("convertRadix: carry overflow");const p=f/n;a=f%n;const d=Math.floor(p);if(s[u]=d,!Number.isSafeInteger(d)||d*n+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:r=u;else continue}if(i.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)i.push(0);return i.reverse()}const bf=(t,e)=>e===0?t:bf(e,t%e),Cs=(t,e)=>t+(e-bf(t,e)),Rs=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Ka(t,e,n,r){if(Ts(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(n<=0||n>32)throw new Error(`convertRadix2: wrong to=${n}`);if(Cs(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Cs(e,n)}`);let i=0,s=0;const o=Rs[e],a=Rs[n]-1,c=[];for(const u of t){if(di(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(i=i<<e|u,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=n;s-=n)c.push((i>>s-n&a)>>>0);const l=Rs[s];if(l===void 0)throw new Error("invalid carry");i&=l-1}if(i=i<<n-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&i>0)throw new Error(`Non-zero padding: ${i}`);return r&&s>0&&c.push(i>>>0),c}function _E(t){di(t);const e=2**8;return{encode:n=>{if(!$s(n))throw new Error("radix.encode input should be Uint8Array");return mf(Array.from(n),e,t)},decode:n=>(Va("radix.decode",n),Uint8Array.from(mf(n,t,e)))}}function mt(t,e=!1){if(di(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Cs(8,t)>32||Cs(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!$s(n))throw new Error("radix2.encode input should be Uint8Array");return Ka(Array.from(n),8,t,!e)},decode:n=>(Va("radix2.decode",n),Uint8Array.from(Ka(n,t,8,e)))}}function vf(t){return yf(t),function(...e){try{return t.apply(null,e)}catch{}}}const IE=ut(mt(5),lt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Ps(5),ht("")),Ef=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",xf=(t,e)=>{En("base64",t);const n=e?/^[A-Za-z0-9=_-]+$/:/^[A-Za-z0-9=+/]+$/,r=e?"base64url":"base64";if(t.length>0&&!n.test(t))throw new Error("invalid base64");return Uint8Array.fromBase64(t,{alphabet:r,lastChunkHandling:"strict"})},Ha=t=>ut(_E(58),lt(t),ht("")),Wa=ut(lt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),ht("")),_f=[996825010,642813549,513874426,1027748829,705979059];function pi(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<_f.length;r++)(e>>r&1)===1&&(n^=_f[r]);return n}function If(t,e,n=1){const r=t.length;let i=1;for(let s=0;s<r;s++){const o=t.charCodeAt(s);if(o<33||o>126)throw new Error(`Invalid prefix (${t})`);i=pi(i)^o>>5}i=pi(i);for(let s=0;s<r;s++)i=pi(i)^t.charCodeAt(s)&31;for(let s of e)i=pi(i)^s;for(let s=0;s<6;s++)i=pi(i);return i^=n,Wa.encode(Ka([i%Rs[30]],30,5,!1))}function Sf(t){const e=t==="bech32"?1:734539939,n=mt(5),r=n.decode,i=n.encode,s=vf(r);function o(h,f,p=90){En("bech32.encode prefix",h),$s(f)&&(f=Array.from(f)),Va("bech32.encode",f);const d=h.length;if(d===0)throw new TypeError(`Invalid prefix length ${d}`);const g=d+7+f.length;if(p!==!1&&g>p)throw new TypeError(`Length ${g} exceeds limit ${p}`);const y=h.toLowerCase(),_=If(y,f,e);return`${y}1${Wa.encode(f)}${_}`}function a(h,f=90){En("bech32.decode input",h);const p=h.length;if(p<8||f!==!1&&p>f)throw new TypeError(`invalid string length: ${p} (${h}). Expected (8..${f})`);const d=h.toLowerCase();if(h!==d&&h!==h.toUpperCase())throw new Error("String must be lowercase or uppercase");const g=d.lastIndexOf("1");if(g===0||g===-1)throw new Error('Letter "1" must be present between prefix and data only');const y=d.slice(0,g),_=d.slice(g+1);if(_.length<6)throw new Error("Data must be at least 6 characters long");const A=Wa.decode(_).slice(0,-6),b=If(y,A,e);if(!_.endsWith(b))throw new Error(`Invalid checksum in ${h}: expected "${b}"`);return{prefix:y,words:A}}const c=vf(a);function u(h){const{prefix:f,words:p}=a(h,!1);return{prefix:f,words:p,bytes:r(p)}}function l(h,f){return o(h,i(f))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const SE=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",AE={encode(t){return ja(t),t.toHex()},decode(t){return En("hex",t),Uint8Array.fromHex(t)}};function Ga(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Af(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ga(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function gi(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Af(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Ga(n)}function DE(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var OE=DE,$E=OE;const Df=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},TE=t=>new TextEncoder().encode(t),BE=t=>new TextDecoder().decode(t);class PE{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class CE{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Of(this,e)}}class RE{constructor(e){this.decoders=e}or(e){return Of(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Of=(t,e)=>new RE({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class NE{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new PE(e,n,r),this.decoder=new CE(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ns=({name:t,prefix:e,encode:n,decode:r})=>new NE(t,e,n,r),yi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=$E(n,e);return Ns({prefix:t,name:e,encode:r,decode:s=>Df(i(s))})},UE=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},FE=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Te=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ns({prefix:e,name:t,encode(i){return FE(i,r,n)},decode(i){return UE(i,r,n,t)}}),kE=Ns({prefix:"\0",name:"identity",encode:t=>BE(t),decode:t=>TE(t)});var LE=Object.freeze({__proto__:null,identity:kE});const ME=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var zE=Object.freeze({__proto__:null,base2:ME});const qE=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var jE=Object.freeze({__proto__:null,base8:qE});const VE=yi({prefix:"9",name:"base10",alphabet:"0123456789"});var KE=Object.freeze({__proto__:null,base10:VE});const HE=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),WE=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var GE=Object.freeze({__proto__:null,base16:HE,base16upper:WE});const YE=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),ZE=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),JE=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),XE=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),QE=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),e3=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),t3=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),n3=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),r3=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var i3=Object.freeze({__proto__:null,base32:YE,base32upper:ZE,base32pad:JE,base32padupper:XE,base32hex:QE,base32hexupper:e3,base32hexpad:t3,base32hexpadupper:n3,base32z:r3});const s3=yi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),o3=yi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var a3=Object.freeze({__proto__:null,base36:s3,base36upper:o3});const c3=yi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),u3=yi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var l3=Object.freeze({__proto__:null,base58btc:c3,base58flickr:u3});const h3=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),f3=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),d3=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),p3=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var g3=Object.freeze({__proto__:null,base64:h3,base64pad:f3,base64url:d3,base64urlpad:p3});const $f=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),y3=$f.reduce((t,e,n)=>(t[n]=e,t),[]),w3=$f.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function m3(t){return t.reduce((e,n)=>(e+=y3[n],e),"")}function b3(t){const e=[];for(const n of t){const r=w3[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const v3=Ns({prefix:"\u{1F680}",name:"base256emoji",encode:m3,decode:b3});var E3=Object.freeze({__proto__:null,base256emoji:v3}),x3=Bf,Tf=128,_3=127,I3=~_3,S3=Math.pow(2,31);function Bf(t,e,n){e=e||[],n=n||0;for(var r=n;t>=S3;)e[n++]=t&255|Tf,t/=128;for(;t&I3;)e[n++]=t&255|Tf,t>>>=7;return e[n]=t|0,Bf.bytes=n-r+1,e}var A3=Ya,D3=128,Pf=127;function Ya(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&Pf)<<i:(o&Pf)*Math.pow(2,i),i+=7}while(o>=D3);return Ya.bytes=s-r,n}var O3=Math.pow(2,7),$3=Math.pow(2,14),T3=Math.pow(2,21),B3=Math.pow(2,28),P3=Math.pow(2,35),C3=Math.pow(2,42),R3=Math.pow(2,49),N3=Math.pow(2,56),U3=Math.pow(2,63),F3=function(t){return t<O3?1:t<$3?2:t<T3?3:t<B3?4:t<P3?5:t<C3?6:t<R3?7:t<N3?8:t<U3?9:10},k3={encode:x3,decode:A3,encodingLength:F3},Cf=k3;const Rf=(t,e,n=0)=>(Cf.encode(t,e,n),e),Nf=t=>Cf.encodingLength(t),Za=(t,e)=>{const n=e.byteLength,r=Nf(t),i=r+Nf(n),s=new Uint8Array(i+n);return Rf(t,s,0),Rf(n,s,r),s.set(e,i),new L3(t,n,e,s)};class L3{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const Uf=({name:t,code:e,encode:n})=>new M3(t,e,n);class M3{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Za(this.code,n):n.then(r=>Za(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ff=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),z3=Uf({name:"sha2-256",code:18,encode:Ff("SHA-256")}),q3=Uf({name:"sha2-512",code:19,encode:Ff("SHA-512")});var j3=Object.freeze({__proto__:null,sha256:z3,sha512:q3});const kf=0,V3="identity",Lf=Df;var K3=Object.freeze({__proto__:null,identity:{code:kf,name:V3,encode:Lf,digest:t=>Za(kf,Lf(t))}});new TextEncoder,new TextDecoder;const Mf={...LE,...zE,...jE,...KE,...GE,...i3,...a3,...l3,...g3,...E3};({...j3,...K3});function zf(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const qf=zf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Ja=zf("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=Af(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),jf={utf8:qf,"utf-8":qf,hex:Mf.base16,latin1:Ja,ascii:Ja,binary:Ja,...Mf};function bt(t,e="utf8"){const n=jf[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ga(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function et(t,e="utf8"){const n=jf[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):n.encoder.encode(t).substring(1)}const H3={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}},W3="Input must be an string, Buffer or Uint8Array";function G3(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(W3);return e}function Y3(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Us(t){return(4294967296+t).toString(16).substring(1)}function Z3(t,e,n){let r=`
|
|
18
|
+
`+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=Us(e[i]).toUpperCase(),r+=" ",r+=Us(e[i+1]).toUpperCase();else if(n===64)r+=Us(e[i+1]).toUpperCase(),r+=Us(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
|
|
19
|
+
`+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function J3(t,e,n){let r=new Date().getTime();const i=new Uint8Array(e);for(let o=0;o<e;o++)i[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<n;o++){const a=t(i),c=new Date().getTime(),u=c-r;r=c,console.log("Hashed in "+u+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(u/1e3)*100)/100+" MB PER SECOND")}}var Vf={normalizeInput:G3,toHex:Y3,debugPrint:Z3,testSpeed:J3};const Fs=Vf;function ks(t,e,n){const r=t[e]+t[n];let i=t[e+1]+t[n+1];r>=4294967296&&i++,t[e]=r,t[e+1]=i}function Kf(t,e,n,r){let i=t[e]+n;n<0&&(i+=4294967296);let s=t[e+1]+r;i>=4294967296&&s++,t[e]=i,t[e+1]=s}function Hf(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function xn(t,e,n,r,i,s){const o=wi[i],a=wi[i+1],c=wi[s],u=wi[s+1];ks(G,t,e),Kf(G,t,o,a);let l=G[r]^G[t],h=G[r+1]^G[t+1];G[r]=h,G[r+1]=l,ks(G,n,r),l=G[e]^G[n],h=G[e+1]^G[n+1],G[e]=l>>>24^h<<8,G[e+1]=h>>>24^l<<8,ks(G,t,e),Kf(G,t,c,u),l=G[r]^G[t],h=G[r+1]^G[t+1],G[r]=l>>>16^h<<16,G[r+1]=h>>>16^l<<16,ks(G,n,r),l=G[e]^G[n],h=G[e+1]^G[n+1],G[e]=h>>>31^l<<1,G[e+1]=l>>>31^h<<1}const Wf=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),X3=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],Fe=new Uint8Array(X3.map(function(t){return t*2})),G=new Uint32Array(32),wi=new Uint32Array(32);function Gf(t,e){let n=0;for(n=0;n<16;n++)G[n]=t.h[n],G[n+16]=Wf[n];for(G[24]=G[24]^t.t,G[25]=G[25]^t.t/4294967296,e&&(G[28]=~G[28],G[29]=~G[29]),n=0;n<32;n++)wi[n]=Hf(t.b,4*n);for(n=0;n<12;n++)xn(0,8,16,24,Fe[n*16+0],Fe[n*16+1]),xn(2,10,18,26,Fe[n*16+2],Fe[n*16+3]),xn(4,12,20,28,Fe[n*16+4],Fe[n*16+5]),xn(6,14,22,30,Fe[n*16+6],Fe[n*16+7]),xn(0,10,20,30,Fe[n*16+8],Fe[n*16+9]),xn(2,12,22,24,Fe[n*16+10],Fe[n*16+11]),xn(4,14,16,26,Fe[n*16+12],Fe[n*16+13]),xn(6,8,18,28,Fe[n*16+14],Fe[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^G[n]^G[n+16]}const _n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function Yf(t,e,n,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(n&&n.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const i={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};_n.fill(0),_n[0]=t,e&&(_n[1]=e.length),_n[2]=1,_n[3]=1,n&&_n.set(n,32),r&&_n.set(r,48);for(let s=0;s<16;s++)i.h[s]=Wf[s]^Hf(_n,s*4);return e&&(Xa(i,e),i.c=128),i}function Xa(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,Gf(t,!1),t.c=0),t.b[t.c++]=e[n]}function Zf(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;Gf(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3);return e}function Jf(t,e,n,r,i){n=n||64,t=Fs.normalizeInput(t),r&&(r=Fs.normalizeInput(r)),i&&(i=Fs.normalizeInput(i));const s=Yf(n,e,r,i);return Xa(s,t),Zf(s)}function Q3(t,e,n,r,i){const s=Jf(t,e,n,r,i);return Fs.toHex(s)}var ex={blake2b:Jf,blake2bHex:Q3,blake2bInit:Yf,blake2bUpdate:Xa,blake2bFinal:Zf};const Xf=Vf;function tx(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function In(t,e,n,r,i,s){ee[t]=ee[t]+ee[e]+i,ee[r]=Ls(ee[r]^ee[t],16),ee[n]=ee[n]+ee[r],ee[e]=Ls(ee[e]^ee[n],12),ee[t]=ee[t]+ee[e]+s,ee[r]=Ls(ee[r]^ee[t],8),ee[n]=ee[n]+ee[r],ee[e]=Ls(ee[e]^ee[n],7)}function Ls(t,e){return t>>>e^t<<32-e}const Qf=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ke=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),ee=new Uint32Array(16),Be=new Uint32Array(16);function ed(t,e){let n=0;for(n=0;n<8;n++)ee[n]=t.h[n],ee[n+8]=Qf[n];for(ee[12]^=t.t,ee[13]^=t.t/4294967296,e&&(ee[14]=~ee[14]),n=0;n<16;n++)Be[n]=tx(t.b,4*n);for(n=0;n<10;n++)In(0,4,8,12,Be[ke[n*16+0]],Be[ke[n*16+1]]),In(1,5,9,13,Be[ke[n*16+2]],Be[ke[n*16+3]]),In(2,6,10,14,Be[ke[n*16+4]],Be[ke[n*16+5]]),In(3,7,11,15,Be[ke[n*16+6]],Be[ke[n*16+7]]),In(0,5,10,15,Be[ke[n*16+8]],Be[ke[n*16+9]]),In(1,6,11,12,Be[ke[n*16+10]],Be[ke[n*16+11]]),In(2,7,8,13,Be[ke[n*16+12]],Be[ke[n*16+13]]),In(3,4,9,14,Be[ke[n*16+14]],Be[ke[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=ee[n]^ee[n+8]}function td(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const n=e?e.length:0;if(e&&!(n>0&&n<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(Qf),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Qa(r,e),r.c=64),r}function Qa(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,ed(t,!1),t.c=0),t.b[t.c++]=e[n]}function nd(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;ed(t,!0);const e=new Uint8Array(t.outlen);for(let n=0;n<t.outlen;n++)e[n]=t.h[n>>2]>>8*(n&3)&255;return e}function rd(t,e,n){n=n||32,t=Xf.normalizeInput(t);const r=td(n,e);return Qa(r,t),nd(r)}function nx(t,e,n){const r=rd(t,e,n);return Xf.toHex(r)}var rx={blake2s:rd,blake2sHex:nx,blake2sInit:td,blake2sUpdate:Qa,blake2sFinal:nd};const mi=ex,bi=rx;var ix={blake2b:mi.blake2b,blake2bHex:mi.blake2bHex,blake2bInit:mi.blake2bInit,blake2bUpdate:mi.blake2bUpdate,blake2bFinal:mi.blake2bFinal,blake2s:bi.blake2s,blake2sHex:bi.blake2sHex,blake2sInit:bi.blake2sInit,blake2sUpdate:bi.blake2sUpdate,blake2sFinal:bi.blake2sFinal};const sx=":";function tr(t){const[e,n]=t.split(sx);return{namespace:e,reference:n}}function id(t,e){return t.includes(":")?[t]:e.chains||[]}var ox=Object.defineProperty,ax=Object.defineProperties,cx=Object.getOwnPropertyDescriptors,sd=Object.getOwnPropertySymbols,ux=Object.prototype.hasOwnProperty,lx=Object.prototype.propertyIsEnumerable,ec=(t,e,n)=>e in t?ox(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,od=(t,e)=>{for(var n in e||(e={}))ux.call(e,n)&&ec(t,n,e[n]);if(sd)for(var n of sd(e))lx.call(e,n)&&ec(t,n,e[n]);return t},hx=(t,e)=>ax(t,cx(e)),ad=(t,e,n)=>ec(t,typeof e!="symbol"?e+"":e,n);const fx="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},dx="js";function Ms(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function Sn(){return!Yn()&&!!ea()&&navigator.product===fx}function px(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function gx(){return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Dr(){return!Ms()&&!!ea()&&!!Yn()}function vi(){return Sn()?ft.reactNative:Ms()?ft.node:Dr()?ft.browser:ft.unknown}function cd(){var t;try{return Sn()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function yx(t,e){const n=new URLSearchParams(t);for(const r of Object.keys(e).sort())if(e.hasOwnProperty(r)){const i=e[r];i!==void 0&&n.set(r,i)}return n.toString()}function wx(t){var e,n;const r=ud();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(i=>i!=="")),hx(od(od({},r),t),{url:t?.url||r.url,name:t?.name||r.name,description:t?.description||r.description,icons:(n=t?.icons)!=null&&n.length&&t.icons.length>0?t.icons:r.icons})}catch(i){return console.warn("Error populating app metadata",i),t||r}}function ud(){return eh()||{name:"",description:"",url:"",icons:[""]}}function mx(){if(vi()===ft.reactNative&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"){const{OS:n,Version:r}=global.Platform;return[n,r].join("-")}const t=mb();if(t===null)return"unknown";const e=t.os?t.os.replace(" ","").toLowerCase():"unknown";return t.type==="browser"?[e,t.name,t.version].join("-"):[e,t.version].join("-")}function bx(){var t;const e=vi();return e===ft.browser?[e,((t=Ql())==null?void 0:t.host)||"unknown"].join(":"):e}function ld(t,e,n){const r=mx(),i=bx();return[[t,e].join("-"),[dx,n].join("-"),r,i].join("/")}function vx({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=ld(t,e,r),h={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=yx(u[1]||"",h);return u[0]+"?"+f}function nr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function tc(t){return Object.fromEntries(t.entries())}function nc(t){return new Map(Object.entries(t))}function rr(t=M.FIVE_MINUTES,e){const n=M.toMiliseconds(t||M.FIVE_MINUTES);let r,i,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&i&&(clearTimeout(s),i(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const u=new Error(e);o=Promise.reject(u),c(u)},n),r=a,i=c})}}function jt(t,e,n){return new Promise(async(r,i)=>{const s=setTimeout(()=>i(new Error(n)),e);try{const o=await t;r(o)}catch(o){i(o)}clearTimeout(s)})}function hd(t,e){if(typeof e=="string"&&e.startsWith(`${t}:`))return e;if(t.toLowerCase()==="topic"){if(typeof e!="string")throw new Error('Value must be "string" for expirer target type: topic');return`topic:${e}`}else if(t.toLowerCase()==="id"){if(typeof e!="number")throw new Error('Value must be "number" for expirer target type: id');return`id:${e}`}throw new Error(`Unknown expirer target type: ${t}`)}function Ex(t){return hd("topic",t)}function xx(t){return hd("id",t)}function fd(t){const[e,n]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof n=="string")r.topic=n;else if(e==="id"&&Number.isInteger(Number(n)))r.id=Number(n);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${n}`);return r}function Ee(t,e){return M.fromMiliseconds((e||Date.now())+M.toMiliseconds(t))}function An(t){return Date.now()>=M.toMiliseconds(t)}function re(t,e){return`${t}${e?`:${e}`:""}`}function ir(t=[],e=[]){return[...new Set([...t,...e])]}async function _x({id:t,topic:e,wcDeepLink:n}){var r;try{if(!n)return;const i=typeof n=="string"?JSON.parse(n):n,s=i?.href;if(typeof s!="string")return;const o=Ix(s,t,e),a=vi();if(a===ft.browser){if(!((r=Yn())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}Sx(o)}else a===ft.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function Ix(t,e,n){const r=`requestId=${e}&sessionTopic=${n}`;t.endsWith("/")&&(t=t.slice(0,-1));let i=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";i=`${i}${s}${$x(r,!0)}`}else i=`${i}/wc?${r}`;return i}function Sx(t){let e="_self";Ox()?e="_top":(Dx()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function Ax(t,e){let n="";try{if(Dr()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function dd(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function pd(){return typeof crypto<"u"&&crypto!=null&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/gu,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function rc(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function Dx(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function Ox(){try{return window.self!==window.top}catch{return!1}}function $x(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function gd(t){return Buffer.from(t,"base64").toString("utf-8")}function Tx(t){return new Promise(e=>setTimeout(e,t))}class Bx{constructor({limit:e}){ad(this,"limit"),ad(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const n=this.set.values().next().value;n&&this.set.delete(n)}this.set.add(e)}}has(e){return this.set.has(e)}}const zs=BigInt(2**32-1),yd=BigInt(32);function wd(t,e=!1){return e?{h:Number(t&zs),l:Number(t>>yd&zs)}:{h:Number(t>>yd&zs)|0,l:Number(t&zs)|0}}function md(t,e=!1){const n=t.length;let r=new Uint32Array(n),i=new Uint32Array(n);for(let s=0;s<n;s++){const{h:o,l:a}=wd(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const bd=(t,e,n)=>t>>>n,vd=(t,e,n)=>t<<32-n|e>>>n,Dn=(t,e,n)=>t>>>n|e<<32-n,On=(t,e,n)=>t<<32-n|e>>>n,Ei=(t,e,n)=>t<<64-n|e>>>n-32,xi=(t,e,n)=>t>>>n-32|e<<64-n,Px=(t,e)=>e,Cx=(t,e)=>t,Rx=(t,e,n)=>t<<n|e>>>32-n,Nx=(t,e,n)=>e<<n|t>>>32-n,Ux=(t,e,n)=>e<<n-32|t>>>64-n,Fx=(t,e,n)=>t<<n-32|e>>>64-n;function Pt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const ic=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),sc=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,kx=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Lx=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Mx=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),zx=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Or=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function rn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!oc(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function ac(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");rn(t.outputLen),rn(t.blockLen)}function $n(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function cc(t,e){vt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function _i(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Et(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function uc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Vt(t,e){return t<<32-e|t>>>e}const Ed=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function xd(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const sn=Ed?t=>t:t=>xd(t);function qx(t){for(let e=0;e<t.length;e++)t[e]=xd(t[e]);return t}const Tn=Ed?t=>t:qx,_d=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",jx=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ii(t){if(vt(t),_d)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=jx[t[n]];return e}const on={_0:48,_9:57,A:65,F:70,a:97,f:102};function Id(t){if(t>=on._0&&t<=on._9)return t-on._0;if(t>=on.A&&t<=on.F)return t-(on.A-10);if(t>=on.a&&t<=on.f)return t-(on.a-10)}function lc(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(_d)return Uint8Array.fromHex(t);const e=t.length,n=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(n);for(let i=0,s=0;i<n;i++,s+=2){const o=Id(t.charCodeAt(s)),a=Id(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[i]=o*16+a}return r}function Vx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ct(t){return typeof t=="string"&&(t=Vx(t)),vt(t),t}function sr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];vt(i),e+=i.length}const n=new Uint8Array(e);for(let r=0,i=0;r<t.length;r++){const s=t[r];n.set(s,i),i+=s.length}return n}class qs{}function Si(t){const e=r=>t().update(Ct(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Kx(t){const e=(r,i)=>t(i).update(Ct(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function $r(t=32){if(Or&&typeof Or.getRandomValues=="function")return Or.getRandomValues(new Uint8Array(t));if(Or&&typeof Or.randomBytes=="function")return Uint8Array.from(Or.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Hx=BigInt(0),Ai=BigInt(1),Wx=BigInt(2),Gx=BigInt(7),Yx=BigInt(256),Zx=BigInt(113),Sd=[],Ad=[],Dd=[];for(let t=0,e=Ai,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Sd.push(2*(5*r+n)),Ad.push((t+1)*(t+2)/2%64);let i=Hx;for(let s=0;s<7;s++)e=(e<<Ai^(e>>Gx)*Zx)%Yx,e&Wx&&(i^=Ai<<(Ai<<BigInt(s))-Ai);Dd.push(i)}const Od=md(Dd,!0),Jx=Od[0],Xx=Od[1],$d=(t,e,n)=>n>32?Ux(t,e,n):Rx(t,e,n),Td=(t,e,n)=>n>32?Fx(t,e,n):Nx(t,e,n);function Qx(t,e=24){const n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)n[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,u=n[c],l=n[c+1],h=$d(u,l,1)^n[a],f=Td(u,l,1)^n[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Ad[o],c=$d(i,s,a),u=Td(i,s,a),l=Sd[o];i=t[l],s=t[l+1],t[l]=c,t[l+1]=u}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)n[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~n[(a+2)%10]&n[(a+4)%10]}t[0]^=Jx[r],t[1]^=Xx[r]}Et(n)}class hc extends qs{constructor(e,n,r,i=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=i,this.rounds=s,rn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=_i(this.state)}clone(){return this._cloneInto()}keccak(){Tn(this.state32),Qx(this.state32,this.rounds),Tn(this.state32),this.posOut=0,this.pos=0}update(e){$n(this),e=Ct(e),vt(e);const{blockLen:n,state:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(n-this.pos,i-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:n,pos:r,blockLen:i}=this;e[r]^=n,(n&128)!==0&&r===i-1&&this.keccak(),e[i-1]^=128,this.keccak()}writeInto(e){$n(this,!1),vt(e),this.finish();const n=this.state,{blockLen:r}=this;for(let i=0,s=e.length;i<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-i);e.set(n.subarray(this.posOut,this.posOut+o),i),this.posOut+=o,i+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return rn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(cc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Et(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new hc(n,r,i,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=i,e.enableXOF=o,e.destroyed=this.destroyed,e}}const e_=(t,e,n)=>Si(()=>new hc(e,t,n)),t_=e_(1,136,256/8);function n_(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function r_(t,e,n){return t&e^~t&n}function i_(t,e,n){return t&e^t&n^e&n}class Bd extends qs{constructor(e,n,r,i){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=n,this.padOffset=r,this.isLE=i,this.buffer=new Uint8Array(e),this.view=uc(this.buffer)}update(e){$n(this),e=Ct(e),vt(e);const{view:n,buffer:r,blockLen:i}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(i-this.pos,s-o);if(a===i){const c=uc(e);for(;i<=s-o;o+=i)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===i&&(this.process(n,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){$n(this),cc(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Et(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let h=o;h<i;h++)n[h]=0;n_(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=uc(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],s)}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:n,buffer:r,length:i,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=i,e.pos=a,i%n&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const Bn=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),s_=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Pn=new Uint32Array(64);class o_ extends Bd{constructor(e=32){super(64,e,8,!1),this.A=Bn[0]|0,this.B=Bn[1]|0,this.C=Bn[2]|0,this.D=Bn[3]|0,this.E=Bn[4]|0,this.F=Bn[5]|0,this.G=Bn[6]|0,this.H=Bn[7]|0}get(){const{A:e,B:n,C:r,D:i,E:s,F:o,G:a,H:c}=this;return[e,n,r,i,s,o,a,c]}set(e,n,r,i,s,o,a,c){this.A=e|0,this.B=n|0,this.C=r|0,this.D=i|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,n){for(let h=0;h<16;h++,n+=4)Pn[h]=e.getUint32(n,!1);for(let h=16;h<64;h++){const f=Pn[h-15],p=Pn[h-2],d=Vt(f,7)^Vt(f,18)^f>>>3,g=Vt(p,17)^Vt(p,19)^p>>>10;Pn[h]=g+Pn[h-7]+d+Pn[h-16]|0}let{A:r,B:i,C:s,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=Vt(a,6)^Vt(a,11)^Vt(a,25),p=l+f+r_(a,c,u)+s_[h]+Pn[h]|0,d=(Vt(r,2)^Vt(r,13)^Vt(r,22))+i_(r,i,s)|0;l=u,u=c,c=a,a=o+p|0,o=s,s=i,i=r,r=p+d|0}r=r+this.A|0,i=i+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,u=u+this.G|0,l=l+this.H|0,this.set(r,i,s,o,a,c,u,l)}roundClean(){Et(Pn)}destroy(){this.set(0,0,0,0,0,0,0,0),Et(this.buffer)}}const Pd=md(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))),a_=Pd[0],c_=Pd[1],Cn=new Uint32Array(80),Rn=new Uint32Array(80);class fc extends Bd{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:n,Bh:r,Bl:i,Ch:s,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:g,Hl:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.Ah=e|0,this.Al=n|0,this.Bh=r|0,this.Bl=i|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=g|0,this.Hl=y|0}process(e,n){for(let b=0;b<16;b++,n+=4)Cn[b]=e.getUint32(n),Rn[b]=e.getUint32(n+=4);for(let b=16;b<80;b++){const v=Cn[b-15]|0,x=Rn[b-15]|0,T=Dn(v,x,1)^Dn(v,x,8)^bd(v,x,7),R=On(v,x,1)^On(v,x,8)^vd(v,x,7),C=Cn[b-2]|0,m=Rn[b-2]|0,B=Dn(C,m,19)^Ei(C,m,61)^bd(C,m,6),S=On(C,m,19)^xi(C,m,61)^vd(C,m,6),O=kx(R,S,Rn[b-7],Rn[b-16]),P=Lx(O,T,B,Cn[b-7],Cn[b-16]);Cn[b]=P|0,Rn[b]=O|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:g,Gl:y,Hh:_,Hl:A}=this;for(let b=0;b<80;b++){const v=Dn(h,f,14)^Dn(h,f,18)^Ei(h,f,41),x=On(h,f,14)^On(h,f,18)^xi(h,f,41),T=h&p^~h&g,R=f&d^~f&y,C=Mx(A,x,R,c_[b],Rn[b]),m=zx(C,_,v,T,a_[b],Cn[b]),B=C|0,S=Dn(r,i,28)^Ei(r,i,34)^Ei(r,i,39),O=On(r,i,28)^xi(r,i,34)^xi(r,i,39),P=r&s^r&a^s&a,F=i&o^i&c^o&c;_=g|0,A=y|0,g=p|0,y=d|0,p=h|0,d=f|0,{h,l:f}=Pt(u|0,l|0,m|0,B|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const E=ic(B,O,F);r=sc(E,m,S,P),i=E|0}({h:r,l:i}=Pt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Pt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Pt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Pt(this.Fh|0,this.Fl|0,p|0,d|0),{h:g,l:y}=Pt(this.Gh|0,this.Gl|0,g|0,y|0),{h:_,l:A}=Pt(this.Hh|0,this.Hl|0,_|0,A|0),this.set(r,i,s,o,a,c,u,l,h,f,p,d,g,y,_,A)}roundClean(){Et(Cn,Rn)}destroy(){Et(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class u_ extends fc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const ze=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class l_ extends fc{constructor(){super(32),this.Ah=ze[0]|0,this.Al=ze[1]|0,this.Bh=ze[2]|0,this.Bl=ze[3]|0,this.Ch=ze[4]|0,this.Cl=ze[5]|0,this.Dh=ze[6]|0,this.Dl=ze[7]|0,this.Eh=ze[8]|0,this.El=ze[9]|0,this.Fh=ze[10]|0,this.Fl=ze[11]|0,this.Gh=ze[12]|0,this.Gl=ze[13]|0,this.Hh=ze[14]|0,this.Hl=ze[15]|0}}const js=Si(()=>new o_),h_=Si(()=>new fc),f_=Si(()=>new u_),d_=Si(()=>new l_),p_=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),xe=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),q=new Uint32Array(32);function Nn(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*n],p=q[2*n+1],d=q[2*r],g=q[2*r+1],y=ic(c,l,o);u=sc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Px(g,d),Dl:Cx(g)},{h:p,l:f}=Pt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:Dn(h,l,24),Bl:On(h,l,24)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*n]=f,q[2*n+1]=p,q[2*r]=d,q[2*r+1]=g}function Un(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=q[2*t],u=q[2*t+1],l=q[2*e],h=q[2*e+1],f=q[2*n],p=q[2*n+1],d=q[2*r],g=q[2*r+1],y=ic(c,l,o);u=sc(y,u,h,a),c=y|0,{Dh:g,Dl:d}={Dh:g^u,Dl:d^c},{Dh:g,Dl:d}={Dh:Dn(g,d,16),Dl:On(g,d,16)},{h:p,l:f}=Pt(p,f,g,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:Ei(h,l,63),Bl:xi(h,l,63)},q[2*t]=c,q[2*t+1]=u,q[2*e]=l,q[2*e+1]=h,q[2*n]=f,q[2*n+1]=p,q[2*r]=d,q[2*r+1]=g}function g_(t,e={},n,r,i){if(rn(n),t<0||t>n)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>n))throw new Error("key length must be undefined or 1.."+n);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==i)throw new Error("personalization must be undefined or "+i)}class y_ extends qs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,rn(e),rn(n),this.blockLen=e,this.outputLen=n,this.buffer=new Uint8Array(e),this.buffer32=_i(this.buffer)}update(e){$n(this),e=Ct(e),vt(e);const{blockLen:n,buffer:r,buffer32:i}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===n&&(Tn(i),this.compress(i,0,!1),Tn(i),this.pos=0);const u=Math.min(n-this.pos,s-c),l=o+c;if(u===n&&!(l%4)&&c+u<s){const h=new Uint32Array(a,l,Math.floor((s-c)/4));Tn(h);for(let f=0;c+n<s;f+=i.length,c+=n)this.length+=n,this.compress(h,f,!1);Tn(h);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){$n(this),cc(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,Et(this.buffer.subarray(n)),Tn(r),this.compress(r,0,!0),Tn(r);const i=_i(e);this.get().forEach((s,o)=>i[o]=sn(s))}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}_cloneInto(e){const{buffer:n,length:r,finished:i,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(n),e.destroyed=s,e.finished=i,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class w_ extends y_{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=xe[0]|0,this.v0h=xe[1]|0,this.v1l=xe[2]|0,this.v1h=xe[3]|0,this.v2l=xe[4]|0,this.v2h=xe[5]|0,this.v3l=xe[6]|0,this.v3h=xe[7]|0,this.v4l=xe[8]|0,this.v4h=xe[9]|0,this.v5l=xe[10]|0,this.v5h=xe[11]|0,this.v6l=xe[12]|0,this.v6h=xe[13]|0,this.v7l=xe[14]|0,this.v7h=xe[15]|0,g_(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Ct(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Ct(s);const a=_i(s);this.v4l^=sn(a[0]),this.v4h^=sn(a[1]),this.v5l^=sn(a[2]),this.v5h^=sn(a[3])}if(i!==void 0){i=Ct(i);const a=_i(i);this.v6l^=sn(a[0]),this.v6h^=sn(a[1]),this.v7l^=sn(a[2]),this.v7h^=sn(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:n,v1l:r,v1h:i,v2l:s,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:h,v5h:f,v6l:p,v6h:d,v7l:g,v7h:y}=this;return[e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y]}set(e,n,r,i,s,o,a,c,u,l,h,f,p,d,g,y){this.v0l=e|0,this.v0h=n|0,this.v1l=r|0,this.v1h=i|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=h|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=g|0,this.v7h=y|0}compress(e,n,r){this.get().forEach((c,u)=>q[u]=c),q.set(xe,16);let{h:i,l:s}=wd(BigInt(this.length));q[24]=xe[8]^s,q[25]=xe[9]^i,r&&(q[28]=~q[28],q[29]=~q[29]);let o=0;const a=p_;for(let c=0;c<12;c++)Nn(0,4,8,12,e,n+2*a[o++]),Un(0,4,8,12,e,n+2*a[o++]),Nn(1,5,9,13,e,n+2*a[o++]),Un(1,5,9,13,e,n+2*a[o++]),Nn(2,6,10,14,e,n+2*a[o++]),Un(2,6,10,14,e,n+2*a[o++]),Nn(3,7,11,15,e,n+2*a[o++]),Un(3,7,11,15,e,n+2*a[o++]),Nn(0,5,10,15,e,n+2*a[o++]),Un(0,5,10,15,e,n+2*a[o++]),Nn(1,6,11,12,e,n+2*a[o++]),Un(1,6,11,12,e,n+2*a[o++]),Nn(2,7,8,13,e,n+2*a[o++]),Un(2,7,8,13,e,n+2*a[o++]),Nn(3,4,9,14,e,n+2*a[o++]),Un(3,4,9,14,e,n+2*a[o++]);this.v0l^=q[0]^q[16],this.v0h^=q[1]^q[17],this.v1l^=q[2]^q[18],this.v1h^=q[3]^q[19],this.v2l^=q[4]^q[20],this.v2h^=q[5]^q[21],this.v3l^=q[6]^q[22],this.v3h^=q[7]^q[23],this.v4l^=q[8]^q[24],this.v4h^=q[9]^q[25],this.v5l^=q[10]^q[26],this.v5h^=q[11]^q[27],this.v6l^=q[12]^q[28],this.v6h^=q[13]^q[29],this.v7l^=q[14]^q[30],this.v7h^=q[15]^q[31],Et(q)}destroy(){this.destroyed=!0,Et(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const m_=Kx(t=>new w_(t)),b_="https://rpc.walletconnect.org/v1";function Cd(t){const e=`Ethereum Signed Message:
|
|
20
|
+
${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(t_(n)).toString("hex")}async function v_(t,e,n,r,i,s){switch(n.t){case"eip191":return await E_(t,e,n.s);case"eip1271":return await x_(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}async function E_(t,e,n){return(await b2({hash:Cd(e),signature:n})).toLowerCase()===t.toLowerCase()}async function x_(t,e,n,r,i,s){const o=tr(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Cd(e)).substring(2),f=a+h+c+l+u,p=await fetch(`${s||b_}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:__(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:d}=await p.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function __(){return Date.now()+Math.floor(Math.random()*1e3)}function I_(t){const e=atob(t),n=new Uint8Array(e.length);for(let o=0;o<e.length;o++)n[o]=e.charCodeAt(o);const r=n[0];if(r===0)throw new Error("No signatures found");const i=1+r*64;if(n.length<i)throw new Error("Transaction data too short for claimed signature count");if(n.length<100)throw new Error("Transaction too short");const s=Buffer.from(t,"base64").slice(1,65);return ui.encode(s)}function S_(t){const e=new Uint8Array(Buffer.from(t,"base64")),n=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(n.length+e.length);r.set(n),r.set(e,n.length);const i=m_(r,{dkLen:32});return ui.encode(i)}function Rd(t){const e=new Uint8Array(js(A_(t)));return ui.encode(e)}function A_(t){if(t instanceof Uint8Array)return t;if(Array.isArray(t))return new Uint8Array(t);if(typeof t=="object"&&t!=null&&t.data)return new Uint8Array(Object.values(t.data));if(typeof t=="object"&&t)return new Uint8Array(Object.values(t));throw new Error("getNearUint8ArrayFromBytes: Unexpected result type from bytes array")}function Nd(t){const e=Buffer.from(t,"base64"),n=xE(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=pE(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=d_(s);return IE.encode(o).replace(/=+$/,"")}function dc(t){const e=[];let n=BigInt(t);for(;n>=BigInt(128);)e.push(Number(n&BigInt(127)|BigInt(128))),n>>=BigInt(7);return e.push(Number(n)),Buffer.from(e)}function D_(t){const e=Buffer.from(t.signed.bodyBytes,"base64"),n=Buffer.from(t.signed.authInfoBytes,"base64"),r=Buffer.from(t.signature.signature,"base64"),i=[];i.push(Buffer.from([10])),i.push(dc(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(dc(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(dc(r.length)),i.push(r);const s=Buffer.concat(i),o=js(s);return Buffer.from(o).toString("hex").toUpperCase()}var O_=Object.defineProperty,$_=Object.defineProperties,T_=Object.getOwnPropertyDescriptors,Ud=Object.getOwnPropertySymbols,B_=Object.prototype.hasOwnProperty,P_=Object.prototype.propertyIsEnumerable,Fd=(t,e,n)=>e in t?O_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,C_=(t,e)=>{for(var n in e||(e={}))B_.call(e,n)&&Fd(t,n,e[n]);if(Ud)for(var n of Ud(e))P_.call(e,n)&&Fd(t,n,e[n]);return t},R_=(t,e)=>$_(t,T_(e));const N_="did:pkh:",pc=t=>t?.split(":"),U_=t=>{const e=t&&pc(t);if(e)return t.includes(N_)?e[3]:e[1]},gc=t=>{const e=t&&pc(t);if(e)return e[2]+":"+e[3]},Vs=t=>{const e=t&&pc(t);if(e)return e.pop()};async function kd(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=Ld(i,i.iss),o=Vs(i.iss);return await v_(o,s,r,gc(i.iss),n)}const Ld=(t,e)=>{const n=`${t.domain} wants you to sign in with your Ethereum account:`,r=Vs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let i=t.statement||void 0;const s=`URI: ${t.aud||t.uri}`,o=`Version: ${t.version}`,a=`Chain ID: ${U_(e)}`,c=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,l=t.exp?`Expiration Time: ${t.exp}`:void 0,h=t.nbf?`Not Before: ${t.nbf}`:void 0,f=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(g=>`
|
|
21
|
+
- ${g}`).join("")}`:void 0,d=Ks(t.resources);if(d){const g=Di(d);i=K_(i,g)}return[n,r,"",i,"",s,o,a,c,u,l,h,f,p].filter(g=>g!=null).join(`
|
|
22
|
+
`)};function F_(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function k_(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function or(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(n=>{const r=t.att[n];if(Array.isArray(r))throw new Error(`Resource must be an object: ${n}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${n}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${n}`);Object.keys(r).forEach(i=>{const s=r[i];if(!Array.isArray(s))throw new Error(`Ability limits ${i} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${i} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${i}) must be an array of objects, found: ${o}`)})})})}function L_(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:M_(e,n,r)}}}function M_(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function Md(t){return or(t),`urn:recap:${F_(t).replace(/=/g,"")}`}function Di(t){const e=k_(t.replace("urn:recap:",""));return or(e),e}function z_(t,e,n){const r=L_(t,e,n);return Md(r)}function q_(t){return t&&t.includes("urn:recap:")}function j_(t,e){const n=Di(t),r=Di(e),i=V_(n,r);return Md(i)}function V_(t,e){or(t),or(e);const n=Object.keys(t.att).concat(Object.keys(e.att)).sort((i,s)=>i.localeCompare(s)),r={att:{}};return n.forEach(i=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[i])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[i])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;r.att[i]=R_(C_({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function K_(t="",e){or(e);const n="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(n))return t;const r=[];let i=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(i++,`(${i}) '${h}': '${u[h].join("', '")}' for '${a}'.`));r.push(l.join(", ").replace(".,","."))});const s=r.join(" "),o=`${n}${s}`;return`${t?t+" ":""}${o}`}function zd(t){var e;const n=Di(t);or(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function qd(t){const e=Di(t);or(e);const n=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(i=>{var s;(s=i?.[0])!=null&&s.chains&&n.push(i[0].chains)})}),[...new Set(n.flat())]}function Ks(t){if(!t)return;const e=t?.[t.length-1];return q_(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function jd(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function yc(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function wc(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function tt(t,...e){if(!jd(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error("Uint8Array expected of length "+e+", got length="+t.length)}function Vd(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function H_(t,e){tt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function Fn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Tr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function W_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const G_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Y_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function mc(t){if(typeof t=="string")t=Y_(t);else if(jd(t))t=bc(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Z_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function J_(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t[r]^e[r];return n===0}const X_=(t,e)=>{function n(r,...i){if(tt(r),!G_)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=i[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?tt(u):tt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&tt(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");tt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,tt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(tt(u),s&&u.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(n,t),n};function Kd(t,e,n=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(n&&!e8(e))throw new Error("invalid output, must be aligned");return e}function Hd(t,e,n,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,n,r);const i=BigInt(32),s=BigInt(4294967295),o=Number(n>>i&s),a=Number(n&s),c=r?4:0,u=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+u,a,r)}function Q_(t,e,n){yc(n);const r=new Uint8Array(16),i=W_(r);return Hd(i,0,BigInt(e),n),Hd(i,8,BigInt(t),n),r}function e8(t){return t.byteOffset%4===0}function bc(t){return Uint8Array.from(t)}const Wd=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),t8=Wd("expand 16-byte k"),n8=Wd("expand 32-byte k"),r8=Fn(t8),i8=Fn(n8);function te(t,e){return t<<e|t>>>32-e}function vc(t){return t.byteOffset%4===0}const Hs=64,s8=16,Gd=2**32-1,Yd=new Uint32Array;function o8(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(Hs),l=Fn(u),h=vc(i)&&vc(s),f=h?Fn(i):Yd,p=h?Fn(s):Yd;for(let d=0;d<c;o++){if(t(e,n,r,l,o,a),o>=Gd)throw new Error("arx: counter overflow");const g=Math.min(Hs,c-d);if(h&&g===Hs){const y=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let _=0,A;_<s8;_++)A=y+_,p[A]=f[A]^l[_];d+=Hs;continue}for(let y=0,_;y<g;y++)_=d+y,s[_]=i[_]^u[y];d+=g}}function a8(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=Z_({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return wc(i),wc(o),yc(s),yc(n),(a,c,u,l,h=0)=>{tt(a),tt(c),tt(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),tt(l),wc(h),h<0||h>=Gd)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const p=[];let d=a.length,g,y;if(d===32)p.push(g=bc(a)),y=i8;else if(d===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),y=r8,p.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);vc(c)||p.push(c=bc(c));const _=Fn(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(y,_,Fn(c.subarray(0,16)),_),c=c.subarray(16)}const A=16-i;if(A!==c.length)throw new Error(`arx: nonce must be ${A} or 16 bytes`);if(A!==12){const v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,p.push(c)}const b=Fn(c);return o8(t,y,_,b,u,l,h,o),Tr(...p),l}}const Pe=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class c8{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,e=mc(e),tt(e,32);const n=Pe(e,0),r=Pe(e,2),i=Pe(e,4),s=Pe(e,6),o=Pe(e,8),a=Pe(e,10),c=Pe(e,12),u=Pe(e,14);this.r[0]=n&8191,this.r[1]=(n>>>13|r<<3)&8191,this.r[2]=(r>>>10|i<<6)&7939,this.r[3]=(i>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|u<<8)&8191,this.r[9]=u>>>5&127;for(let l=0;l<8;l++)this.pad[l]=Pe(e,16+2*l)}process(e,n,r=!1){const i=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],p=o[6],d=o[7],g=o[8],y=o[9],_=Pe(e,n+0),A=Pe(e,n+2),b=Pe(e,n+4),v=Pe(e,n+6),x=Pe(e,n+8),T=Pe(e,n+10),R=Pe(e,n+12),C=Pe(e,n+14);let m=s[0]+(_&8191),B=s[1]+((_>>>13|A<<3)&8191),S=s[2]+((A>>>10|b<<6)&8191),O=s[3]+((b>>>7|v<<9)&8191),P=s[4]+((v>>>4|x<<12)&8191),F=s[5]+(x>>>1&8191),E=s[6]+((x>>>14|T<<2)&8191),w=s[7]+((T>>>11|R<<5)&8191),I=s[8]+((R>>>8|C<<8)&8191),$=s[9]+(C>>>5|i),D=0,N=D+m*a+B*(5*y)+S*(5*g)+O*(5*d)+P*(5*p);D=N>>>13,N&=8191,N+=F*(5*f)+E*(5*h)+w*(5*l)+I*(5*u)+$*(5*c),D+=N>>>13,N&=8191;let U=D+m*c+B*a+S*(5*y)+O*(5*g)+P*(5*d);D=U>>>13,U&=8191,U+=F*(5*p)+E*(5*f)+w*(5*h)+I*(5*l)+$*(5*u),D+=U>>>13,U&=8191;let L=D+m*u+B*c+S*a+O*(5*y)+P*(5*g);D=L>>>13,L&=8191,L+=F*(5*d)+E*(5*p)+w*(5*f)+I*(5*h)+$*(5*l),D+=L>>>13,L&=8191;let j=D+m*l+B*u+S*c+O*a+P*(5*y);D=j>>>13,j&=8191,j+=F*(5*g)+E*(5*d)+w*(5*p)+I*(5*f)+$*(5*h),D+=j>>>13,j&=8191;let V=D+m*h+B*l+S*u+O*c+P*a;D=V>>>13,V&=8191,V+=F*(5*y)+E*(5*g)+w*(5*d)+I*(5*p)+$*(5*f),D+=V>>>13,V&=8191;let K=D+m*f+B*h+S*l+O*u+P*c;D=K>>>13,K&=8191,K+=F*a+E*(5*y)+w*(5*g)+I*(5*d)+$*(5*p),D+=K>>>13,K&=8191;let H=D+m*p+B*f+S*h+O*l+P*u;D=H>>>13,H&=8191,H+=F*c+E*a+w*(5*y)+I*(5*g)+$*(5*d),D+=H>>>13,H&=8191;let Z=D+m*d+B*p+S*f+O*h+P*l;D=Z>>>13,Z&=8191,Z+=F*u+E*c+w*a+I*(5*y)+$*(5*g),D+=Z>>>13,Z&=8191;let Q=D+m*g+B*d+S*p+O*f+P*h;D=Q>>>13,Q&=8191,Q+=F*l+E*u+w*c+I*a+$*(5*y),D+=Q>>>13,Q&=8191;let W=D+m*y+B*g+S*d+O*p+P*f;D=W>>>13,W&=8191,W+=F*h+E*l+w*u+I*c+$*a,D+=W>>>13,W&=8191,D=(D<<2)+D|0,D=D+N|0,N=D&8191,D=D>>>13,U+=D,s[0]=N,s[1]=U,s[2]=L,s[3]=j,s[4]=V,s[5]=K,s[6]=H,s[7]=Z,s[8]=Q,s[9]=W}finalize(){const{h:e,pad:n}=this,r=new Uint16Array(10);let i=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=i,i=e[a]>>>13,e[a]&=8191;e[0]+=i*5,i=e[0]>>>13,e[0]&=8191,e[1]+=i,i=e[1]>>>13,e[1]&=8191,e[2]+=i,r[0]=e[0]+5,i=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+i,i=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(i^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+n[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+n[a]|0)+(o>>>16)|0,e[a]=o&65535;Tr(r)}update(e){Vd(this),e=mc(e),tt(e);const{buffer:n,blockLen:r}=this,i=e.length;for(let s=0;s<i;){const o=Math.min(r-this.pos,i-s);if(o===r){for(;r<=i-s;s+=r)this.process(e,s);continue}n.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(n,0,!1),this.pos=0)}return this}destroy(){Tr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vd(this),H_(e,this),this.finished=!0;const{buffer:n,h:r}=this;let{pos:i}=this;if(i){for(n[i++]=1;i<16;i++)n[i]=0;this.process(n,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:n}=this;this.digestInto(e);const r=e.slice(0,n);return this.destroy(),r}}function u8(t){const e=(r,i)=>t(i).update(mc(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const l8=u8(t=>new c8(t));function h8(t,e,n,r,i,s=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],p=e[3],d=e[4],g=e[5],y=e[6],_=e[7],A=i,b=n[0],v=n[1],x=n[2],T=o,R=a,C=c,m=u,B=l,S=h,O=f,P=p,F=d,E=g,w=y,I=_,$=A,D=b,N=v,U=x;for(let j=0;j<s;j+=2)T=T+B|0,$=te($^T,16),F=F+$|0,B=te(B^F,12),T=T+B|0,$=te($^T,8),F=F+$|0,B=te(B^F,7),R=R+S|0,D=te(D^R,16),E=E+D|0,S=te(S^E,12),R=R+S|0,D=te(D^R,8),E=E+D|0,S=te(S^E,7),C=C+O|0,N=te(N^C,16),w=w+N|0,O=te(O^w,12),C=C+O|0,N=te(N^C,8),w=w+N|0,O=te(O^w,7),m=m+P|0,U=te(U^m,16),I=I+U|0,P=te(P^I,12),m=m+P|0,U=te(U^m,8),I=I+U|0,P=te(P^I,7),T=T+S|0,U=te(U^T,16),w=w+U|0,S=te(S^w,12),T=T+S|0,U=te(U^T,8),w=w+U|0,S=te(S^w,7),R=R+O|0,$=te($^R,16),I=I+$|0,O=te(O^I,12),R=R+O|0,$=te($^R,8),I=I+$|0,O=te(O^I,7),C=C+P|0,D=te(D^C,16),F=F+D|0,P=te(P^F,12),C=C+P|0,D=te(D^C,8),F=F+D|0,P=te(P^F,7),m=m+B|0,N=te(N^m,16),E=E+N|0,B=te(B^E,12),m=m+B|0,N=te(N^m,8),E=E+N|0,B=te(B^E,7);let L=0;r[L++]=o+T|0,r[L++]=a+R|0,r[L++]=c+C|0,r[L++]=u+m|0,r[L++]=l+B|0,r[L++]=h+S|0,r[L++]=f+O|0,r[L++]=p+P|0,r[L++]=d+F|0,r[L++]=g+E|0,r[L++]=y+w|0,r[L++]=_+I|0,r[L++]=A+$|0,r[L++]=b+D|0,r[L++]=v+N|0,r[L++]=x+U|0}const f8=a8(h8,{counterRight:!1,counterLength:4,allowShortKeys:!1}),d8=new Uint8Array(16),Zd=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(d8.subarray(n))},p8=new Uint8Array(32);function Jd(t,e,n,r,i){const s=t(e,n,p8),o=l8.create(s);i&&Zd(o,i),Zd(o,r);const a=Q_(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Tr(s,a),c}const g8=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=Kd(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Jd(t,e,n,a,r);return s.set(c,o),Tr(c),s},decrypt(i,s){s=Kd(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Jd(t,e,n,o,r);if(!J_(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Tr(c),s}}),Xd=X_({blockSize:64,nonceLength:12,tagLength:16},g8(f8));class Qd extends qs{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,ac(e);const r=Ct(n);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const i=this.blockLen,s=new Uint8Array(i);s.set(r.length>i?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Et(s)}update(e){return $n(this),this.iHash.update(e),this}digestInto(e){$n(this),vt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:n,iHash:r,finished:i,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=i,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=n._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const Ws=(t,e,n)=>new Qd(t,e).update(n).digest();Ws.create=(t,e)=>new Qd(t,e);function y8(t,e,n){return ac(t),n===void 0&&(n=new Uint8Array(t.outputLen)),Ws(t,Ct(n),Ct(e))}const Ec=Uint8Array.from([0]),ep=Uint8Array.of();function w8(t,e,n,r=32){ac(t),rn(r);const i=t.outputLen;if(r>255*i)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/i);n===void 0&&(n=ep);const o=new Uint8Array(s*i),a=Ws.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Ec[0]=l+1,c.update(l===0?ep:u).update(n).update(Ec).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),Et(u,Ec),o.slice(0,r)}const m8=(t,e,n,r,i)=>w8(t,y8(t,e,n),r,i),Gs=js,xc=BigInt(0),_c=BigInt(1);function Ys(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Zs(t){const e=t.toString(16);return e.length&1?"0"+e:e}function tp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xc:BigInt("0x"+t)}function Js(t){return tp(Ii(t))}function Xs(t){return vt(t),tp(Ii(Uint8Array.from(t).reverse()))}function Ic(t,e){return lc(t.toString(16).padStart(e*2,"0"))}function Sc(t,e){return Ic(t,e).reverse()}function nt(t,e,n){let r;if(typeof e=="string")try{r=lc(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(oc(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const i=r.length;if(typeof n=="number"&&i!==n)throw new Error(t+" of length "+n+" expected, got "+i);return r}const Ac=t=>typeof t=="bigint"&&xc<=t;function b8(t,e,n){return Ac(t)&&Ac(e)&&Ac(n)&&e<=t&&t<n}function Dc(t,e,n,r){if(!b8(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function v8(t){let e;for(e=0;t>xc;t>>=_c,e+=1);return e}const Qs=t=>(_c<<BigInt(t))-_c;function E8(t,e,n){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof n!="function")throw new Error("hmacFn must be a function");const r=f=>new Uint8Array(f),i=f=>Uint8Array.of(f);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},u=(...f)=>n(o,s,...f),l=(f=r(0))=>{o=u(i(0),f),s=u(),f.length!==0&&(o=u(i(1),f),s=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){s=u();const d=s.slice();p.push(d),f+=s.length}return sr(...p)};return(f,p)=>{c(),l(f);let d;for(;!(d=p(h()));)l();return c(),d}}function eo(t,e,n={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(i,s,o){const a=t[i];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${i}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([i,s])=>r(i,s,!1)),Object.entries(n).forEach(([i,s])=>r(i,s,!0))}function np(t){const e=new WeakMap;return(n,...r)=>{const i=e.get(n);if(i!==void 0)return i;const s=t(n,...r);return e.set(n,s),s}}const rt=BigInt(0),Ge=BigInt(1),ar=BigInt(2),x8=BigInt(3),rp=BigInt(4),ip=BigInt(5),sp=BigInt(8);function xt(t,e){const n=t%e;return n>=rt?n:e+n}function Rt(t,e,n){let r=t;for(;e-- >rt;)r*=r,r%=n;return r}function op(t,e){if(t===rt)throw new Error("invert: expected non-zero number");if(e<=rt)throw new Error("invert: expected positive modulus, got "+e);let n=xt(t,e),r=e,i=rt,s=Ge;for(;n!==rt;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==Ge)throw new Error("invert: does not exist");return xt(i,e)}function ap(t,e){const n=(t.ORDER+Ge)/rp,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function _8(t,e){const n=(t.ORDER-ip)/sp,r=t.mul(e,ar),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,ar),i),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function I8(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ge,n=0;for(;e%ar===rt;)e/=ar,n++;let r=ar;const i=Br(t);for(;up(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return ap;let s=i.pow(r,e);const o=(e+Ge)/ar;return function(a,c){if(a.is0(c))return c;if(up(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let p=1,d=a.sqr(h);for(;!a.eql(d,a.ONE);)if(p++,d=a.sqr(d),p===u)throw new Error("Cannot find square root");const g=Ge<<BigInt(u-p-1),y=a.pow(l,g);u=p,l=a.sqr(y),h=a.mul(h,l),f=a.mul(f,y)}return f}}function S8(t){return t%rp===x8?ap:t%sp===ip?_8:I8(t)}const A8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function D8(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=A8.reduce((r,i)=>(r[i]="function",r),e);return eo(t,n),t}function O8(t,e,n){if(n<rt)throw new Error("invalid exponent, negatives unsupported");if(n===rt)return t.ONE;if(n===Ge)return e;let r=t.ONE,i=e;for(;n>rt;)n&Ge&&(r=t.mul(r,i)),i=t.sqr(i),n>>=Ge;return r}function cp(t,e,n=!1){const r=new Array(e.length).fill(n?t.ZERO:void 0),i=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(i);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function up(t,e){const n=(t.ORDER-Ge)/ar,r=t.pow(e,n),i=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!i&&!s&&!o)throw new Error("invalid Legendre symbol result");return i?1:s?0:-1}function $8(t,e){e!==void 0&&rn(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Br(t,e,n=!1,r={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let i,s;if(typeof e=="object"&&e!=null){if(r.sqrt||n)throw new Error("cannot specify opts in two arguments");const l=e;l.BITS&&(i=l.BITS),l.sqrt&&(s=l.sqrt),typeof l.isLE=="boolean"&&(n=l.isLE)}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:o,nByteLength:a}=$8(t,i);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let c;const u=Object.freeze({ORDER:t,isLE:n,BITS:o,BYTES:a,MASK:Qs(o),ZERO:rt,ONE:Ge,create:l=>xt(l,t),isValid:l=>{if(typeof l!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof l);return rt<=l&&l<t},is0:l=>l===rt,isValidNot0:l=>!u.is0(l)&&u.isValid(l),isOdd:l=>(l&Ge)===Ge,neg:l=>xt(-l,t),eql:(l,h)=>l===h,sqr:l=>xt(l*l,t),add:(l,h)=>xt(l+h,t),sub:(l,h)=>xt(l-h,t),mul:(l,h)=>xt(l*h,t),pow:(l,h)=>O8(u,l,h),div:(l,h)=>xt(l*op(h,t),t),sqrN:l=>l*l,addN:(l,h)=>l+h,subN:(l,h)=>l-h,mulN:(l,h)=>l*h,inv:l=>op(l,t),sqrt:s||(l=>(c||(c=S8(t)),c(u,l))),toBytes:l=>n?Sc(l,a):Ic(l,a),fromBytes:l=>{if(l.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+l.length);return n?Xs(l):Js(l)},invertBatch:l=>cp(u,l),cmov:(l,h,f)=>f?h:l});return Object.freeze(u)}function lp(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function hp(t){const e=lp(t);return e+Math.ceil(e/2)}function T8(t,e,n=!1){const r=t.length,i=lp(e),s=hp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?Xs(t):Js(t),a=xt(o,e-Ge)+Ge;return n?Sc(a,i):Ic(a,i)}const Pr=BigInt(0),cr=BigInt(1);function Oi(t,e){const n=e.negate();return t?n:e}function B8(t,e,n){const r=e==="pz"?s=>s.pz:s=>s.ez,i=cp(t.Fp,n.map(r));return n.map((s,o)=>s.toAffine(i[o])).map(t.fromAffine)}function fp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Oc(t,e){fp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Qs(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function dp(t,e,n){const{windowSize:r,mask:i,maxNumber:s,shiftBy:o}=n;let a=Number(t&i),c=t>>o;a>r&&(a-=s,c+=cr);const u=e*r,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function P8(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((n,r)=>{if(!(n instanceof e))throw new Error("invalid point at index "+r)})}function C8(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((n,r)=>{if(!e.isValid(n))throw new Error("invalid scalar at index "+r)})}const $c=new WeakMap,pp=new WeakMap;function Tc(t){return pp.get(t)||1}function gp(t){if(t!==Pr)throw new Error("invalid wNAF")}function R8(t,e){return{constTimeNegate:Oi,hasPrecomputes(n){return Tc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Pr;)r&cr&&(i=i.add(s)),s=s.double(),r>>=cr;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=Oc(r,e),o=[];let a=n,c=a;for(let u=0;u<i;u++){c=a,o.push(c);for(let l=1;l<s;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(n,r,i){let s=t.ZERO,o=t.BASE;const a=Oc(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:d}=dp(i,c,a);i=u,h?o=o.add(Oi(p,r[d])):s=s.add(Oi(f,r[l]))}return gp(i),{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=Oc(n,e);for(let a=0;a<o.windows&&i!==Pr;a++){const{nextN:c,offset:u,isZero:l,isNeg:h}=dp(i,a,o);if(i=c,!l){const f=r[u];s=s.add(h?f.negate():f)}}return gp(i),s},getPrecomputes(n,r,i){let s=$c.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&(typeof i=="function"&&(s=i(s)),$c.set(r,s))),s},wNAFCached(n,r,i){const s=Tc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Tc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){fp(r,e),pp.set(n,r),$c.delete(n)}}}function N8(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Pr||r>Pr;)n&cr&&(s=s.add(i)),r&cr&&(o=o.add(i)),i=i.double(),n>>=cr,r>>=cr;return{p1:s,p2:o}}function U8(t,e,n,r){P8(n,t),C8(r,e);const i=n.length,s=r.length;if(i!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=v8(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Qs(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let g=0;g<s;g++){const y=r[g],_=Number(y>>BigInt(p)&u);l[_]=l[_].add(n[g])}let d=o;for(let g=l.length-1,y=o;g>0;g--)y=y.add(l[g]),d=d.add(y);if(f=f.add(d),p!==0)for(let g=0;g<c;g++)f=f.double()}return f}function yp(t,e){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return D8(e),e}else return Br(t)}function F8(t,e,n={}){if(!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const o of["p","n","h"]){const a=e[o];if(!(typeof a=="bigint"&&a>Pr))throw new Error(`CURVE.${o} must be positive bigint`)}const r=yp(e.p,n.Fp),i=yp(e.n,n.Fn),s=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const o of s)if(!r.isValid(e[o]))throw new Error(`CURVE.${o} must be valid field element of CURVE.Fp`);return{Fp:r,Fn:i}}BigInt(0),BigInt(1),BigInt(2),BigInt(8);const $i=BigInt(0),Cr=BigInt(1),to=BigInt(2);function k8(t){return eo(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function L8(t){const e=k8(t),{P:n,type:r,adjustScalarBytes:i,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||$r,u=a?255:448,l=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?to**BigInt(254):to**BigInt(447),d=a?BigInt(8)*to**BigInt(251)-Cr:BigInt(4)*to**BigInt(445)-Cr,g=p+d+Cr,y=m=>xt(m,n),_=A(h);function A(m){return Sc(y(m),l)}function b(m){const B=nt("u coordinate",m,l);return a&&(B[31]&=127),y(Xs(B))}function v(m){return Xs(i(nt("scalar",m,l)))}function x(m,B){const S=C(b(B),v(m));if(S===$i)throw new Error("invalid private or public key received");return A(S)}function T(m){return x(m,_)}function R(m,B,S){const O=y(m*(B-S));return B=y(B-O),S=y(S+O),{x_2:B,x_3:S}}function C(m,B){Dc("u",m,$i,n),Dc("scalar",B,p,g);const S=B,O=m;let P=Cr,F=$i,E=m,w=Cr,I=$i;for(let D=BigInt(u-1);D>=$i;D--){const N=S>>D&Cr;I^=N,{x_2:P,x_3:E}=R(I,P,E),{x_2:F,x_3:w}=R(I,F,w),I=N;const U=P+F,L=y(U*U),j=P-F,V=y(j*j),K=L-V,H=E+w,Z=E-w,Q=y(Z*U),W=y(H*j),ae=Q+W,ye=Q-W;E=y(ae*ae),w=y(O*y(ye*ye)),P=y(L*V),F=y(K*(L+y(f*K)))}({x_2:P,x_3:E}=R(I,P,E)),{x_2:F,x_3:w}=R(I,F,w);const $=s(F);return y(P*$)}return{scalarMult:x,scalarMultBase:T,getSharedSecret:(m,B)=>x(m,B),getPublicKey:m=>T(m),utils:{randomPrivateKey:()=>c(l)},GuBytes:_.slice()}}BigInt(0);const M8=BigInt(1),wp=BigInt(2),z8=BigInt(3),q8=BigInt(5),j8=BigInt(8),mp={p:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:j8,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function V8(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=mp.p,o=t*t%s*t%s,a=Rt(o,wp,s)*o%s,c=Rt(a,M8,s)*t%s,u=Rt(c,q8,s)*c%s,l=Rt(u,e,s)*u%s,h=Rt(l,n,s)*l%s,f=Rt(h,r,s)*h%s,p=Rt(f,i,s)*f%s,d=Rt(p,i,s)*f%s,g=Rt(d,e,s)*u%s;return{pow_p_5_8:Rt(g,wp,s)*t%s,b2:o}}function K8(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const Bc=(()=>{const t=mp.p;return L8({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=V8(e);return xt(Rt(n,z8,t)*r,t)},adjustScalarBytes:K8})})();function bp(t){t.lowS!==void 0&&Ys("lowS",t.lowS),t.prehash!==void 0&&Ys("prehash",t.prehash)}class H8 extends Error{constructor(e=""){super(e)}}const an={Err:H8,_tlv:{encode:(t,e)=>{const{Err:n}=an;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length&1)throw new n("tlv.encode: unpadded data");const r=e.length/2,i=Zs(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Zs(i.length/2|128):"";return Zs(t)+s+i+e},decode(t,e){const{Err:n}=an;let r=0;if(t<0||t>256)throw new n("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new n("tlv.decode: wrong tlv");const i=e[r++],s=!!(i&128);let o=0;if(!s)o=i;else{const c=i&127;if(!c)throw new n("tlv.decode(long): indefinite length not supported");if(c>4)throw new n("tlv.decode(long): byte length is too big");const u=e.subarray(r,r+c);if(u.length!==c)throw new n("tlv.decode: length bytes not complete");if(u[0]===0)throw new n("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(r+=c,o<128)throw new n("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new n("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=an;if(t<Ti)throw new e("integer: negative integers are not allowed");let n=Zs(t);if(Number.parseInt(n[0],16)&8&&(n="00"+n),n.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return n},decode(t){const{Err:e}=an;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return Js(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=an,i=nt("signature",t),{v:s,l:o}=r.decode(48,i);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:u,l}=r.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:n.decode(a),s:n.decode(u)}},hexFromSig(t){const{_tlv:e,_int:n}=an,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Ti=BigInt(0),Bi=BigInt(1),W8=BigInt(2),no=BigInt(3),G8=BigInt(4);function Y8(t,e,n){function r(i){const s=t.sqr(i),o=t.mul(s,i);return t.add(t.add(o,t.mul(i,e)),n)}return r}function vp(t,e,n){const{BYTES:r}=t;function i(s){let o;if(typeof s=="bigint")o=s;else{let a=nt("private key",s);if(e){if(!e.includes(a.length*2))throw new Error("invalid private key");const c=new Uint8Array(r);c.set(a,c.length-a.length),a=c}try{o=t.fromBytes(a)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof s}`)}}if(n&&(o=t.create(o)),!t.isValidNot0(o))throw new Error("invalid private key: out of range [1..N-1]");return o}return i}function Z8(t,e={}){const{Fp:n,Fn:r}=F8("weierstrass",t,e),{h:i,n:s}=t;eo(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:o}=e;if(o&&(!n.is0(t.a)||typeof o.beta!="bigint"||typeof o.splitScalar!="function"))throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function');function a(){if(!n.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function c(C,m,B){const{x:S,y:O}=m.toAffine(),P=n.toBytes(S);if(Ys("isCompressed",B),B){a();const F=!n.isOdd(O);return sr(Ep(F),P)}else return sr(Uint8Array.of(4),P,n.toBytes(O))}function u(C){vt(C);const m=n.BYTES,B=m+1,S=2*m+1,O=C.length,P=C[0],F=C.subarray(1);if(O===B&&(P===2||P===3)){const E=n.fromBytes(F);if(!n.isValid(E))throw new Error("bad point: is not on curve, wrong x");const w=f(E);let I;try{I=n.sqrt(w)}catch(D){const N=D instanceof Error?": "+D.message:"";throw new Error("bad point: is not on curve, sqrt error"+N)}a();const $=n.isOdd(I);return(P&1)===1!==$&&(I=n.neg(I)),{x:E,y:I}}else if(O===S&&P===4){const E=n.fromBytes(F.subarray(m*0,m*1)),w=n.fromBytes(F.subarray(m*1,m*2));if(!p(E,w))throw new Error("bad point: is not on curve");return{x:E,y:w}}else throw new Error(`bad point: got length ${O}, expected compressed=${B} or uncompressed=${S}`)}const l=e.toBytes||c,h=e.fromBytes||u,f=Y8(n,t.a,t.b);function p(C,m){const B=n.sqr(m),S=f(C);return n.eql(B,S)}if(!p(t.Gx,t.Gy))throw new Error("bad curve params: generator point");const d=n.mul(n.pow(t.a,no),G8),g=n.mul(n.sqr(t.b),BigInt(27));if(n.is0(n.add(d,g)))throw new Error("bad curve params: a or b");function y(C,m,B=!1){if(!n.isValid(m)||B&&n.is0(m))throw new Error(`bad point coordinate ${C}`);return m}function _(C){if(!(C instanceof x))throw new Error("ProjectivePoint expected")}const A=np((C,m)=>{const{px:B,py:S,pz:O}=C;if(n.eql(O,n.ONE))return{x:B,y:S};const P=C.is0();m==null&&(m=P?n.ONE:n.inv(O));const F=n.mul(B,m),E=n.mul(S,m),w=n.mul(O,m);if(P)return{x:n.ZERO,y:n.ZERO};if(!n.eql(w,n.ONE))throw new Error("invZ was invalid");return{x:F,y:E}}),b=np(C=>{if(C.is0()){if(e.allowInfinityPoint&&!n.is0(C.py))return;throw new Error("bad point: ZERO")}const{x:m,y:B}=C.toAffine();if(!n.isValid(m)||!n.isValid(B))throw new Error("bad point: x or y not field elements");if(!p(m,B))throw new Error("bad point: equation left != right");if(!C.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function v(C,m,B,S,O){return B=new x(n.mul(B.px,C),B.py,B.pz),m=Oi(S,m),B=Oi(O,B),m.add(B)}class x{constructor(m,B,S){this.px=y("x",m),this.py=y("y",B,!0),this.pz=y("z",S),Object.freeze(this)}static fromAffine(m){const{x:B,y:S}=m||{};if(!m||!n.isValid(B)||!n.isValid(S))throw new Error("invalid affine point");if(m instanceof x)throw new Error("projective point not allowed");return n.is0(B)&&n.is0(S)?x.ZERO:new x(B,S,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(m){return B8(x,"pz",m)}static fromBytes(m){return vt(m),x.fromHex(m)}static fromHex(m){const B=x.fromAffine(h(nt("pointHex",m)));return B.assertValidity(),B}static fromPrivateKey(m){const B=vp(r,e.allowedPrivateKeyLengths,e.wrapPrivateKey);return x.BASE.multiply(B(m))}static msm(m,B){return U8(x,r,m,B)}precompute(m=8,B=!0){return R.setWindowSize(this,m),B||this.multiply(no),this}_setWindowSize(m){this.precompute(m)}assertValidity(){b(this)}hasEvenY(){const{y:m}=this.toAffine();if(!n.isOdd)throw new Error("Field doesn't support isOdd");return!n.isOdd(m)}equals(m){_(m);const{px:B,py:S,pz:O}=this,{px:P,py:F,pz:E}=m,w=n.eql(n.mul(B,E),n.mul(P,O)),I=n.eql(n.mul(S,E),n.mul(F,O));return w&&I}negate(){return new x(this.px,n.neg(this.py),this.pz)}double(){const{a:m,b:B}=t,S=n.mul(B,no),{px:O,py:P,pz:F}=this;let E=n.ZERO,w=n.ZERO,I=n.ZERO,$=n.mul(O,O),D=n.mul(P,P),N=n.mul(F,F),U=n.mul(O,P);return U=n.add(U,U),I=n.mul(O,F),I=n.add(I,I),E=n.mul(m,I),w=n.mul(S,N),w=n.add(E,w),E=n.sub(D,w),w=n.add(D,w),w=n.mul(E,w),E=n.mul(U,E),I=n.mul(S,I),N=n.mul(m,N),U=n.sub($,N),U=n.mul(m,U),U=n.add(U,I),I=n.add($,$),$=n.add(I,$),$=n.add($,N),$=n.mul($,U),w=n.add(w,$),N=n.mul(P,F),N=n.add(N,N),$=n.mul(N,U),E=n.sub(E,$),I=n.mul(N,D),I=n.add(I,I),I=n.add(I,I),new x(E,w,I)}add(m){_(m);const{px:B,py:S,pz:O}=this,{px:P,py:F,pz:E}=m;let w=n.ZERO,I=n.ZERO,$=n.ZERO;const D=t.a,N=n.mul(t.b,no);let U=n.mul(B,P),L=n.mul(S,F),j=n.mul(O,E),V=n.add(B,S),K=n.add(P,F);V=n.mul(V,K),K=n.add(U,L),V=n.sub(V,K),K=n.add(B,O);let H=n.add(P,E);return K=n.mul(K,H),H=n.add(U,j),K=n.sub(K,H),H=n.add(S,O),w=n.add(F,E),H=n.mul(H,w),w=n.add(L,j),H=n.sub(H,w),$=n.mul(D,K),w=n.mul(N,j),$=n.add(w,$),w=n.sub(L,$),$=n.add(L,$),I=n.mul(w,$),L=n.add(U,U),L=n.add(L,U),j=n.mul(D,j),K=n.mul(N,K),L=n.add(L,j),j=n.sub(U,j),j=n.mul(D,j),K=n.add(K,j),U=n.mul(L,K),I=n.add(I,U),U=n.mul(H,K),w=n.mul(V,w),w=n.sub(w,U),U=n.mul(V,L),$=n.mul(H,$),$=n.add($,U),new x(w,I,$)}subtract(m){return this.add(m.negate())}is0(){return this.equals(x.ZERO)}multiply(m){const{endo:B}=e;if(!r.isValidNot0(m))throw new Error("invalid scalar: out of range");let S,O;const P=F=>R.wNAFCached(this,F,x.normalizeZ);if(B){const{k1neg:F,k1:E,k2neg:w,k2:I}=B.splitScalar(m),{p:$,f:D}=P(E),{p:N,f:U}=P(I);O=D.add(U),S=v(B.beta,$,N,F,w)}else{const{p:F,f:E}=P(m);S=F,O=E}return x.normalizeZ([S,O])[0]}multiplyUnsafe(m){const{endo:B}=e,S=this;if(!r.isValid(m))throw new Error("invalid scalar: out of range");if(m===Ti||S.is0())return x.ZERO;if(m===Bi)return S;if(R.hasPrecomputes(this))return this.multiply(m);if(B){const{k1neg:O,k1:P,k2neg:F,k2:E}=B.splitScalar(m),{p1:w,p2:I}=N8(x,S,P,E);return v(B.beta,w,I,O,F)}else return R.wNAFCachedUnsafe(S,m)}multiplyAndAddUnsafe(m,B,S){const O=this.multiplyUnsafe(B).add(m.multiplyUnsafe(S));return O.is0()?void 0:O}toAffine(m){return A(this,m)}isTorsionFree(){const{isTorsionFree:m}=e;return i===Bi?!0:m?m(x,this):R.wNAFCachedUnsafe(this,s).is0()}clearCofactor(){const{clearCofactor:m}=e;return i===Bi?this:m?m(x,this):this.multiplyUnsafe(i)}toBytes(m=!0){return Ys("isCompressed",m),this.assertValidity(),l(x,this,m)}toRawBytes(m=!0){return this.toBytes(m)}toHex(m=!0){return Ii(this.toBytes(m))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}}x.BASE=new x(t.Gx,t.Gy,n.ONE),x.ZERO=new x(n.ZERO,n.ONE,n.ZERO),x.Fp=n,x.Fn=r;const T=r.BITS,R=R8(x,e.endo?Math.ceil(T/2):T);return x}function Ep(t){return Uint8Array.of(t?2:3)}function J8(t,e,n={}){eo(e,{hash:"function"},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=e.randomBytes||$r,i=e.hmac||((S,...O)=>Ws(e.hash,S,sr(...O))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o;function u(S){const O=a>>Bi;return S>O}function l(S){return u(S)?o.neg(S):S}function h(S,O){if(!o.isValidNot0(O))throw new Error(`invalid signature ${S}: out of range 1..CURVE.n`)}class f{constructor(O,P,F){h("r",O),h("s",P),this.r=O,this.s=P,F!=null&&(this.recovery=F),Object.freeze(this)}static fromCompact(O){const P=o.BYTES,F=nt("compactSignature",O,P*2);return new f(o.fromBytes(F.subarray(0,P)),o.fromBytes(F.subarray(P,P*2)))}static fromDER(O){const{r:P,s:F}=an.toSig(nt("DER",O));return new f(P,F)}assertValidity(){}addRecoveryBit(O){return new f(this.r,this.s,O)}recoverPublicKey(O){const P=s.ORDER,{r:F,s:E,recovery:w}=this;if(w==null||![0,1,2,3].includes(w))throw new Error("recovery id invalid");if(a*W8<P&&w>1)throw new Error("recovery id is ambiguous for h>1 curve");const I=w===2||w===3?F+a:F;if(!s.isValid(I))throw new Error("recovery id 2 or 3 invalid");const $=s.toBytes(I),D=t.fromHex(sr(Ep((w&1)===0),$)),N=o.inv(I),U=b(nt("msgHash",O)),L=o.create(-U*N),j=o.create(E*N),V=t.BASE.multiplyUnsafe(L).add(D.multiplyUnsafe(j));if(V.is0())throw new Error("point at infinify");return V.assertValidity(),V}hasHighS(){return u(this.s)}normalizeS(){return this.hasHighS()?new f(this.r,o.neg(this.s),this.recovery):this}toBytes(O){if(O==="compact")return sr(o.toBytes(this.r),o.toBytes(this.s));if(O==="der")return lc(an.hexFromSig(this));throw new Error("invalid format")}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ii(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ii(this.toBytes("compact"))}}const p=vp(o,n.allowedPrivateKeyLengths,n.wrapPrivateKey),d={isValidPrivateKey(S){try{return p(S),!0}catch{return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{const S=a;return T8(r(hp(S)),S)},precompute(S=8,O=t.BASE){return O.precompute(S,!1)}};function g(S,O=!0){return t.fromPrivateKey(S).toBytes(O)}function y(S){if(typeof S=="bigint")return!1;if(S instanceof t)return!0;const O=nt("key",S).length,P=s.BYTES,F=P+1,E=2*P+1;if(!(n.allowedPrivateKeyLengths||o.BYTES===F))return O===F||O===E}function _(S,O,P=!0){if(y(S)===!0)throw new Error("first arg must be private key");if(y(O)===!1)throw new Error("second arg must be public key");return t.fromHex(O).multiply(p(S)).toBytes(P)}const A=e.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");const O=Js(S),P=S.length*8-c;return P>0?O>>BigInt(P):O},b=e.bits2int_modN||function(S){return o.create(A(S))},v=Qs(c);function x(S){return Dc("num < 2^"+c,S,Ti,v),o.toBytes(S)}function T(S,O,P=R){if(["recovered","canonical"].some(V=>V in P))throw new Error("sign() legacy options not supported");const{hash:F}=e;let{lowS:E,prehash:w,extraEntropy:I}=P;E==null&&(E=!0),S=nt("msgHash",S),bp(P),w&&(S=nt("prehashed msgHash",F(S)));const $=b(S),D=p(O),N=[x(D),x($)];if(I!=null&&I!==!1){const V=I===!0?r(s.BYTES):I;N.push(nt("extraEntropy",V))}const U=sr(...N),L=$;function j(V){const K=A(V);if(!o.isValidNot0(K))return;const H=o.inv(K),Z=t.BASE.multiply(K).toAffine(),Q=o.create(Z.x);if(Q===Ti)return;const W=o.create(H*o.create(L+Q*D));if(W===Ti)return;let ae=(Z.x===Q?0:2)|Number(Z.y&Bi),ye=W;return E&&u(W)&&(ye=l(W),ae^=1),new f(Q,ye,ae)}return{seed:U,k2sig:j}}const R={lowS:e.lowS,prehash:!1},C={lowS:e.lowS,prehash:!1};function m(S,O,P=R){const{seed:F,k2sig:E}=T(S,O,P);return E8(e.hash.outputLen,o.BYTES,i)(F,E)}t.BASE.precompute(8);function B(S,O,P,F=C){const E=S;O=nt("msgHash",O),P=nt("publicKey",P),bp(F);const{lowS:w,prehash:I,format:$}=F;if("strict"in F)throw new Error("options.strict was renamed to lowS");if($!==void 0&&!["compact","der","js"].includes($))throw new Error('format must be "compact", "der" or "js"');const D=typeof E=="string"||oc(E),N=!D&&!$&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!D&&!N)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let U,L;try{if(N)if($===void 0||$==="js")U=new f(E.r,E.s);else throw new Error("invalid format");if(D){try{$!=="compact"&&(U=f.fromDER(E))}catch(ae){if(!(ae instanceof an.Err))throw ae}!U&&$!=="der"&&(U=f.fromCompact(E))}L=t.fromHex(P)}catch{return!1}if(!U||w&&U.hasHighS())return!1;I&&(O=e.hash(O));const{r:j,s:V}=U,K=b(O),H=o.inv(V),Z=o.create(K*H),Q=o.create(j*H),W=t.BASE.multiplyUnsafe(Z).add(L.multiplyUnsafe(Q));return W.is0()?!1:o.create(W.x)===j}return Object.freeze({getPublicKey:g,getSharedSecret:_,sign:m,verify:B,utils:d,Point:t,Signature:f})}function X8(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},n=t.Fp,r=Br(e.n,t.nBitLength),i={Fp:n,Fn:r,allowedPrivateKeyLengths:t.allowedPrivateKeyLengths,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,wrapPrivateKey:t.wrapPrivateKey,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:i}}function Q8(t){const{CURVE:e,curveOpts:n}=X8(t),r={hash:t.hash,hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:n,ecdsaOpts:r}}function eI(t,e){return Object.assign({},e,{ProjectivePoint:e.Point,CURVE:t})}function tI(t){const{CURVE:e,curveOpts:n,ecdsaOpts:r}=Q8(t),i=Z8(e,n),s=J8(i,r,n);return eI(t,s)}function Pc(t,e){const n=r=>tI({...t,hash:r});return{...n(e),create:n}}const xp={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},_p={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},Ip={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},nI=Br(xp.p),rI=Br(_p.p),iI=Br(Ip.p),sI=Pc({...xp,Fp:nI,lowS:!1},js);Pc({..._p,Fp:rI,lowS:!1},f_),Pc({...Ip,Fp:iI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},h_);const oI=sI,Sp="base10",Ye="base16",it="base64pad",kn="base64url",Pi="utf8",Ap=0,cn=1,Ci=2,aI=0,Dp=1,Ri=12,Cc=32;function cI(){const t=Bc.utils.randomPrivateKey(),e=Bc.getPublicKey(t);return{privateKey:et(t,Ye),publicKey:et(e,Ye)}}function Rc(){const t=$r(Cc);return et(t,Ye)}function uI(t,e){const n=Bc.getSharedSecret(bt(t,Ye),bt(e,Ye)),r=m8(Gs,n,void 0,void 0,Cc);return et(r,Ye)}function ro(t){const e=Gs(bt(t,Ye));return et(e,Ye)}function _t(t){const e=Gs(bt(t,Pi));return et(e,Ye)}function Op(t){return bt(`${t}`,Sp)}function ur(t){return Number(et(t,Sp))}function $p(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Tp(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function lI(t){const e=Op(typeof t.type<"u"?t.type:Ap);if(ur(e)===cn&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?bt(t.senderPublicKey,Ye):void 0,r=typeof t.iv<"u"?bt(t.iv,Ye):$r(Ri),i=bt(t.symKey,Ye),s=Xd(i,r).encrypt(bt(t.message,Pi)),o=Bp({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===kn?$p(o):o}function hI(t){const e=bt(t.symKey,Ye),{sealed:n,iv:r}=Ni({encoded:t.encoded,encoding:t.encoding}),i=Xd(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return et(i,Pi)}function fI(t,e){const n=Op(Ci),r=$r(Ri),i=bt(t,Pi),s=Bp({type:n,sealed:i,iv:r});return e===kn?$p(s):s}function dI(t,e){const{sealed:n}=Ni({encoded:t,encoding:e});return et(n,Pi)}function Bp(t){if(ur(t.type)===Ci)return et(gi([t.type,t.sealed]),it);if(ur(t.type)===cn){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return et(gi([t.type,t.senderPublicKey,t.iv,t.sealed]),it)}return et(gi([t.type,t.iv,t.sealed]),it)}function Ni(t){const e=(t.encoding||it)===kn?Tp(t.encoded):t.encoded,n=bt(e,it),r=n.slice(aI,Dp),i=Dp;if(ur(r)===cn){const c=i+Cc,u=c+Ri,l=n.slice(i,c),h=n.slice(c,u),f=n.slice(u);return{type:r,sealed:f,iv:h,senderPublicKey:l}}if(ur(r)===Ci){const c=n.slice(i),u=$r(Ri);return{type:r,sealed:c,iv:u}}const s=i+Ri,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function pI(t,e){const n=Ni({encoded:t,encoding:e?.encoding});return Pp({type:ur(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?et(n.senderPublicKey,Ye):void 0,receiverPublicKey:e?.receiverPublicKey})}function Pp(t){const e=t?.type||Ap;if(e===cn){if(typeof t?.senderPublicKey>"u")throw new Error("missing sender public key");if(typeof t?.receiverPublicKey>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t?.senderPublicKey,receiverPublicKey:t?.receiverPublicKey}}function Cp(t){return t.type===cn&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function Rp(t){return t.type===Ci}function gI(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return gi([new Uint8Array([4]),e,n])}function yI(t,e){const[n,r,i]=t.split("."),s=Buffer.from(Tp(i),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${n}.${r}`,u=Gs(c),l=gI(e);if(!oI.verify(gi([o,a]),u,l))throw new Error("Invalid signature");return Qo(t).payload}const wI="irn";function io(t){return t?.relay||{protocol:wI}}function Rr(t){const e=H3[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}function mI(t,e="-"){const n={},r="relay"+e;return Object.keys(t).forEach(i=>{if(i.startsWith(r)){const s=i.replace(r,""),o=t[i];n[s]=o}}),n}function Np(t){if(!t.includes("wc:")){const u=gd(t);u!=null&&u.includes("wc:")&&(t=u)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),n=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),i=t.substring(e+1,n).split("@"),s=typeof n<"u"?t.substring(n):"",o=new URLSearchParams(s),a={};o.forEach((u,l)=>{a[l]=u});const c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:bI(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:mI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function bI(t){return t.startsWith("//")?t.substring(2):t}function vI(t,e="-"){const n="relay",r={};return Object.keys(t).forEach(i=>{const s=i,o=n+e+s;t[s]&&(r[o]=t[s])}),r}function Up(t){const e=new URLSearchParams,n=vI(t.relay);Object.keys(n).sort().forEach(i=>{e.set(i,n[i])}),e.set("symKey",t.symKey),t.expiryTimestamp&&e.set("expiryTimestamp",t.expiryTimestamp.toString()),t.methods&&e.set("methods",t.methods.join(","));const r=e.toString();return`${t.protocol}:${t.topic}@${t.version}?${r}`}function so(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var EI=Object.defineProperty,xI=Object.defineProperties,_I=Object.getOwnPropertyDescriptors,Fp=Object.getOwnPropertySymbols,II=Object.prototype.hasOwnProperty,SI=Object.prototype.propertyIsEnumerable,kp=(t,e,n)=>e in t?EI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,AI=(t,e)=>{for(var n in e||(e={}))II.call(e,n)&&kp(t,n,e[n]);if(Fp)for(var n of Fp(e))SI.call(e,n)&&kp(t,n,e[n]);return t},DI=(t,e)=>xI(t,_I(e));function Nr(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function OI(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Nr(n.accounts))}),e}function $I(t,e){const n=[];return Object.values(t).forEach(r=>{Nr(r.accounts).includes(e)&&n.push(...r.methods)}),n}function TI(t,e){const n=[];return Object.values(t).forEach(r=>{Nr(r.accounts).includes(e)&&n.push(...r.events)}),n}function Lp(t){return t.includes(":")}function BI(t){return Lp(t)?t.split(":")[0]:t}function Mp(t){var e,n,r;const i={};if(!Ui(t))return i;for(const[s,o]of Object.entries(t)){const a=Lp(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=BI(s);i[l]=DI(AI({},i[l]),{chains:ir(a,(e=i[l])==null?void 0:e.chains),methods:ir(c,(n=i[l])==null?void 0:n.methods),events:ir(u,(r=i[l])==null?void 0:r.events)})}return i}function PI(t){const e={};return t?.forEach(n=>{var r;const[i,s]=n.split(":");e[i]||(e[i]={accounts:[],chains:[],events:[],methods:[]}),e[i].accounts.push(n),(r=e[i].chains)==null||r.push(`${i}:${s}`)}),e}function zp(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=PI(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=ir(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function CI(t,e){var n,r,i,s,o,a;const c=Mp(t),u=Mp(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:ir((n=c[f])==null?void 0:n.chains,(r=u[f])==null?void 0:r.chains),methods:ir((i=c[f])==null?void 0:i.methods,(s=u[f])==null?void 0:s.methods),events:ir((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}const RI={INVALID_METHOD:{message:"Invalid method.",code:1001},INVALID_EVENT:{message:"Invalid event.",code:1002},INVALID_UPDATE_REQUEST:{message:"Invalid update request.",code:1003},INVALID_EXTEND_REQUEST:{message:"Invalid extend request.",code:1004},INVALID_SESSION_SETTLE_REQUEST:{message:"Invalid session settle request.",code:1005},UNAUTHORIZED_METHOD:{message:"Unauthorized method.",code:3001},UNAUTHORIZED_EVENT:{message:"Unauthorized event.",code:3002},UNAUTHORIZED_UPDATE_REQUEST:{message:"Unauthorized update request.",code:3003},UNAUTHORIZED_EXTEND_REQUEST:{message:"Unauthorized extend request.",code:3004},USER_REJECTED:{message:"User rejected.",code:5e3},USER_REJECTED_CHAINS:{message:"User rejected chains.",code:5001},USER_REJECTED_METHODS:{message:"User rejected methods.",code:5002},USER_REJECTED_EVENTS:{message:"User rejected events.",code:5003},UNSUPPORTED_CHAINS:{message:"Unsupported chains.",code:5100},UNSUPPORTED_METHODS:{message:"Unsupported methods.",code:5101},UNSUPPORTED_EVENTS:{message:"Unsupported events.",code:5102},UNSUPPORTED_ACCOUNTS:{message:"Unsupported accounts.",code:5103},UNSUPPORTED_NAMESPACE_KEY:{message:"Unsupported namespace key.",code:5104},USER_DISCONNECTED:{message:"User disconnected.",code:6e3},SESSION_SETTLEMENT_FAILED:{message:"Session settlement failed.",code:7e3},WC_METHOD_UNSUPPORTED:{message:"Unsupported wc_ method.",code:10001}},NI={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function z(t,e){const{message:n,code:r}=NI[t];return{message:e?`${n} ${e}`:n,code:r}}function fe(t,e){const{message:n,code:r}=RI[t];return{message:e?`${n} ${e}`:n,code:r}}function Ur(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ui(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function we(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function Nc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function UI(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return nr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Nr(a),h=n[o];(!nr(id(o,h),l)||!nr(h.methods,c)||!nr(h.events,u))&&(s=!1)}),s):!1}function Fi(t){return we(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function FI(t){if(we(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Fi(n)}}return!1}function kI(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(we(t,!1)){if(e(t))return!0;const n=gd(t);return e(n)}}catch{}return!1}function LI(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function MI(t){return t?.topic}function zI(t,e){let n=null;return we(t?.publicKey,!1)||(n=z("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function qp(t){let e=!0;return Ur(t)?t.length&&(e=t.every(n=>we(n,!1))):e=!1,e}function qI(t,e,n){let r=null;return Ur(e)&&e.length?e.forEach(i=>{r||Fi(i)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Fi(t)||(r=fe("UNSUPPORTED_CHAINS",`${n}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function jI(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=qI(i,id(i,s),`${e} ${n}`);o&&(r=o)}),r}function VI(t,e){let n=null;return Ur(t)?t.forEach(r=>{n||FI(r)||(n=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function KI(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=VI(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function HI(t,e){let n=null;return qp(t?.methods)?qp(t?.events)||(n=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function jp(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=HI(r,`${e}, namespace`);i&&(n=i)}),n}function WI(t,e,n){let r=null;if(t&&Ui(t)){const i=jp(t,e);i&&(r=i);const s=jI(t,e,n);s&&(r=s)}else r=z("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function Uc(t,e){let n=null;if(t&&Ui(t)){const r=jp(t,e);r&&(n=r);const i=KI(t,e);i&&(n=i)}else n=z("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function Vp(t){return we(t.protocol,!0)}function GI(t,e){let n=!1;return e&&!t?n=!0:t&&Ur(t)&&t.length&&t.forEach(r=>{n=Vp(r)}),n}function YI(t){return typeof t=="number"}function st(t){return typeof t<"u"&&typeof t!==null}function ZI(t){return!(!t||typeof t!="object"||!t.code||!Nc(t.code,!1)||!t.message||!we(t.message,!1))}function JI(t){return!(_e(t)||!we(t.method,!1))}function XI(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!Nc(t.id,!1)||!we(t.jsonrpc,!1))}function QI(t){return!(_e(t)||!we(t.name,!1))}function Kp(t,e){return!(!Fi(e)||!OI(t).includes(e))}function eS(t,e,n){return we(n,!1)?$I(t,e).includes(n):!1}function tS(t,e,n){return we(n,!1)?TI(t,e).includes(n):!1}function Hp(t,e,n){let r=null;const i=nS(t),s=rS(e),o=Object.keys(i),a=Object.keys(s),c=Wp(Object.keys(t)),u=Wp(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
|
|
23
23
|
Required: ${l.toString()}
|
|
24
|
-
Received: ${Object.keys(e).toString()}`)),
|
|
24
|
+
Received: ${Object.keys(e).toString()}`)),nr(o,a)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
|
|
25
25
|
Required: ${o.toString()}
|
|
26
|
-
Approved: ${a.toString()}`)),Object.keys(e).forEach(
|
|
27
|
-
Required: ${
|
|
28
|
-
Approved: ${
|
|
26
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const f=Nr(e[h].accounts);f.includes(h)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
27
|
+
Required: ${h}
|
|
28
|
+
Approved: ${f.toString()}`))}),o.forEach(h=>{r||(nr(i[h].methods,s[h].methods)?nr(i[h].events,s[h].events)||(r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${h}`)):r=z("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function nS(t){const e={};return Object.keys(t).forEach(n=>{var r;n.includes(":")?e[n]=t[n]:(r=t[n].chains)==null||r.forEach(i=>{e[i]={methods:t[n].methods,events:t[n].events}})}),e}function Wp(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function rS(t){const e={};return Object.keys(t).forEach(n=>{n.includes(":")?e[n]=t[n]:Nr(t[n].accounts)?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}),e}function iS(t,e){return Nc(t,!1)&&t<=e.max&&t>=e.min}function Gp(){const t=vi();return new Promise(e=>{switch(t){case ft.browser:e(sS());break;case ft.reactNative:e(oS());break;case ft.node:e(aS());break;default:e(!0)}})}function sS(){return Dr()&&navigator?.onLine}async function oS(){return Sn()&&typeof global<"u"&&global!=null&&global.NetInfo?(await(global==null?void 0:global.NetInfo.fetch()))?.isConnected:!0}function aS(){return!0}function cS(t){switch(vi()){case ft.browser:uS(t);break;case ft.reactNative:lS(t);break}}function uS(t){!Sn()&&Dr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function lS(t){Sn()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function hS(){var t;return Dr()&&Yn()?((t=Yn())==null?void 0:t.visibilityState)==="visible":!0}const Fc={};class ki{static get(e){return Fc[e]}static set(e,n){Fc[e]=n}static delete(e){delete Fc[e]}}function fS(t){const e=ui.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function dS({publicKey:t,signature:e,payload:n}){var r;const i=kc(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=yS(n.address),a=n.era==="00"?new Uint8Array([0]):kc(n.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(n.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${gS(n.tip)}`),h=mS(l),f=new Uint8Array([0,...t,o,...e,...a,...u,...h,...i]),p=wS(f.length+1);return new Uint8Array([...p,s,...f])}function pS(t){const e=kc(t),n=ix.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function kc(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function gS(t){return t.startsWith("0x")?t.slice(2):t}function yS(t){const e=ui.decode(t)[0];return e===42?0:e===60?2:1}function wS(t){if(t<64)return new Uint8Array([t<<2]);if(t<16384){const e=t<<2|1;return new Uint8Array([e&255,e>>8&255])}else if(t<1<<30){const e=t<<2|2;return new Uint8Array([e&255,e>>8&255,e>>16&255,e>>24&255])}else throw new Error("Compact encoding > 2^30 not supported")}function mS(t){if(t<BigInt(1)<<BigInt(6))return new Uint8Array([Number(t<<BigInt(2))]);if(t<BigInt(1)<<BigInt(14)){const e=t<<BigInt(2)|BigInt(1);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255))])}else if(t<BigInt(1)<<BigInt(30)){const e=t<<BigInt(2)|BigInt(2);return new Uint8Array([Number(e&BigInt(255)),Number(e>>BigInt(8)&BigInt(255)),Number(e>>BigInt(16)&BigInt(255)),Number(e>>BigInt(24)&BigInt(255))])}else throw new Error("BigInt compact encoding not supported > 2^30")}function bS(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=fS(t.transaction.address),r=dS({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return pS(i)}const vS="PARSE_ERROR",ES="INVALID_REQUEST",xS="METHOD_NOT_FOUND",_S="INVALID_PARAMS",Yp="INTERNAL_ERROR",Lc="SERVER_ERROR",IS=[-32700,-32600,-32601,-32602,-32603],Li={[vS]:{code:-32700,message:"Parse error"},[ES]:{code:-32600,message:"Invalid Request"},[xS]:{code:-32601,message:"Method not found"},[_S]:{code:-32602,message:"Invalid params"},[Yp]:{code:-32603,message:"Internal error"},[Lc]:{code:-32e3,message:"Server error"}},Zp=Lc;function SS(t){return IS.includes(t)}function Jp(t){return Object.keys(Li).includes(t)?Li[t]:Li[Zp]}function AS(t){const e=Object.values(Li).find(n=>n.code===t);return e||Li[Zp]}function DS(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var Xp={};/*! *****************************************************************************
|
|
29
29
|
Copyright (c) Microsoft Corporation.
|
|
30
30
|
|
|
31
31
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -38,5 +38,5 @@ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(Px(n)).toStr
|
|
|
38
38
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
39
39
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
40
40
|
PERFORMANCE OF THIS SOFTWARE.
|
|
41
|
-
***************************************************************************** */var Hc=function(t,e){return Hc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Hc(t,e)};function 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})});
|
|
41
|
+
***************************************************************************** */var Mc=function(t,e){return Mc=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,r){n.__proto__=r}||function(n,r){for(var i in r)r.hasOwnProperty(i)&&(n[i]=r[i])},Mc(t,e)};function OS(t,e){Mc(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var zc=function(){return zc=Object.assign||function(e){for(var n,r=1,i=arguments.length;r<i;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(e[s]=n[s])}return e},zc.apply(this,arguments)};function $S(t,e){var n={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(n[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,r=Object.getOwnPropertySymbols(t);i<r.length;i++)e.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(t,r[i])&&(n[r[i]]=t[r[i]]);return n}function TS(t,e,n,r){var i=arguments.length,s=i<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,n):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,n,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(i<3?o(s):i>3?o(e,n,s):o(e,n))||s);return i>3&&s&&Object.defineProperty(e,n,s),s}function BS(t,e){return function(n,r){e(n,r,t)}}function PS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function CS(t,e,n,r){function i(s){return s instanceof n?s:new n(function(o){o(s)})}return new(n||(n=Promise))(function(s,o){function a(l){try{u(r.next(l))}catch(h){o(h)}}function c(l){try{u(r.throw(l))}catch(h){o(h)}}function u(l){l.done?s(l.value):i(l.value).then(a,c)}u((r=r.apply(t,e||[])).next())})}function RS(t,e){var n={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,i,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(u){return function(l){return c([u,l])}}function c(u){if(r)throw new TypeError("Generator is already executing.");for(;n;)try{if(r=1,i&&(s=u[0]&2?i.return:u[0]?i.throw||((s=i.return)&&s.call(i),0):i.next)&&!(s=s.call(i,u[1])).done)return s;switch(i=0,s&&(u=[u[0]&2,s.value]),u[0]){case 0:case 1:s=u;break;case 4:return n.label++,{value:u[1],done:!1};case 5:n.label++,i=u[1],u=[0];continue;case 7:u=n.ops.pop(),n.trys.pop();continue;default:if(s=n.trys,!(s=s.length>0&&s[s.length-1])&&(u[0]===6||u[0]===2)){n=0;continue}if(u[0]===3&&(!s||u[1]>s[0]&&u[1]<s[3])){n.label=u[1];break}if(u[0]===6&&n.label<s[1]){n.label=s[1],s=u;break}if(s&&n.label<s[2]){n.label=s[2],n.ops.push(u);break}s[2]&&n.ops.pop(),n.trys.pop();continue}u=e.call(t,n)}catch(l){u=[6,l],i=0}finally{r=s=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function NS(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function US(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function qc(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Qp(t,e){var n=typeof Symbol=="function"&&t[Symbol.iterator];if(!n)return t;var r=n.call(t),i,s=[],o;try{for(;(e===void 0||e-- >0)&&!(i=r.next()).done;)s.push(i.value)}catch(a){o={error:a}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return s}function FS(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Qp(arguments[e]));return t}function kS(){for(var t=0,e=0,n=arguments.length;e<n;e++)t+=arguments[e].length;for(var r=Array(t),i=0,e=0;e<n;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,i++)r[i]=s[o];return r}function Mi(t){return this instanceof Mi?(this.v=t,this):new Mi(t)}function LS(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=n.apply(t,e||[]),i,s=[];return i={},o("next"),o("throw"),o("return"),i[Symbol.asyncIterator]=function(){return this},i;function o(f){r[f]&&(i[f]=function(p){return new Promise(function(d,g){s.push([f,p,d,g])>1||a(f,p)})})}function a(f,p){try{c(r[f](p))}catch(d){h(s[0][3],d)}}function c(f){f.value instanceof Mi?Promise.resolve(f.value.v).then(u,l):h(s[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),s.shift(),s.length&&a(s[0][0],s[0][1])}}function MS(t){var e,n;return e={},r("next"),r("throw",function(i){throw i}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(i,s){e[i]=t[i]?function(o){return(n=!n)?{value:Mi(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function zS(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof qc=="function"?qc(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(s){n[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),i(a,c,o.done,o.value)})}}function i(s,o,a,c){Promise.resolve(c).then(function(u){s({value:u,done:a})},o)}}function qS(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function jS(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var n in t)Object.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e.default=t,e}function VS(t){return t&&t.__esModule?t:{default:t}}function KS(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function HS(t,e,n){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,n),n}var WS=Object.freeze({__proto__:null,__extends:OS,get __assign(){return zc},__rest:$S,__decorate:TS,__param:BS,__metadata:PS,__awaiter:CS,__generator:RS,__createBinding:NS,__exportStar:US,__values:qc,__read:Qp,__spread:FS,__spreadArrays:kS,__await:Mi,__asyncGenerator:LS,__asyncDelegator:MS,__asyncValues:zS,__makeTemplateObject:qS,__importStar:jS,__importDefault:VS,__classPrivateFieldGet:KS,__classPrivateFieldSet:HS}),GS=fu(WS),un={},eg;function YS(){if(eg)return un;eg=1,Object.defineProperty(un,"__esModule",{value:!0}),un.isBrowserCryptoAvailable=un.getSubtleCrypto=un.getBrowerCrypto=void 0;function t(){return Ft?.crypto||Ft?.msCrypto||{}}un.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}un.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return un.isBrowserCryptoAvailable=n,un}var ln={},tg;function ZS(){if(tg)return ln;tg=1,Object.defineProperty(ln,"__esModule",{value:!0}),ln.isBrowser=ln.isNode=ln.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ln.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}ln.isNode=e;function n(){return!t()&&!e()}return ln.isBrowser=n,ln}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=GS;e.__exportStar(YS(),t),e.__exportStar(ZS(),t)})(Xp);function ot(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Ln(t=6){return BigInt(ot(t))}function hn(t,e,n){return{id:n||ot(),jsonrpc:"2.0",method:t,params:e}}function oo(t,e){return{id:t,jsonrpc:"2.0",result:e}}function jc(t,e,n){return{id:t,jsonrpc:"2.0",error:JS(e,n)}}function JS(t,e){return typeof t>"u"?Jp(Yp):(typeof t=="string"&&(t=Object.assign(Object.assign({},Jp(Lc)),{message:t})),typeof e<"u"&&(t.data=e),SS(t.code)&&(t=AS(t.code)),t)}class XS{}class QS extends XS{constructor(){super()}}class e6 extends QS{constructor(e){super()}}const t6="^wss?:";function n6(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function r6(t,e){const n=n6(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function ng(t){return r6(t,t6)}function i6(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function rg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Vc(t){return rg(t)&&"method"in t}function ao(t){return rg(t)&&(Kt(t)||It(t))}function Kt(t){return"result"in t}function It(t){return"error"in t}class s6 extends e6{constructor(e){super(e),this.events=new Ve.exports.EventEmitter,this.hasRegisteredEventListeners=!1,this.connection=this.setConnection(e),this.connection.connected&&this.registerEventListeners()}async connect(e=this.connection){await this.open(e)}async disconnect(){await this.close()}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async request(e,n){return this.requestStrict(hn(e.method,e.params||[],e.id||Ln().toString()),n)}async requestStrict(e,n){return new Promise(async(r,i)=>{if(!this.connection.connected)try{await this.open()}catch(s){i(s)}this.events.on(`${e.id}`,s=>{It(s)?i(s.error):r(s.result)});try{await this.connection.send(e,n)}catch(s){i(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const o6=()=>typeof WebSocket<"u"?WebSocket:typeof global<"u"&&typeof global.WebSocket<"u"?global.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),a6=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",ig=t=>t.split("?")[0],sg=10,c6=o6();class u6{constructor(e){if(this.url=e,this.events=new Ve.exports.EventEmitter,this.registering=!1,!ng(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,n)=>{if(typeof this.socket>"u"){n(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Hn(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!ng(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const n=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=n||this.events.listenerCount("open")>=n)&&this.events.setMaxListeners(n+1),new Promise((r,i)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),i(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return i(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((n,r)=>{const i=Xp.isReactNative()?void 0:{rejectUnauthorized:!i6(e)},s=new c6(e,[],i);a6()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),n(s)}})}onOpen(e){e.onmessage=n=>this.onPayload(n),e.onclose=n=>this.onClose(n),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const n=typeof e.data=="string"?gr(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=jc(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return DS(e,ig(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>sg&&this.events.setMaxListeners(sg)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${ig(this.url)}`));return this.events.emit("register_error",n),n}}const og="wc",ag=2,co="core",Ht=`${og}@2:${co}:`,l6={name:co,logger:"error"},h6={database:":memory:"},f6="crypto",cg="client_ed25519_seed",d6=M.ONE_DAY,p6="keychain",g6="0.3",y6="messages",w6="0.3",m6=M.SIX_HOURS,b6="publisher",ug="irn",v6="error",lg="wss://relay.walletconnect.org",E6="relayer",ge={message:"relayer_message",message_ack:"relayer_message_ack",connect:"relayer_connect",disconnect:"relayer_disconnect",error:"relayer_error",connection_stalled:"relayer_connection_stalled",transport_closed:"relayer_transport_closed",publish:"relayer_publish"},x6="_subscription",St={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},_6=.1,Kc="2.21.8",he={link_mode:"link_mode",relay:"relay"},uo={inbound:"inbound",outbound:"outbound"},I6="0.3",S6="WALLETCONNECT_CLIENT_ID",hg="WALLETCONNECT_LINK_MODE_APPS",dt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},A6="subscription",D6="0.3",O6="pairing",$6="0.3",zi={wc_pairingDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:M.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:M.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:M.ONE_DAY,prompt:!1,tag:0},res:{ttl:M.ONE_DAY,prompt:!1,tag:0}}},lr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Nt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},T6="history",B6="0.3",P6="expirer",At={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},C6="0.3",R6="verify-api",N6="https://verify.walletconnect.com",fg="https://verify.walletconnect.org",qi=fg,U6=`${qi}/v3`,F6=[N6,fg],k6="echo",L6="https://echo.walletconnect.com",Wt={pairing_started:"pairing_started",pairing_uri_validation_success:"pairing_uri_validation_success",pairing_uri_not_expired:"pairing_uri_not_expired",store_new_pairing:"store_new_pairing",subscribing_pairing_topic:"subscribing_pairing_topic",subscribe_pairing_topic_success:"subscribe_pairing_topic_success",existing_pairing:"existing_pairing",pairing_not_expired:"pairing_not_expired",emit_inactive_pairing:"emit_inactive_pairing",emit_session_proposal:"emit_session_proposal",subscribing_to_pairing_topic:"subscribing_to_pairing_topic"},fn={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Mn={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success"},ji={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found"},hr={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},Vi={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},M6=.1,z6="event-client",q6=86400,j6="https://pulse.walletconnect.org/batch";function V6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var n=new Uint8Array(256),r=0;r<n.length;r++)n[r]=255;for(var i=0;i<t.length;i++){var s=t.charAt(i),o=s.charCodeAt(0);if(n[o]!==255)throw new TypeError(s+" is ambiguous");n[o]=i}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var g=0,y=0,_=0,A=d.length;_!==A&&d[_]===0;)_++,g++;for(var b=(A-_)*l+1>>>0,v=new Uint8Array(b);_!==A;){for(var x=d[_],T=0,R=b-1;(x!==0||T<y)&&R!==-1;R--,T++)x+=256*v[R]>>>0,v[R]=x%a>>>0,x=x/a>>>0;if(x!==0)throw new Error("Non-zero carry");y=T,_++}for(var C=b-y;C!==b&&v[C]===0;)C++;for(var m=c.repeat(g);C<b;++C)m+=t.charAt(v[C]);return m}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var g=0;if(d[g]!==" "){for(var y=0,_=0;d[g]===c;)y++,g++;for(var A=(d.length-g)*u+1>>>0,b=new Uint8Array(A);d[g];){var v=n[d.charCodeAt(g)];if(v===255)return;for(var x=0,T=A-1;(v!==0||x<_)&&T!==-1;T--,x++)v+=a*b[T]>>>0,b[T]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=x,g++}if(d[g]!==" "){for(var R=A-_;R!==A&&b[R]===0;)R++;for(var C=new Uint8Array(y+(A-R)),m=y;R!==A;)C[m++]=b[R++];return C}}}function p(d){var g=f(d);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var K6=V6,H6=K6;const dg=t=>{if(t instanceof Uint8Array&&t.constructor.name==="Uint8Array")return t;if(t instanceof ArrayBuffer)return new Uint8Array(t);if(ArrayBuffer.isView(t))return new Uint8Array(t.buffer,t.byteOffset,t.byteLength);throw new Error("Unknown type, must be binary type")},W6=t=>new TextEncoder().encode(t),G6=t=>new TextDecoder().decode(t);class Y6{constructor(e,n,r){this.name=e,this.prefix=n,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class Z6{constructor(e,n,r){if(this.name=e,this.prefix=n,n.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=n.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return pg(this,e)}}class J6{constructor(e){this.decoders=e}or(e){return pg(this,e)}decode(e){const n=e[0],r=this.decoders[n];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const pg=(t,e)=>new J6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class X6{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new Y6(e,n,r),this.decoder=new Z6(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const lo=({name:t,prefix:e,encode:n,decode:r})=>new X6(t,e,n,r),Ki=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=H6(n,e);return lo({prefix:t,name:e,encode:r,decode:s=>dg(i(s))})},Q6=(t,e,n,r)=>{const i={};for(let l=0;l<e.length;++l)i[e[l]]=l;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*n/8|0);let a=0,c=0,u=0;for(let l=0;l<s;++l){const h=i[t[l]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<n|h,a+=n,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=n||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},e4=(t,e,n)=>{const r=e[e.length-1]==="=",i=(1<<n)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>n;)o-=n,s+=e[i&a>>o];if(o&&(s+=e[i&a<<n-o]),r)for(;s.length*n&7;)s+="=";return s},Ce=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>lo({prefix:e,name:t,encode(i){return e4(i,r,n)},decode(i){return Q6(i,r,n,t)}}),t4=lo({prefix:"\0",name:"identity",encode:t=>G6(t),decode:t=>W6(t)});var n4=Object.freeze({__proto__:null,identity:t4});const r4=Ce({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var i4=Object.freeze({__proto__:null,base2:r4});const s4=Ce({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var o4=Object.freeze({__proto__:null,base8:s4});const a4=Ki({prefix:"9",name:"base10",alphabet:"0123456789"});var c4=Object.freeze({__proto__:null,base10:a4});const u4=Ce({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),l4=Ce({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var h4=Object.freeze({__proto__:null,base16:u4,base16upper:l4});const f4=Ce({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),d4=Ce({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),p4=Ce({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),g4=Ce({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),y4=Ce({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),w4=Ce({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),m4=Ce({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),b4=Ce({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),v4=Ce({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var E4=Object.freeze({__proto__:null,base32:f4,base32upper:d4,base32pad:p4,base32padupper:g4,base32hex:y4,base32hexupper:w4,base32hexpad:m4,base32hexpadupper:b4,base32z:v4});const x4=Ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_4=Ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var I4=Object.freeze({__proto__:null,base36:x4,base36upper:_4});const S4=Ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),A4=Ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var D4=Object.freeze({__proto__:null,base58btc:S4,base58flickr:A4});const O4=Ce({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),$4=Ce({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),T4=Ce({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),B4=Ce({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var P4=Object.freeze({__proto__:null,base64:O4,base64pad:$4,base64url:T4,base64urlpad:B4});const gg=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),C4=gg.reduce((t,e,n)=>(t[n]=e,t),[]),R4=gg.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function N4(t){return t.reduce((e,n)=>(e+=C4[n],e),"")}function U4(t){const e=[];for(const n of t){const r=R4[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const F4=lo({prefix:"\u{1F680}",name:"base256emoji",encode:N4,decode:U4});var k4=Object.freeze({__proto__:null,base256emoji:F4}),L4=wg,yg=128,M4=127,z4=~M4,q4=Math.pow(2,31);function wg(t,e,n){e=e||[],n=n||0;for(var r=n;t>=q4;)e[n++]=t&255|yg,t/=128;for(;t&z4;)e[n++]=t&255|yg,t>>>=7;return e[n]=t|0,wg.bytes=n-r+1,e}var j4=Hc,V4=128,mg=127;function Hc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Hc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&mg)<<i:(o&mg)*Math.pow(2,i),i+=7}while(o>=V4);return Hc.bytes=s-r,n}var K4=Math.pow(2,7),H4=Math.pow(2,14),W4=Math.pow(2,21),G4=Math.pow(2,28),Y4=Math.pow(2,35),Z4=Math.pow(2,42),J4=Math.pow(2,49),X4=Math.pow(2,56),Q4=Math.pow(2,63),eA=function(t){return t<K4?1:t<H4?2:t<W4?3:t<G4?4:t<Y4?5:t<Z4?6:t<J4?7:t<X4?8:t<Q4?9:10},tA={encode:L4,decode:j4,encodingLength:eA},bg=tA;const vg=(t,e,n=0)=>(bg.encode(t,e,n),e),Eg=t=>bg.encodingLength(t),Wc=(t,e)=>{const n=e.byteLength,r=Eg(t),i=r+Eg(n),s=new Uint8Array(i+n);return vg(t,s,0),vg(n,s,r),s.set(e,i),new nA(t,n,e,s)};class nA{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const xg=({name:t,code:e,encode:n})=>new rA(t,e,n);class rA{constructor(e,n,r){this.name=e,this.code=n,this.encode=r}digest(e){if(e instanceof Uint8Array){const n=this.encode(e);return n instanceof Uint8Array?Wc(this.code,n):n.then(r=>Wc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const _g=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),iA=xg({name:"sha2-256",code:18,encode:_g("SHA-256")}),sA=xg({name:"sha2-512",code:19,encode:_g("SHA-512")});var oA=Object.freeze({__proto__:null,sha256:iA,sha512:sA});const Ig=0,aA="identity",Sg=dg;var cA=Object.freeze({__proto__:null,identity:{code:Ig,name:aA,encode:Sg,digest:t=>Wc(Ig,Sg(t))}});new TextEncoder,new TextDecoder;const Ag={...n4,...i4,...o4,...c4,...h4,...E4,...I4,...D4,...P4,...k4};({...oA,...cA});function Dg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function uA(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Dg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Og(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const $g=Og("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Gc=Og("ascii","a",t=>{let e="a";for(let n=0;n<t.length;n++)e+=String.fromCharCode(t[n]);return e},t=>{t=t.substring(1);const e=uA(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),lA={utf8:$g,"utf-8":$g,hex:Ag.base16,latin1:Gc,ascii:Gc,binary:Gc,...Ag};function hA(t,e="utf8"){const n=lA[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Dg(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var fA=Object.defineProperty,dA=(t,e,n)=>e in t?fA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Gt=(t,e,n)=>dA(t,typeof e!="symbol"?e+"":e,n);class pA{constructor(e,n){this.core=e,this.logger=n,Gt(this,"keychain",new Map),Gt(this,"name",p6),Gt(this,"version",g6),Gt(this,"initialized",!1),Gt(this,"storagePrefix",Ht),Gt(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Gt(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Gt(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),Gt(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=z("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),Gt(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,tc(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?nc(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var gA=Object.defineProperty,yA=(t,e,n)=>e in t?gA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Re=(t,e,n)=>yA(t,typeof e!="symbol"?e+"":e,n);class wA{constructor(e,n,r){this.core=e,this.logger=n,Re(this,"name",f6),Re(this,"keychain"),Re(this,"randomSessionIdentifier",Rc()),Re(this,"initialized",!1),Re(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Re(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Re(this,"getClientId",async()=>{this.isInitialized();const i=await this.getClientSeed(),s=Gl(i);return Wl(s.publicKey)}),Re(this,"generateKeyPair",()=>{this.isInitialized();const i=cI();return this.setPrivateKey(i.publicKey,i.privateKey)}),Re(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Gl(s),a=this.randomSessionIdentifier;return await ub(a,i,d6,o)}),Re(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=uI(a,s);return this.setSymKey(c,o)}),Re(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ro(i);return await this.keychain.set(o,i),o}),Re(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Re(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Re(this,"encode",async(i,s,o)=>{this.isInitialized();const a=Pp(o),c=Hn(s);if(Rp(a))return fI(c,o?.encoding);if(Cp(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;i=await this.generateSharedKey(f,p)}const u=this.getSymKey(i),{type:l,senderPublicKey:h}=a;return lI({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),Re(this,"decode",async(i,s,o)=>{this.isInitialized();const a=pI(s,o);if(Rp(a)){const c=dI(s,o?.encoding);return gr(c)}if(Cp(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=hI({symKey:c,encoded:s,encoding:o?.encoding});return gr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Re(this,"getPayloadType",(i,s=it)=>{const o=Ni({encoded:i,encoding:s});return ur(o.type)}),Re(this,"getPayloadSenderPublicKey",(i,s=it)=>{const o=Ni({encoded:i,encoding:s});return o.senderPublicKey?et(o.senderPublicKey,Ye):void 0}),this.core=e,this.logger=Ke(n,this.name),this.keychain=r||new pA(this.core,this.logger)}get context(){return Je(this.logger)}async setPrivateKey(e,n){return await this.keychain.set(e,n),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(cg)}catch{e=Rc(),await this.keychain.set(cg,e)}return hA(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mA=Object.defineProperty,bA=Object.defineProperties,vA=Object.getOwnPropertyDescriptors,Tg=Object.getOwnPropertySymbols,EA=Object.prototype.hasOwnProperty,xA=Object.prototype.propertyIsEnumerable,Yc=(t,e,n)=>e in t?mA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_A=(t,e)=>{for(var n in e||(e={}))EA.call(e,n)&&Yc(t,n,e[n]);if(Tg)for(var n of Tg(e))xA.call(e,n)&&Yc(t,n,e[n]);return t},IA=(t,e)=>bA(t,vA(e)),pt=(t,e,n)=>Yc(t,typeof e!="symbol"?e+"":e,n);class SA extends cw{constructor(e,n){super(e,n),this.logger=e,this.core=n,pt(this,"messages",new Map),pt(this,"messagesWithoutClientAck",new Map),pt(this,"name",y6),pt(this,"version",w6),pt(this,"initialized",!1),pt(this,"storagePrefix",Ht),pt(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const i=await this.getRelayerMessagesWithoutClientAck();typeof i<"u"&&(this.messagesWithoutClientAck=i),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),pt(this,"set",async(r,i,s)=>{this.isInitialized();const o=_t(i);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=i,this.messages.set(r,a),s===uo.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,IA(_A({},c),{[o]:i}))}return await this.persist(),o}),pt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),pt(this,"getWithoutAck",r=>{this.isInitialized();const i={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};i[s]=Object.values(o)}return i}),pt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=_t(i);return typeof s[o]<"u"}),pt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=_t(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),pt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ke(e,this.name),this.core=n}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get storageKeyWithoutClientAck(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name+"_withoutClientAck"}async setRelayerMessages(e){await this.core.storage.setItem(this.storageKey,tc(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,tc(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?nc(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?nc(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AA=Object.defineProperty,DA=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,Bg=Object.getOwnPropertySymbols,$A=Object.prototype.hasOwnProperty,TA=Object.prototype.propertyIsEnumerable,Zc=(t,e,n)=>e in t?AA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fr=(t,e)=>{for(var n in e||(e={}))$A.call(e,n)&&Zc(t,n,e[n]);if(Bg)for(var n of Bg(e))TA.call(e,n)&&Zc(t,n,e[n]);return t},Pg=(t,e)=>DA(t,OA(e)),Dt=(t,e,n)=>Zc(t,typeof e!="symbol"?e+"":e,n);class BA extends uw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Dt(this,"events",new Ve.exports.EventEmitter),Dt(this,"name",b6),Dt(this,"queue",new Map),Dt(this,"publishTimeout",M.toMiliseconds(M.ONE_MINUTE)),Dt(this,"initialPublishTimeout",M.toMiliseconds(M.ONE_SECOND*15)),Dt(this,"needsTransportRestart",!1),Dt(this,"publish",async(r,i,s)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:i,opts:s}});const h=s?.ttl||m6,f=s?.prompt||!1,p=s?.tag||0,d=s?.id||Ln().toString(),g=Rr(io().protocol),y={id:d,method:s?.publishMethod||g.publish,params:Fr({topic:r,message:i,ttl:h,prompt:f,tag:p,attestation:s?.attestation},s?.tvf&&{tvf:s.tvf})},_=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{_e((o=y.params)==null?void 0:o.prompt)&&((a=y.params)==null||delete a.prompt),_e((c=y.params)==null?void 0:c.tag)&&((u=y.params)==null||delete u.tag);const A=new Promise(async b=>{const v=({id:T})=>{var R;((R=y.id)==null?void 0:R.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(ge.publish,v),b())};this.relayer.events.on(ge.publish,v);const x=jt(new Promise((T,R)=>{this.rpcPublish(y,s).then(T).catch(C=>{this.logger.warn(C,C?.message),R(C)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await x,this.events.removeListener(ge.publish,v)}catch(T){this.queue.set(d,{request:y,opts:s,attempt:1}),this.logger.warn(T,T?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:r,message:i,opts:s}}),await jt(A,this.publishTimeout,_)}catch(A){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(A),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw A}finally{this.queue.delete(d)}}),Dt(this,"publishCustom",async r=>{var i,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:u,opts:l={}}=r,{attestation:h,tvf:f,publishMethod:p,prompt:d,tag:g,ttl:y=M.FIVE_MINUTES}=l,_=l.id||Ln().toString(),A=Rr(io().protocol),b=p||A.publish,v={id:_,method:b,params:Fr(Pg(Fr({},u),{ttl:y,prompt:d,tag:g,attestation:h}),f)},x=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{_e((i=v.params)==null?void 0:i.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const T=new Promise(async R=>{const C=({id:B})=>{var S;((S=v.id)==null?void 0:S.toString())===B.toString()&&(this.removeRequestFromQueue(B),this.relayer.events.removeListener(ge.publish,C),R())};this.relayer.events.on(ge.publish,C);const m=jt(new Promise((B,S)=>{this.rpcPublish(v,l).then(B).catch(O=>{this.logger.warn(O,O?.message),S(O)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${_} tag:${g}`);try{await m,this.events.removeListener(ge.publish,C)}catch(B){this.queue.set(_,{request:v,opts:l,attempt:1}),this.logger.warn(B,B?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:u,opts:l}}),await jt(T,this.publishTimeout,x)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw T}finally{this.queue.delete(_)}}),Dt(this,"on",(r,i)=>{this.events.on(r,i)}),Dt(this,"once",(r,i)=>{this.events.once(r,i)}),Dt(this,"off",(r,i)=>{this.events.off(r,i)}),Dt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ke(n,this.name),this.registerEventListeners()}get context(){return Je(this.logger)}async rpcPublish(e,n){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(ge.publish,Fr(Fr({},e),n)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,n)=>{var r;const i=e.attempt+1;this.queue.set(n,Pg(Fr({},e),{attempt:i})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${i}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Vn.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(ge.connection_stalled);return}this.checkQueue()}),this.relayer.on(ge.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var PA=Object.defineProperty,CA=(t,e,n)=>e in t?PA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kr=(t,e,n)=>CA(t,typeof e!="symbol"?e+"":e,n);class RA{constructor(){kr(this,"map",new Map),kr(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),kr(this,"get",e=>this.map.get(e)||[]),kr(this,"exists",(e,n)=>this.get(e).includes(n)),kr(this,"delete",(e,n)=>{if(typeof n>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,n))return;const i=r.filter(s=>s!==n);if(!i.length){this.map.delete(e);return}this.map.set(e,i)}),kr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var NA=Object.defineProperty,UA=Object.defineProperties,FA=Object.getOwnPropertyDescriptors,Cg=Object.getOwnPropertySymbols,kA=Object.prototype.hasOwnProperty,LA=Object.prototype.propertyIsEnumerable,Jc=(t,e,n)=>e in t?NA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hi=(t,e)=>{for(var n in e||(e={}))kA.call(e,n)&&Jc(t,n,e[n]);if(Cg)for(var n of Cg(e))LA.call(e,n)&&Jc(t,n,e[n]);return t},Xc=(t,e)=>UA(t,FA(e)),ce=(t,e,n)=>Jc(t,typeof e!="symbol"?e+"":e,n);class MA extends fw{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,ce(this,"subscriptions",new Map),ce(this,"topicMap",new RA),ce(this,"events",new Ve.exports.EventEmitter),ce(this,"name",A6),ce(this,"version",D6),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Ht),ce(this,"subscribeTimeout",M.toMiliseconds(M.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(r,i)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}});try{const o=io(i),a={topic:r,relay:o,transportType:i?.transportType};(s=i?.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,i);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:i}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),ce(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),ce(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ce(this,"on",(r,i)=>{this.events.on(r,i)}),ce(this,"once",(r,i)=>{this.events.once(r,i)}),ce(this,"off",(r,i)=>{this.events.off(r,i)}),ce(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(i=>{r.push(i)}),await this.batchSubscribe(r)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Vn.pulse,async()=>{await this.checkPending()}),this.events.on(dt.created,async r=>{const i=dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(dt.deleted,async r=>{const i=dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ke(n,this.name),this.clientId=""}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.relayer.core.customStoragePrefix+"//"+this.name}get length(){return this.subscriptions.size}get ids(){return Array.from(this.subscriptions.keys())}get values(){return Array.from(this.subscriptions.values())}get topics(){return this.topicMap.topics}get hasAnyTopics(){return this.topicMap.topics.length>0||this.pending.size>0||this.cached.length>0||this.subscriptions.size>0}hasSubscription(e,n){let r=!1;try{r=this.getSubscription(e).topic===n}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,n){const r=this.topicMap.get(e);await Promise.all(r.map(async i=>await this.unsubscribeById(e,i,n)))}async unsubscribeById(e,n,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}});try{const i=io(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,n,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:n,opts:r}})}catch(i){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(i),i}}async rpcSubscribe(e,n,r){var i,s;const o=await this.getSubscriptionId(e);if((i=r?.internal)!=null&&i.skipSubscribe)return o;(!r||r?.transportType===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Rr(n.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r?.internal)==null?void 0:s.throwOnFailedPublish;try{if(r?.transportType===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},M.toMiliseconds(M.ONE_SECOND)),o;const u=new Promise(async h=>{const f=p=>{p.topic===e&&(this.events.removeListener(dt.created,f),h(p.id))};this.events.on(dt.created,f);try{const p=await jt(new Promise((d,g)=>{this.relayer.request(a).catch(y=>{this.logger.warn(y,y?.message),g(y)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(dt.created,f),h(p)}catch{}}),l=await jt(u,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!l&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return l?o:null}catch(u){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(ge.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Rr(n.protocol).batchSubscribe,params:{topics:e.map(i=>i.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await jt(new Promise(i=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(i)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Rr(n.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let i;try{i=await await jt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(ge.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Rr(r.protocol).unsubscribe,params:{topic:e,id:n}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i}),this.relayer.request(i)}onSubscribe(e,n){this.setSubscription(e,Xc(Hi({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Hi({},n)),this.pending.delete(n.topic)})}async onUnsubscribe(e,n,r){this.events.removeAllListeners(n),this.hasSubscription(n,e)&&this.deleteSubscription(n,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,n){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:n}),this.addSubscription(e,n)}addSubscription(e,n){this.subscriptions.set(e,Hi({},n)),this.topicMap.set(n.topic,e),this.events.emit(dt.created,n)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const n=this.subscriptions.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}deleteSubscription(e,n){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:n});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(dt.deleted,Xc(Hi({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(dt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],n=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<n;r++){const i=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(i)}}this.events.emit(dt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(n=>{var r;return n.topic===((r=this.subscriptions.get(n.id))==null?void 0:r.topic)})){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async n=>Xc(Hi({},n),{id:await this.getSubscriptionId(n.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const n=await this.rpcBatchFetchMessages(e);n&&n.messages&&(await Tx(M.toMiliseconds(M.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(n.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return _t(e+await this.getClientId())}}var zA=Object.defineProperty,Rg=Object.getOwnPropertySymbols,qA=Object.prototype.hasOwnProperty,jA=Object.prototype.propertyIsEnumerable,Qc=(t,e,n)=>e in t?zA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ng=(t,e)=>{for(var n in e||(e={}))qA.call(e,n)&&Qc(t,n,e[n]);if(Rg)for(var n of Rg(e))jA.call(e,n)&&Qc(t,n,e[n]);return t},ne=(t,e,n)=>Qc(t,typeof e!="symbol"?e+"":e,n);class VA extends lw{constructor(e){super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new Ve.exports.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",E6),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",M.toMiliseconds(M.THIRTY_SECONDS+M.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",M.toMiliseconds(M.ONE_SECOND*15)),ne(this,"request",async n=>{var r,i;this.logger.debug("Publishing Request Payload");const s=n.id||Ln().toString();await this.toEstablishConnection();try{this.logger.trace({id:s,method:n.method,topic:(r=n.params)==null?void 0:r.topic},"relayer.request - publishing...");const o=`${s}:${((i=n.params)==null?void 0:i.tag)||""}`;this.requestsInFlight.push(o);const a=await this.provider.request(n);return this.requestsInFlight=this.requestsInFlight.filter(c=>c!==o),a}catch(o){throw this.logger.debug(`Failed to Publish Request: ${s}`),o}}),ne(this,"resetPingTimeout",()=>{Ms()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var n,r,i,s;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(s=(i=(r=(n=this.provider)==null?void 0:n.connection)==null?void 0:r.socket)==null?void 0:i.terminate)==null||s.call(i)}catch(o){this.logger.warn(o,o?.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",n=>{this.onProviderPayload(n),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(ge.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",n=>{this.logger.fatal(`Fatal socket error: ${n.message}`),this.events.emit(ge.error,n),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(St.payload,this.onPayloadHandler),this.provider.on(St.connect,this.onConnectHandler),this.provider.on(St.disconnect,this.onDisconnectHandler),this.provider.on(St.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=typeof e.logger<"u"&&typeof e.logger!="string"?Ke(e.logger,this.name):kt(Po({level:e.logger||v6})),this.messages=new SA(this.logger,e.core),this.subscriber=new MA(this,this.logger),this.publisher=new BA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg,px()?this.packageName=cd():gx()&&(this.bundleId=cd()),this.provider={}}async init(){this.logger.trace("Initialized"),this.registerEventListeners(),await Promise.all([this.messages.init(),this.subscriber.init()]),this.initialized=!0,this.transportOpen().catch(e=>this.logger.warn(e,e?.message))}get context(){return Je(this.logger)}get connected(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,n,r;return((r=(n=(e=this.provider)==null?void 0:e.connection)==null?void 0:n.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,n,r){this.isInitialized(),await this.publisher.publish(e,n,r),await this.recordMessageEvent({topic:e,message:n,publishedAt:Date.now(),transportType:he.relay},uo.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,n){var r,i,s;this.isInitialized(),(!(n!=null&&n.transportType)||n?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((r=n?.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(i=n?.internal)==null?void 0:i.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(dt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(dt.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Ng({internal:{throwOnFailedPublish:o}},n)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,n){this.isInitialized(),await this.subscriber.unsubscribe(e,n)}on(e,n){this.events.on(e,n)}once(e,n){this.events.once(e,n)}off(e,n){this.events.off(e,n)}removeListener(e,n){this.events.removeListener(e,n)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await jt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(n,r)=>{await this.connect(e).then(n).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await Gp())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if(e?.length===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const n=e.sort((r,i)=>r.publishedAt-i.publishedAt);this.logger.debug(`Batch of ${n.length} message events sorted`);for(const r of n)try{await this.onMessageEvent(r)}catch(i){this.logger.warn(i,"Error while processing batch message event: "+i?.message)}this.logger.trace(`Batch of ${n.length} message events processed`)}async onLinkMessageEvent(e,n){const{topic:r}=e;if(!n.sessionExists){const i=Ee(M.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(ge.message,e),await this.recordMessageEvent(e,uo.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let n=1;for(;n<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${n}...`),await this.createProvider(),await new Promise(async(r,i)=>{const s=()=>{i(new Error("Connection interrupted while trying to connect"))};this.provider.once(St.disconnect,s),await jt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{i(o)}).finally(()=>{this.provider.off(St.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{i(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(St.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(St.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const i=r;this.logger.warn({},i.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${n}`);break}await new Promise(r=>setTimeout(r,M.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Ms())try{(n=(e=this.provider)==null?void 0:e.connection)!=null&&n.socket&&((s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o?.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new s6(new u6(vx({sdkVersion:Kc,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,n){const{topic:r,message:i}=e;await this.messages.set(r,i,n)}async shouldIgnoreMessageEvent(e){const{topic:n,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(n))return this.logger.warn(`Ignoring message for unknown topic ${n}`),!0;const i=this.messages.has(n,r);return i&&this.logger.warn(`Ignoring duplicate message: ${r}`),i}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Vc(e)){if(!e.method.endsWith(x6))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ng({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ao(e)&&this.events.emit(ge.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,uo.inbound),this.events.emit(ge.message,e))}async acknowledgePayload(e){const n=oo(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(St.payload,this.onPayloadHandler),this.provider.off(St.connect,this.onConnectHandler),this.provider.off(St.disconnect,this.onDisconnectHandler),this.provider.off(St.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await Gp();cS(async n=>{e!==n&&(e=n,n?await this.transportOpen().catch(r=>this.logger.error(r,r?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Vn.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&hS())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(ge.disconnect),this.connectionAttemptInProgress=!1,!this.reconnectInProgress&&(this.reconnectInProgress=!0,await this.subscriber.stop(),this.subscriber.hasAnyTopics&&(this.transportExplicitlyClosed||(this.reconnectTimeout=setTimeout(async()=>{await this.transportOpen().catch(e=>this.logger.error(e,e?.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},M.toMiliseconds(_6)))))}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function KA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Ug(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Fg(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const HA="[object RegExp]",WA="[object String]",GA="[object Number]",YA="[object Boolean]",kg="[object Arguments]",ZA="[object Symbol]",JA="[object Date]",XA="[object Map]",QA="[object Set]",eD="[object Array]",tD="[object Function]",nD="[object ArrayBuffer]",eu="[object Object]",rD="[object Error]",iD="[object DataView]",sD="[object Uint8Array]",oD="[object Uint8ClampedArray]",aD="[object Uint16Array]",cD="[object Uint32Array]",uD="[object BigUint64Array]",lD="[object Int8Array]",hD="[object Int16Array]",fD="[object Int32Array]",dD="[object BigInt64Array]",pD="[object Float32Array]",gD="[object Float64Array]";function yD(){}function Lg(t){if(!t||typeof t!="object")return!1;const e=Object.getPrototypeOf(t);return e===null||e===Object.prototype||Object.getPrototypeOf(e)===null?Object.prototype.toString.call(t)==="[object Object]":!1}function wD(t,e,n){return Wi(t,e,void 0,void 0,void 0,void 0,n)}function Wi(t,e,n,r,i,s,o){const a=o(t,e,n,r,i,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return Gi(t,e,s,o)}return Gi(t,e,s,o)}function Gi(t,e,n,r){if(Object.is(t,e))return!0;let i=Fg(t),s=Fg(e);if(i===kg&&(i=eu),s===kg&&(s=eu),i!==s)return!1;switch(i){case WA:return t.toString()===e.toString();case GA:{const c=t.valueOf(),u=e.valueOf();return KA(c,u)}case YA:case JA:case ZA:return Object.is(t.valueOf(),e.valueOf());case HA:return t.source===e.source&&t.flags===e.flags;case tD:return t===e}n=n??new Map;const o=n.get(t),a=n.get(e);if(o!=null&&a!=null)return o===e;n.set(t,e),n.set(e,t);try{switch(i){case XA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Wi(u,e.get(c),c,t,e,n,r))return!1;return!0}case QA:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>Wi(h,p,void 0,t,e,n,r));if(f===-1)return!1;u.splice(f,1)}return!0}case eD:case sD:case oD:case aD:case cD:case uD:case lD:case hD:case fD:case dD:case pD:case gD:{if(typeof Buffer<"u"&&Buffer.isBuffer(t)!==Buffer.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!Wi(t[c],e[c],c,t,e,n,r))return!1;return!0}case nD:return t.byteLength!==e.byteLength?!1:Gi(new Uint8Array(t),new Uint8Array(e),n,r);case iD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Gi(new Uint8Array(t),new Uint8Array(e),n,r);case rD:return t.name===e.name&&t.message===e.message;case eu:{if(!(Gi(t.constructor,e.constructor,n,r)||Lg(t)&&Lg(e)))return!1;const c=[...Object.keys(t),...Ug(t)],u=[...Object.keys(e),...Ug(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!Wi(f,p,h,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function mD(t,e){return wD(t,e,yD)}var bD=Object.defineProperty,Mg=Object.getOwnPropertySymbols,vD=Object.prototype.hasOwnProperty,ED=Object.prototype.propertyIsEnumerable,tu=(t,e,n)=>e in t?bD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,zg=(t,e)=>{for(var n in e||(e={}))vD.call(e,n)&&tu(t,n,e[n]);if(Mg)for(var n of Mg(e))ED.call(e,n)&&tu(t,n,e[n]);return t},at=(t,e,n)=>tu(t,typeof e!="symbol"?e+"":e,n);class fr extends hw{constructor(e,n,r,i=Ht,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,at(this,"map",new Map),at(this,"version",I6),at(this,"cached",[]),at(this,"initialized",!1),at(this,"getKey"),at(this,"storagePrefix",Ht),at(this,"recentlyDeleted",[]),at(this,"recentlyDeletedLimit",200),at(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):LI(o)?this.map.set(o.id,o):MI(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),at(this,"set",async(o,a)=>{this.isInitialized(),this.map.has(o)?await this.update(o,a):(this.logger.debug("Setting value"),this.logger.trace({type:"method",method:"set",key:o,value:a}),this.map.set(o,a),await this.persist())}),at(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),at(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>mD(a[c],o[c]))):this.values)),at(this,"update",async(o,a)=>{this.isInitialized(),this.logger.debug("Updating value"),this.logger.trace({type:"method",method:"update",key:o,update:a});const c=zg(zg({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),at(this,"delete",async(o,a)=>{this.isInitialized(),this.map.has(o)&&(this.logger.debug("Deleting value"),this.logger.trace({type:"method",method:"delete",key:o,reason:a}),this.map.delete(o),this.addToRecentlyDeleted(o),await this.persist())}),this.logger=Ke(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.map.size}get keys(){return Array.from(this.map.keys())}get values(){return Array.from(this.map.values())}addToRecentlyDeleted(e){this.recentlyDeleted.push(e),this.recentlyDeleted.length>=this.recentlyDeletedLimit&&this.recentlyDeleted.splice(0,this.recentlyDeletedLimit/2)}async setDataStore(e){await this.core.storage.setItem(this.storageKey,e)}async getDataStore(){return await this.core.storage.getItem(this.storageKey)}getData(e){const n=this.map.get(e);if(!n){if(this.recentlyDeleted.includes(e)){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return n}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var xD=Object.defineProperty,_D=(t,e,n)=>e in t?xD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,J=(t,e,n)=>_D(t,typeof e!="symbol"?e+"":e,n);class ID{constructor(e,n){this.core=e,this.logger=n,J(this,"name",O6),J(this,"version",$6),J(this,"events",new Ve.exports),J(this,"pairings"),J(this,"initialized",!1),J(this,"storagePrefix",Ht),J(this,"ignoredPayloadTypes",[cn]),J(this,"registeredMethods",[]),J(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),J(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),J(this,"create",async r=>{this.isInitialized();const i=Rc(),s=await this.core.crypto.setSymKey(i),o=Ee(M.FIVE_MINUTES),a={protocol:ug},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=Up({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(lr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r?.transportType,internal:r?.internal}),{topic:s,uri:u}}),J(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[Wt.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=Np(r.uri);i.props.properties.topic=s,i.addTrace(Wt.pairing_uri_validation_success),i.addTrace(Wt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(Wt.existing_pairing),l.active)throw i.setError(fn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(Wt.pairing_not_expired)}const h=c||Ee(M.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(s,h),await this.pairings.set(s,f),i.addTrace(Wt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(lr.create,f),i.addTrace(Wt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(Wt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(fn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(p){throw i.setError(fn.subscribe_pairing_topic_failure),p}return i.addTrace(Wt.subscribe_pairing_topic_success),f}),J(this,"activate",async({topic:r})=>{this.isInitialized();const i=Ee(M.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),J(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:i}=r;if(this.pairings.keys.includes(i)){const s=await this.sendRequest(i,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=rr();this.events.once(re("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),J(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),J(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),J(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),J(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:i}=r;this.pairings.keys.includes(i)&&(await this.sendRequest(i,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(i))}),J(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return Up({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),J(this,"sendRequest",async(r,i,s)=>{const o=hn(i,s),a=await this.core.crypto.encode(r,o),c=zi[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),J(this,"sendResult",async(r,i,s)=>{const o=oo(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=zi[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"sendError",async(r,i,s)=>{const o=jc(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=zi[c]?zi[c].res:zi.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),J(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),J(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>An(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),J(this,"onRelayEventRequest",async r=>{const{topic:i,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(i,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(i,s);default:return await this.onUnknownRpcMethodRequest(i,s)}}),J(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s}=r,o=(await this.core.history.get(i,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(i,s);default:return this.onUnknownRpcMethodResponse(o)}}),J(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(lr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),J(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{Kt(i)?this.events.emit(re("pairing_ping",s),{}):It(i)&&this.events.emit(re("pairing_ping",s),{error:i.error})},500)}),J(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(lr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),J(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),J(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),J(this,"isValidPair",(r,i)=>{var s;if(!st(r)){const{message:a}=z("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(!kI(r.uri)){const{message:a}=z("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(fn.malformed_pairing_uri),new Error(a)}const o=Np(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=z("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(fn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&M.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(fn.pairing_expired);const{message:a}=z("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),J(this,"isValidPing",async r=>{if(!st(r)){const{message:s}=z("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),J(this,"isValidDisconnect",async r=>{if(!st(r)){const{message:s}=z("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),J(this,"isValidPairingTopic",async r=>{if(!we(r,!1)){const{message:i}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(An(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=z("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ke(n,this.name),this.pairings=new fr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return Je(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(ge.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Vc(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:n,payload:s}),this.core.history.delete(n,s.id)),await this.core.relayer.messages.ack(n,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(At.expired,async e=>{const{topic:n}=fd(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(lr.expire,{topic:n}))})}}var SD=Object.defineProperty,AD=(t,e,n)=>e in t?SD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ne=(t,e,n)=>AD(t,typeof e!="symbol"?e+"":e,n);class DD extends aw{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ne(this,"records",new Map),Ne(this,"events",new Ve.exports.EventEmitter),Ne(this,"name",T6),Ne(this,"version",B6),Ne(this,"cached",[]),Ne(this,"initialized",!1),Ne(this,"storagePrefix",Ht),Ne(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ne(this,"set",(r,i,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:i,chainId:s}),this.records.has(i.id))return;const o={id:i.id,topic:r,request:{method:i.method,params:i.params||null},chainId:s,expiry:Ee(M.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Nt.created,o)}),Ne(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const i=await this.getRecord(r.id);typeof i.response>"u"&&(i.response=It(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(Nt.updated,i))}),Ne(this,"get",async(r,i)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:i}),await this.getRecord(i))),Ne(this,"delete",(r,i)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:i}),this.values.forEach(s=>{if(s.topic===r){if(typeof i<"u"&&s.id!==i)return;this.records.delete(s.id),this.events.emit(Nt.deleted,s)}}),this.persist()}),Ne(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ne(this,"on",(r,i)=>{this.events.on(r,i)}),Ne(this,"once",(r,i)=>{this.events.once(r,i)}),Ne(this,"off",(r,i)=>{this.events.off(r,i)}),Ne(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get size(){return this.records.size}get keys(){return Array.from(this.records.keys())}get values(){return Array.from(this.records.values())}get pending(){const e=[];return this.values.forEach(n=>{if(typeof n.response<"u")return;const r={topic:n.topic,request:hn(n.request.method,n.request.params,n.id),chainId:n.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const n=this.records.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Nt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Nt.created,e=>{const n=Nt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Nt.updated,e=>{const n=Nt.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(Nt.deleted,e=>{const n=Nt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Vn.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{M.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(Nt.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var OD=Object.defineProperty,$D=(t,e,n)=>e in t?OD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qe=(t,e,n)=>$D(t,typeof e!="symbol"?e+"":e,n);class TD extends dw{constructor(e,n){super(e,n),this.core=e,this.logger=n,qe(this,"expirations",new Map),qe(this,"events",new Ve.exports.EventEmitter),qe(this,"name",P6),qe(this,"version",C6),qe(this,"cached",[]),qe(this,"initialized",!1),qe(this,"storagePrefix",Ht),qe(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),qe(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),qe(this,"set",(r,i)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:i};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(At.created,{target:s,expiration:o})}),qe(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),qe(this,"del",r=>{if(this.isInitialized(),this.has(r)){const i=this.formatTarget(r),s=this.getExpiration(i);this.expirations.delete(i),this.events.emit(At.deleted,{target:i,expiration:s})}}),qe(this,"on",(r,i)=>{this.events.on(r,i)}),qe(this,"once",(r,i)=>{this.events.once(r,i)}),qe(this,"off",(r,i)=>{this.events.off(r,i)}),qe(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ke(n,this.name)}get context(){return Je(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}get length(){return this.expirations.size}get keys(){return Array.from(this.expirations.keys())}get values(){return Array.from(this.expirations.values())}formatTarget(e){if(typeof e=="string")return Ex(e);if(typeof e=="number")return xx(e);const{message:n}=z("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(n)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(At.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=z("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(n),new Error(n)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const n=this.expirations.get(e);if(!n){const{message:r}=z("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;M.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(At.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Vn.pulse,()=>this.checkExpirations()),this.events.on(At.created,e=>{const n=At.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(At.expired,e=>{const n=At.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(At.deleted,e=>{const n=At.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}}var BD=Object.defineProperty,PD=(t,e,n)=>e in t?BD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,me=(t,e,n)=>PD(t,typeof e!="symbol"?e+"":e,n);class CD extends pw{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,me(this,"name",R6),me(this,"abortController"),me(this,"isDevEnv"),me(this,"verifyUrlV3",U6),me(this,"storagePrefix",Ht),me(this,"version",ag),me(this,"publicKey"),me(this,"fetchPromise"),me(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&M.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),me(this,"register",async i=>{if(!Dr()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=i,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const u=Yn(),l=this.startAbortTimer(M.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",y),u.body.removeChild(g),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const g=u.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",d,{signal:this.abortController.signal});const y=_=>{if(_.data&&typeof _.data=="string")try{const A=JSON.parse(_.data);if(A.type==="verify_attestation"){if(Qo(A.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",y),f(A.attestation===null?"":A.attestation)}}catch(A){this.logger.warn(A)}};u.body.appendChild(g),window.addEventListener("message",y,{signal:this.abortController.signal})});return this.logger.debug("jwt attestation",h),h}catch(u){this.logger.warn(u)}return""}),me(this,"resolve",async i=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=i;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Qo(s).payload.id!==a)return;const u=await this.isValidJwtAttestation(s);if(u){if(!u.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return u}}if(!o)return;const c=this.getVerifyUrl(i?.verifyUrl);return this.fetchAttestation(o,c)}),me(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(M.ONE_SECOND*5),a=await fetch(`${s}/attestation/${i}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),me(this,"getVerifyUrl",i=>{let s=i||qi;return F6.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${qi}`),s=qi),s}),me(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(M.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(i),await s.json()}catch(i){this.logger.warn(i)}}),me(this,"persistPublicKey",async i=>{this.logger.debug("persisting public key to local storage",i),await this.store.setItem(this.storeKey,i),this.publicKey=i}),me(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),me(this,"isValidJwtAttestation",async i=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(i,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(i,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),me(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),me(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const i=await this.fetchPromise;return this.fetchPromise=void 0,i}),me(this,"validateAttestation",(i,s)=>{const o=yI(i,s.publicKey),a={hasExpired:M.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=Ke(n,this.name),this.abortController=new AbortController,this.isDevEnv=rc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return Je(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),M.toMiliseconds(e))}}var RD=Object.defineProperty,ND=(t,e,n)=>e in t?RD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qg=(t,e,n)=>ND(t,typeof e!="symbol"?e+"":e,n);class UD extends gw{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,qg(this,"context",k6),qg(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${L6}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:i,type:o,token:s,always_raw:a})})}),this.logger=Ke(n,this.context)}}var FD=Object.defineProperty,jg=Object.getOwnPropertySymbols,kD=Object.prototype.hasOwnProperty,LD=Object.prototype.propertyIsEnumerable,nu=(t,e,n)=>e in t?FD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Yi=(t,e)=>{for(var n in e||(e={}))kD.call(e,n)&&nu(t,n,e[n]);if(jg)for(var n of jg(e))LD.call(e,n)&&nu(t,n,e[n]);return t},De=(t,e,n)=>nu(t,typeof e!="symbol"?e+"":e,n);class MD extends yw{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,De(this,"context",z6),De(this,"storagePrefix",Ht),De(this,"storageVersion",M6),De(this,"events",new Map),De(this,"shouldPersist",!1),De(this,"init",async()=>{if(!rc())try{const i={eventId:pd(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:ld(this.core.relayer.protocol,this.core.relayer.version,Kc)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),De(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=pd(),l=this.core.projectId||"",h=Date.now(),f=Yi({eventId:u,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),De(this,"getEvent",i=>{const{eventId:s,topic:o}=i;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return Yi(Yi({},a),this.setMethods(a.eventId))}),De(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),De(this,"setEventListeners",()=>{this.core.heartbeat.on(Vn.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{M.fromMiliseconds(Date.now())-M.fromMiliseconds(i.timestamp)>q6&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),De(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),De(this,"addTrace",(i,s)=>{const o=this.events.get(i);o&&(o.props.properties.trace.push(s),this.events.set(i,o),this.shouldPersist=!0)}),De(this,"setError",(i,s)=>{const o=this.events.get(i);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(i,o),this.shouldPersist=!0)}),De(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),De(this,"restore",async()=>{try{const i=await this.core.storage.getItem(this.storageKey)||[];if(!i.length)return;i.forEach(s=>{this.events.set(s.eventId,Yi(Yi({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),De(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const i=[];for(const[s,o]of this.events)o.props.type&&i.push(o);if(i.length!==0)try{if((await this.sendEvent(i)).ok)for(const s of i)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),De(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${j6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Kc}${s}`,{method:"POST",body:JSON.stringify(i)})}),De(this,"getAppDomain",()=>ud().url),this.logger=Ke(n,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var zD=Object.defineProperty,Vg=Object.getOwnPropertySymbols,qD=Object.prototype.hasOwnProperty,jD=Object.prototype.propertyIsEnumerable,ru=(t,e,n)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kg=(t,e)=>{for(var n in e||(e={}))qD.call(e,n)&&ru(t,n,e[n]);if(Vg)for(var n of Vg(e))jD.call(e,n)&&ru(t,n,e[n]);return t},le=(t,e,n)=>ru(t,typeof e!="symbol"?e+"":e,n);class iu extends rw{constructor(e){var n;super(e),le(this,"protocol",og),le(this,"version",ag),le(this,"name",co),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new Ve.exports.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const r=this.getGlobalCore(e?.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||lg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Po({level:typeof e?.logger=="string"&&e.logger?e.logger:l6.logger,name:co}),{logger:s,chunkLoggerController:o}=ew({opts:i,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(n=this.logChunkController)!=null&&n.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=Ke(s,this.name),this.heartbeat=new So,this.crypto=new wA(this,this.logger,e?.keychain),this.history=new DD(this,this.logger),this.expirer=new TD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new Ay(Kg(Kg({},h6),e?.storageOptions)),this.relayer=new VA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new ID(this,this.logger),this.verify=new CD(this,this.logger,this.storage),this.echoClient=new UD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new MD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new iu(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(S6,r),n}get context(){return Je(this.logger)}async start(){this.initialized||await this.initialize()}async getLogsBlob(){var e;return(e=this.logChunkController)==null?void 0:e.logsToBlob({clientId:await this.crypto.getClientId()})}async addLinkModeSupportedApp(e){this.linkModeSupportedApps.includes(e)||(this.linkModeSupportedApps.push(e),await this.storage.setItem(hg,this.linkModeSupportedApps))}async initialize(){this.logger.trace("Initialized");try{await this.crypto.init(),await this.history.init(),await this.expirer.init(),await this.relayer.init(),await this.heartbeat.init(),await this.pairing.init(),this.linkModeSupportedApps=await this.storage.getItem(hg)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(`Core Initialization Failure at epoch ${Date.now()}`,e),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){var n;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((n=e.opts)==null?void 0:n.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof process<"u"&&process.env.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const VD=iu,Hg="wc",Wg=2,Gg="client",su=`${Hg}@${Wg}:${Gg}:`,ou={name:Gg,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Yg="WALLETCONNECT_DEEPLINK_CHOICE",KD="proposal",Zg="Proposal expired",HD="session",Lr=M.SEVEN_DAYS,WD="engine",Ue={wc_sessionPropose:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1104},res:{ttl:M.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1106},res:{ttl:M.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:M.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1112},res:{ttl:M.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:M.ONE_DAY,prompt:!1,tag:1114},res:{ttl:M.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:M.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:M.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:M.FIVE_MINUTES,prompt:!1,tag:1119}}},au={min:M.FIVE_MINUTES,max:M.SEVEN_DAYS},Yt={idle:"IDLE",active:"ACTIVE"},GD={eth_sendTransaction:{key:""},eth_sendRawTransaction:{key:""},wallet_sendCalls:{key:""},solana_signTransaction:{key:"signature"},solana_signAllTransactions:{key:"transactions"},solana_signAndSendTransaction:{key:"signature"},sui_signAndExecuteTransaction:{key:"digest"},sui_signTransaction:{key:""},hedera_signAndExecuteTransaction:{key:"transactionId"},hedera_executeTransaction:{key:"transactionId"},near_signTransaction:{key:""},near_signTransactions:{key:""},tron_signTransaction:{key:"txID"},xrpl_signTransaction:{key:""},xrpl_signTransactionFor:{key:""},algo_signTxn:{key:""},sendTransfer:{key:"txid"},stacks_stxTransfer:{key:"txId"},polkadot_signTransaction:{key:""},cosmos_signDirect:{key:""}},YD="request",ZD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],JD="wc",XD="auth",QD="authKeys",e5="pairingTopics",t5="requests",ho=`${JD}@${1.5}:${XD}:`,fo=`${ho}:PUB_KEY`;var n5=Object.defineProperty,r5=Object.defineProperties,i5=Object.getOwnPropertyDescriptors,Jg=Object.getOwnPropertySymbols,s5=Object.prototype.hasOwnProperty,o5=Object.prototype.propertyIsEnumerable,cu=(t,e,n)=>e in t?n5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ie=(t,e)=>{for(var n in e||(e={}))s5.call(e,n)&&cu(t,n,e[n]);if(Jg)for(var n of Jg(e))o5.call(e,n)&&cu(t,n,e[n]);return t},je=(t,e)=>r5(t,i5(e)),k=(t,e,n)=>cu(t,typeof e!="symbol"?e+"":e,n);class a5 extends vw{constructor(e){super(e),k(this,"name",WD),k(this,"events",new Ve.exports),k(this,"initialized",!1),k(this,"requestQueue",{state:Yt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:Yt.idle,queue:[]}),k(this,"emittedSessionRequests",new Bx({limit:500})),k(this,"requestQueueDelay",M.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Ue)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();const r=je(ie({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(r),r.optionalNamespaces=CI(r.requiredNamespaces,r.optionalNamespaces),r.requiredNamespaces={};const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:o,sessionProperties:a,scopedProperties:c,relays:u}=r;let l=i,h,f=!1;try{if(l){const T=this.client.core.pairing.pairings.get(l);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),f=T.active}}catch(T){throw this.client.logger.error(`connect() -> pairing.get(${l}) failed`),T}if(!l||!f){const{topic:T,uri:R}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});l=T,h=R}if(!l){const{message:T}=z("NO_MATCHING_KEY",`connect() pairing topic: ${l}`);throw new Error(T)}const p=await this.client.core.crypto.generateKeyPair(),d=Ue.wc_sessionPropose.req.ttl||M.FIVE_MINUTES,g=Ee(d),y=je(ie(ie({requiredNamespaces:s,optionalNamespaces:o,relays:u??[{protocol:ug}],proposer:{publicKey:p,metadata:this.client.metadata},expiryTimestamp:g,pairingTopic:l},a&&{sessionProperties:a}),c&&{scopedProperties:c}),{id:ot()}),_=re("session_connect",y.id),{reject:A,resolve:b,done:v}=rr(d,Zg),x=({id:T})=>{T===y.id&&(this.client.events.off("proposal_expire",x),this.pendingSessions.delete(y.id),this.events.emit(_,{error:{message:Zg,code:0}}))};return this.client.events.on("proposal_expire",x),this.events.once(_,({error:T,session:R})=>{this.client.events.off("proposal_expire",x),T?A(T):R&&b(R)}),await this.sendProposeSession({proposal:y,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:y.id}}}),await this.setProposal(y.id,y),{uri:h,approval:v}}),k(this,"pair",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(n)}catch(r){throw this.client.logger.error("pair() failed"),r}}),k(this,"approve",async n=>{var r,i,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=n?.id)==null?void 0:r.toString(),trace:[Mn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(m){throw o.setError(ji.no_internet_connection),m}try{await this.isValidProposalId(n?.id)}catch(m){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(ji.proposal_not_found),m}try{await this.isValidApprove(n)}catch(m){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(ji.session_approve_namespace_validation_failure),m}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:d,proposer:g,requiredNamespaces:y,optionalNamespaces:_}=p;let A=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:d});A||(A=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Mn.session_approve_started,properties:{topic:d,trace:[Mn.session_approve_started,Mn.session_namespaces_validation_success]}}));const b=await this.client.core.crypto.generateKeyPair(),v=g.publicKey,x=await this.client.core.crypto.generateSharedKey(b,v),T=ie(ie(ie({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:b,metadata:this.client.metadata},expiry:Ee(Lr)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),R=he.relay;A.addTrace(Mn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(x,{transportType:R,internal:{skipSubscribe:!0}})}catch(m){throw A.setError(ji.subscribe_session_topic_failure),m}A.addTrace(Mn.subscribe_session_topic_success);const C=je(ie({},T),{topic:x,requiredNamespaces:y,optionalNamespaces:_,pairingTopic:d,acknowledged:!1,self:T.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:b,transportType:he.relay});await this.client.session.set(x,C),A.addTrace(Mn.store_session);try{await this.sendApproveSession({sessionTopic:x,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:b},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:a}}}),A.addTrace(Mn.session_approve_publish_success)}catch(m){throw this.client.logger.error(m),this.client.session.delete(x,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(x),m}return this.client.core.eventClient.deleteEvent({eventId:A.eventId}),await this.client.core.pairing.updateMetadata({topic:d,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:d}),await this.setExpiry(x,Ee(Lr)),{topic:x,acknowledged:()=>Promise.resolve(this.client.session.get(x))}}),k(this,"reject",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(n)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:i}=n;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:i,rpcOpts:Ue.wc_sessionPropose.reject}),await this.deleteProposal(r)}),k(this,"update",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(n)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:i}=n,{done:s,resolve:o,reject:a}=rr(),c=ot(),u=Ln().toString(),l=this.client.session.get(r).namespaces;return this.events.once(re("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:i}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:i},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:l}),a(h)}),{acknowledged:s}}),k(this,"extend",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(n)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=n,i=ot(),{done:s,resolve:o,reject:a}=rr();return this.events.once(re("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Ee(Lr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(y){throw this.client.logger.error("request() -> isValidRequest() failed"),y}const{chainId:r,request:i,topic:s,expiry:o=Ue.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const c=ot(),u=Ln().toString(),{done:l,resolve:h,reject:f}=rr(o,"Request expired. Please try again.");this.events.once(re("session_request",c),({error:y,result:_})=>{y?f(y):h(_)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:{request:je(ie({},i),{expiryTimestamp:Ee(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(y=>f(y)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:je(ie({},i),{expiryTimestamp:Ee(o)}),chainId:r};return await Promise.all([new Promise(async y=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:p,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),y()}),new Promise(async y=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const A=await Ax(this.client.core.storage,Yg);await _x({id:c,topic:s,wcDeepLink:A})}y()}),l()]).then(y=>y[2])}),k(this,"respond",async n=>{this.isInitialized(),await this.isValidRespond(n);const{topic:r,response:i}=n,{id:s}=i,o=this.client.session.get(r);o.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const a=this.getAppLinkIfEnabled(o.peer.metadata,o.transportType);Kt(i)?await this.sendResult({id:s,topic:r,result:i.result,throwOnFailedPublish:!0,appLink:a}):It(i)&&await this.sendError({id:s,topic:r,error:i.error,appLink:a}),this.cleanupAfterResponse(n)}),k(this,"ping",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(n)}catch(i){throw this.client.logger.error("ping() -> isValidPing() failed"),i}const{topic:r}=n;if(this.client.session.keys.includes(r)){const i=ot(),s=Ln().toString(),{done:o,resolve:a,reject:c}=rr();this.events.once(re("session_ping",i),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:i,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),k(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=Ln().toString(),a=ot();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(n);const{topic:r}=n;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:i}=z("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),k(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>UI(r,n)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(n,r)=>{var i;this.isInitialized(),this.isValidAuthenticate(n);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((i=this.client.metadata.redirect)==null?void 0:i.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:g=[],expiry:y}=n,_=[...n.resources||[]],{topic:A,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:A,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),x=ro(v);if(await Promise.all([this.client.auth.authKeys.set(fo,{responseTopic:x,publicKey:v}),this.client.auth.pairingTopics.set(x,{topic:x,pairingTopic:A})]),await this.client.core.relayer.subscribe(x,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${A}`),g.length>0){const{namespace:D}=tr(a[0]);let N=z_(D,"request",g);Ks(_)&&(N=j_(N,_.pop())),_.push(N)}const T=y&&y>Ue.wc_sessionAuthenticate.req.ttl?y:Ue.wc_sessionAuthenticate.req.ttl,R={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ee(T)},C={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},m={requiredNamespaces:{},optionalNamespaces:C,relays:[{protocol:"irn"}],pairingTopic:A,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:Ee(Ue.wc_sessionPropose.req.ttl),id:ot()},{done:B,resolve:S,reject:O}=rr(T,"Request expired"),P=ot(),F=re("session_connect",m.id),E=re("session_request",P),w=async({error:D,session:N})=>{this.events.off(E,I),D?O(D):N&&S({session:N})},I=async D=>{var N,U,L;if(await this.deletePendingAuthRequest(P,{message:"fulfilled",code:0}),D.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return D.error.code===W.code?void 0:(this.events.off(F,w),O(D.error.message))}await this.deleteProposal(m.id),this.events.off(F,w);const{cacaos:j,responder:V}=D.result,K=[],H=[];for(const W of j){await kd({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),O(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:ae}=W,ye=Ks(ae.resources),gt=[gc(ae.iss)],Ot=Vs(ae.iss);if(ye){const $t=zd(ye),Zt=qd(ye);K.push(...$t),gt.push(...Zt)}for(const $t of gt)H.push(`${$t}:${Ot}`)}const Z=await this.client.core.crypto.generateSharedKey(v,V.publicKey);let Q;K.length>0&&(Q={topic:Z,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:Ee(Lr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:A,namespaces:zp([...new Set(K)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(Z,{transportType:o}),await this.client.session.set(Z,Q),A&&await this.client.core.pairing.updateMetadata({topic:A,metadata:V.metadata}),Q=this.client.session.get(Z)),(N=this.client.metadata.redirect)!=null&&N.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(L=V.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(Z,{transportType:he.link_mode})),S({auths:j,session:Q})};this.events.once(F,w),this.events.once(E,I);let $;try{if(s){const D=hn("wc_sessionAuthenticate",R,P);this.client.core.history.set(A,D);const N=await this.client.core.crypto.encode("",D,{type:Ci,encoding:kn});$=so(r,A,N)}else await Promise.all([this.sendRequest({topic:A,method:"wc_sessionAuthenticate",params:R,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:P}),this.sendRequest({topic:A,method:"wc_sessionPropose",params:m,expiry:Ue.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:m.id})])}catch(D){throw this.events.off(F,w),this.events.off(E,I),D}return await this.setProposal(m.id,m),await this.setAuthRequest(P,{request:je(ie({},R),{verifyContext:{}}),pairingTopic:A,transportType:o}),{uri:$??b,response:B}}),k(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[hr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(y){throw s.setError(Vi.no_internet_connection),y}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Vi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ro(c),h={type:cn,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const y of i){if(!await kd({cacao:y,projectId:this.client.core.projectId})){s.setError(Vi.invalid_cacao);const x=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:x,encodeOpts:h}),new Error(x.message)}s.addTrace(hr.cacaos_verified);const{p:_}=y,A=Ks(_.resources),b=[gc(_.iss)],v=Vs(_.iss);if(A){const x=zd(A),T=qd(A);f.push(...x),b.push(...T)}for(const x of b)p.push(`${x}:${v}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(hr.create_authenticated_session_topic);let g;if(f?.length>0){g={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Ee(Lr),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:zp([...new Set(f)],[...new Set(p)]),transportType:a},s.addTrace(hr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(y){throw s.setError(Vi.subscribe_authenticated_session_topic_failure),y}s.addTrace(hr.subscribe_authenticated_session_topic_success),await this.client.session.set(d,g),s.addTrace(hr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(hr.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:r,result:{cacaos:i,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(y){throw s.setError(Vi.authenticated_session_approve_publish_failure),y}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async n=>{this.isInitialized();const{id:r,reason:i}=n,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ro(o),u={type:cn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ue.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),k(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return Ld(r,i)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const n=this.relayMessageCache.shift();n&&await this.onRelayMessage(n)}catch(n){this.client.logger.error(n)}},50)}),k(this,"cleanupDuplicatePairings",async n=>{if(n.pairingTopic)try{const r=this.client.core.pairing.pairings.get(n.pairingTopic),i=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===n.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(i.length===0)return;this.client.logger.info(`Cleaning up ${i.length} duplicate pairing(s)`),await Promise.all(i.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),k(this,"deleteSession",async n=>{var r;const{topic:i,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=n,{self:c}=this.client.session.get(i);await this.client.core.relayer.unsubscribe(i),await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(i,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(i)&&await this.client.core.crypto.deleteSymKey(i),s||this.client.core.expirer.del(i),this.client.core.storage.removeItem(Yg).catch(u=>this.client.logger.warn(u)),this.getPendingSessionRequests().forEach(u=>{u.topic===i&&this.deletePendingSessionRequest(u.id,fe("USER_DISCONNECTED"))}),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=Yt.idle),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),k(this,"deleteProposal",async(n,r)=>{if(r)try{const i=this.client.proposal.get(n);this.client.core.eventClient.getEvent({topic:i.pairingTopic})?.setError(ji.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),k(this,"deletePendingSessionRequest",async(n,r,i=!1)=>{await Promise.all([this.client.pendingRequest.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==n),i&&(this.sessionRequestQueue.state=Yt.idle,this.client.events.emit("session_request_expire",{id:n}))}),k(this,"deletePendingAuthRequest",async(n,r,i=!1)=>{await Promise.all([this.client.auth.requests.delete(n,r),i?Promise.resolve():this.client.core.expirer.del(n)])}),k(this,"setExpiry",async(n,r)=>{this.client.session.keys.includes(n)&&(this.client.core.expirer.set(n,r),await this.client.session.update(n,{expiry:r}))}),k(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Ee(Ue.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),k(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=he.relay}=r;this.client.core.expirer.set(n,i.expiryTimestamp),await this.client.auth.requests.set(n,{authPayload:i.authPayload,requester:i.requester,expiryTimestamp:i.expiryTimestamp,id:n,pairingTopic:s,verifyContext:i.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Ee(Ue.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:i,params:s,verifyContext:o})}),k(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=n,p=hn(i,s,c);let d;const g=!!l;try{const A=g?kn:it;d=await this.client.core.crypto.encode(r,p,{encoding:A})}catch(A){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),A}let y;if(ZD.includes(i)){const A=_t(JSON.stringify(p)),b=_t(d);y=await this.client.core.verify.register({id:b,decryptedId:A})}const _=ie(ie({},Ue[i].req),f);if(_.attestation=y,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(r,p),g){const A=so(l,r,d);await global.Linking.openURL(A,this.client.name)}else _.tvf=je(ie({},h),{correlationId:p.id}),u?(_.internal=je(ie({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,d,_)):this.client.core.relayer.publish(r,d,_).catch(A=>this.client.logger.error(A));return p.id}),k(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=hn("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:it}),a=_t(JSON.stringify(s)),c=_t(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:je(ie({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),k(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=oo(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:it}),l=hn("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(r,l,{encoding:it});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:je(ie({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=oo(r,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const d=h?kn:it;l=await this.client.core.crypto.encode(i,u,je(ie({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),d}let f,p;try{f=await this.client.core.history.get(i,r);const d=f.request;try{p=this.getTVFParams(r,d.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${i}, ${r}) failed`),d}if(h){const d=so(c,i,l);await global.Linking.openURL(d,this.client.name)}else{const d=f.request.method,g=Ue[d].res;g.tvf=je(ie({},p),{correlationId:r}),o?(g.internal=je(ie({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(y=>this.client.logger.error(y))}await this.client.core.history.resolve(u)}),k(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=jc(r,s);let l;const h=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=h?kn:it;l=await this.client.core.crypto.encode(i,u,je(ie({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),p}let f;try{f=await this.client.core.history.get(i,r)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),p}if(h){const p=so(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||Ue[p].res;this.client.core.relayer.publish(i,l,d)}await this.client.core.history.resolve(u)}),k(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;An(i.expiry)&&(s=!0),this.client.core.crypto.keychain.has(i.topic)||(s=!0),s&&n.push(i.topic)}),this.client.proposal.getAll().forEach(i=>{An(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),k(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),k(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Yt.active){this.client.logger.info("Request queue already active, skipping...");return}for(this.client.logger.info(`Request queue starting with ${this.requestQueue.queue.length} requests`);this.requestQueue.queue.length>0;){this.requestQueue.state=Yt.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=Yt.idle}),k(this,"processRequest",async n=>{const{topic:r,payload:i,attestation:s,transportType:o,encryptedId:a}=n,c=i.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:i,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,i);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,i);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,i);case"wc_sessionPing":return await this.onSessionPingRequest(r,i);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,i);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,i);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:i,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async n=>{const{topic:r,payload:i,transportType:s}=n,o=(await this.client.core.history.get(r,i.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,i,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,i);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,i);case"wc_sessionExtend":return this.onSessionExtendResponse(r,i);case"wc_sessionPing":return this.onSessionPingResponse(r,i);case"wc_sessionRequest":return this.onSessionRequestResponse(r,i);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,i);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=z("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),k(this,"shouldIgnorePairingRequest",n=>{const{topic:r,requestMethod:i}=n,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(i)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async n=>{const{topic:r,payload:i,attestation:s,encryptedId:o}=n,{params:a,id:c}=i;try{const u=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(fn.proposal_listener_not_found)),this.isValidConnect(ie({},i.params));const l=a.expiryTimestamp||Ee(Ue.wc_sessionPropose.req.ttl),h=ie({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:_t(JSON.stringify(i)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(Wt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ue.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),k(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(Kt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const u=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:u});const l=await this.client.core.crypto.generateSharedKey(c,u);this.pendingSessions.set(s,{sessionTopic:l,pairingTopic:n,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:i});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:n})}else if(It(r)){await this.deleteProposal(s);const o=re("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),k(this,"onSessionSettleRequest",async(n,r)=>{const{id:i,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f}=r.params,p=[...this.pendingSessions.values()].find(y=>y.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const d=this.client.proposal.get(p.proposalId),g=je(ie(ie(ie({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:d.requiredNamespaces,optionalNamespaces:d.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:g.peer.metadata}),this.client.events.emit("session_connect",{session:g}),this.events.emit(re("session_connect",p.proposalId),{session:g}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:r.id,topic:n,result:!0})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;Kt(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(re("session_approve",i),{})):It(r)&&(await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.events.emit(re("session_approve",i),{error:r.error}))}),k(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=ki.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:n,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(ie({topic:n},i));try{ki.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw ki.delete(o),c}this.client.events.emit("session_update",{id:s,topic:n,params:i})}catch(o){await this.sendError({id:s,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=re("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_update",i),{}):It(r)&&this.events.emit(re("session_update",i),{error:r.error})}),k(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Ee(Lr)),await this.sendResult({id:i,topic:n,result:!0}),this.client.events.emit("session_extend",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=re("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_extend",i),{}):It(r)&&this.events.emit(re("session_extend",i),{error:r.error})}),k(this,"onSessionPingRequest",async(n,r)=>{const{id:i}=r;try{this.isValidPing({topic:n}),await this.sendResult({id:i,topic:n,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:i,topic:n})}catch(s){await this.sendError({id:i,topic:n,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=re("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Kt(r)?this.events.emit(re("session_ping",i),{}):It(r)&&this.events.emit(re("session_ping",i),{error:r.error})},500)}),k(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{this.isValidDisconnect({topic:n,reason:r.params}),await Promise.all([new Promise(s=>{this.client.core.relayer.once(ge.publish,async()=>{s(await this.deleteSession({topic:n,id:i}))})}),this.sendResult({id:i,topic:n,result:!0}),this.cleanupPendingSentRequestsForTopic({topic:n,error:fe("USER_DISCONNECTED")})]).catch(s=>this.client.logger.error(s))}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:h,params:f}=a;try{await this.isValidRequest(ie({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:_t(JSON.stringify(hn("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),g={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(g),l===he.link_mode&&(r=p.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=p.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),k(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=re("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Kt(r)?this.events.emit(re("session_request",i),{result:r.result}):It(r)&&this.events.emit(re("session_request",i),{error:r.error})}),k(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=ki.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(ie({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),ki.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),Kt(r)?this.events.emit(re("session_request",i),{result:r.result}):It(r)&&this.events.emit(re("session_request",i),{error:r.error})}),k(this,"onSessionAuthenticateRequest",async n=>{var r;const{topic:i,payload:s,attestation:o,encryptedId:a,transportType:c}=n;try{const{requester:u,authPayload:l,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:_t(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:p,pairingTopic:i,transportType:c}),c===he.link_mode&&(r=u.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:i,params:s.params,id:s.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),p={type:cn,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:p,rpcOpts:Ue.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),k(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Yt.idle,this.processSessionRequestQueue()},M.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:n,error:r})=>{const i=this.client.core.history.pending;i.length>0&&i.filter(s=>s.topic===n&&s.request.method==="wc_sessionRequest").forEach(s=>{const o=s.request.id,a=re("session_request",o);if(this.events.listenerCount(a)===0)throw new Error(`emitting ${a} without any listeners`);this.events.emit(re("session_request",s.request.id),{error:r})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Yt.active){this.client.logger.info("session request queue is already active.");return}const n=this.sessionRequestQueue.queue[0];if(!n){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(n)}catch(r){this.client.logger.error(r)}}),k(this,"emitSessionRequest",n=>{if(this.emittedSessionRequests.has(n.id)){this.client.logger.warn({id:n.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${n.id}`);return}this.sessionRequestQueue.state=Yt.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),k(this,"onPairingCreated",n=>{if(n.methods&&this.expectedPairingMethodMap.set(n.topic,n.methods),n.active)return;const r=this.client.proposal.getAll().find(i=>i.pairingTopic===n.topic);r&&this.onSessionProposeRequest({topic:n.topic,payload:hn("wc_sessionPropose",je(ie({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),k(this,"isValidConnect",async n=>{if(!st(n)){const{message:u}=z("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(n)}`);throw new Error(u)}const{pairingTopic:r,requiredNamespaces:i,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=n;if(_e(r)||await this.isValidPairingTopic(r),!GI(c,!0)){const{message:u}=z("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(!_e(i)&&Ui(i)!==0){const u="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(u):this.client.logger.warn(u),this.validateNamespaces(i,"requiredNamespaces")}if(!_e(s)&&Ui(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(i||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(l=>u.includes(l.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(u)}`)}}),k(this,"validateNamespaces",(n,r)=>{const i=WI(n,"connect()",r);if(i)throw new Error(i.message)}),k(this,"isValidApprove",async n=>{if(!st(n))throw new Error(z("MISSING_OR_INVALID",`approve() params: ${n}`).message);const{id:r,namespaces:i,relayProtocol:s,sessionProperties:o,scopedProperties:a}=n;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),u=Uc(i,"approve()");if(u)throw new Error(u.message);const l=Hp(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!we(s,!0)){const{message:h}=z("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(_e(o)||this.validateSessionProps(o,"sessionProperties"),!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(i));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async n=>{if(!st(n)){const{message:s}=z("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!ZI(i)){const{message:s}=z("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",n=>{if(!st(n)){const{message:u}=z("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!Vp(r)){const{message:u}=z("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=zI(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Uc(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(An(o)){const{message:u}=z("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),k(this,"isValidUpdate",async n=>{if(!st(n)){const{message:c}=z("MISSING_OR_INVALID",`update() params: ${n}`);throw new Error(c)}const{topic:r,namespaces:i}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=Uc(i,"update()");if(o)throw new Error(o.message);const a=Hp(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),k(this,"isValidRequest",async n=>{if(!st(n)){const{message:c}=z("MISSING_OR_INVALID",`request() params: ${n}`);throw new Error(c)}const{topic:r,request:i,chainId:s,expiry:o}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!Kp(a,s)){const{message:c}=z("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!JI(i)){const{message:c}=z("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!eS(a,s,i.method)){const{message:c}=z("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}if(o&&!iS(o,au)){const{message:c}=z("MISSING_OR_INVALID",`request() expiry: ${o}. Expiry must be a number (in seconds) between ${au.min} and ${au.max}`);throw new Error(c)}}),k(this,"isValidRespond",async n=>{var r;if(!st(n)){const{message:o}=z("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(o)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(o){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),o}if(!XI(s)){const{message:o}=z("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(o)}}),k(this,"isValidPing",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidEmit",async n=>{if(!st(n)){const{message:a}=z("MISSING_OR_INVALID",`emit() params: ${n}`);throw new Error(a)}const{topic:r,event:i,chainId:s}=n;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!Kp(o,s)){const{message:a}=z("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!QI(i)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!tS(o,s,i.name)){const{message:a}=z("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async n=>{if(!st(n)){const{message:i}=z("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidAuthenticate",n=>{const{chains:r,uri:i,domain:s,nonce:o}=n;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!we(i,!1))throw new Error("uri is required parameter");if(!we(s,!1))throw new Error("domain is required parameter");if(!we(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>tr(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=tr(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||qi,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const l=this.getAppLinkIfEnabled(o,a);return c.verified.validation=l&&new URL(l).origin===new URL(o.url).origin?"VALID":"INVALID",c}const u=await this.client.core.verify.resolve({attestationId:r,hash:i,encryptedId:s,verifyUrl:o.verifyUrl});u&&(c.verified.origin=u.origin,c.verified.isScam=u.isScam,c.verified.validation=u.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(u){this.client.logger.warn(u)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=z("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),k(this,"addToRecentlyDeleted",(n,r)=>{if(this.recentlyDeletedMap.set(n,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let i=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(i++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=z("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),k(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,h,f;return!n||r!==he.link_mode?!1:((s=(i=this.client.metadata)==null?void 0:i.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((u=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:u.universal)!==""&&((l=n?.redirect)==null?void 0:l.universal)!==void 0&&((h=n?.redirect)==null?void 0:h.universal)!==""&&((f=n?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),k(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=dd(n,"topic")||"",i=decodeURIComponent(dd(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var n;if(rc()||Sn()&&(n=this.client.metadata.redirect)!=null&&n.linkMode){const r=global==null?void 0:global.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const i=await r.getInitialURL();i&&setTimeout(()=>{this.handleLinkModeMessage({url:i})},50)}}}),k(this,"getTVFParams",(n,r,i)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:n,rpcMethods:[r.request.method],chainId:r.chainId};try{const u=this.extractTxHashesFromResult(r.request,i);c.txHashes=u,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(u){this.client.logger.warn("Error getting TVF params",u)}return c}),k(this,"isValidContractData",n=>{var r;if(!n)return!1;try{const i=n?.data||((r=n?.[0])==null?void 0:r.data);if(!i.startsWith("0x"))return!1;const s=i.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=GD[s];if(s==="sui_signTransaction")return[S_(r.transactionBytes)];if(s==="near_signTransaction")return[Rd(r)];if(s==="near_signTransactions")return r.map(c=>Rd(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[bS({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Ur(r)?r.map(c=>Nd(c)):[Nd(r)];if(s==="cosmos_signDirect")return[D_(r)];if(typeof r=="string")return[r];const a=r[o.key];if(Ur(a))return s==="solana_signAllTransactions"?a.map(c=>I_(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn("Error extracting tx hashes from result",s)}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,i]of Object.entries(n))for(const s of i)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn("processPendingMessageEvents failed",e)}}isInitialized(){if(!this.initialized){const{message:e}=z("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(ge.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:n,message:r,attestation:i,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(fo)?this.client.auth.authKeys.get(fo):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===he.link_mode?kn:it});Vc(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:_t(r)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:n,payload:a,transportType:s}),this.client.core.history.delete(n,a.id)):await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s}),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(At.expired,async e=>{const{topic:n,id:r}=fd(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,z("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,z("EXPIRED"),!0);n?this.client.session.keys.includes(n)&&(await this.deleteSession({topic:n,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:n})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(lr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(lr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!we(e,!1)){const{message:n}=z("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(n)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=z("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!we(e,!1)){const{message:n}=z("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(n)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=z("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=z("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(we(e,!1)){const{message:n}=z("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=z("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!YI(e)){const{message:n}=z("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=z("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(An(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=z("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}}class c5 extends fr{constructor(e,n){super(e,n,KD,su),this.core=e,this.logger=n}}class u5 extends fr{constructor(e,n){super(e,n,HD,su),this.core=e,this.logger=n}}class l5 extends fr{constructor(e,n){super(e,n,YD,su,r=>r.id),this.core=e,this.logger=n}}class h5 extends fr{constructor(e,n){super(e,n,QD,ho,()=>fo),this.core=e,this.logger=n}}class f5 extends fr{constructor(e,n){super(e,n,e5,ho),this.core=e,this.logger=n}}class d5 extends fr{constructor(e,n){super(e,n,t5,ho,r=>r.id),this.core=e,this.logger=n}}var p5=Object.defineProperty,g5=(t,e,n)=>e in t?p5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,uu=(t,e,n)=>g5(t,typeof e!="symbol"?e+"":e,n);class y5{constructor(e,n){this.core=e,this.logger=n,uu(this,"authKeys"),uu(this,"pairingTopics"),uu(this,"requests"),this.authKeys=new h5(this.core,this.logger),this.pairingTopics=new f5(this.core,this.logger),this.requests=new d5(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var w5=Object.defineProperty,m5=(t,e,n)=>e in t?w5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,X=(t,e,n)=>m5(t,typeof e!="symbol"?e+"":e,n);class lu extends bw{constructor(e){super(e),X(this,"protocol",Hg),X(this,"version",Wg),X(this,"name",ou.name),X(this,"metadata"),X(this,"core"),X(this,"logger"),X(this,"events",new Ve.exports.EventEmitter),X(this,"engine"),X(this,"session"),X(this,"proposal"),X(this,"pendingRequest"),X(this,"auth"),X(this,"signConfig"),X(this,"on",(r,i)=>this.events.on(r,i)),X(this,"once",(r,i)=>this.events.once(r,i)),X(this,"off",(r,i)=>this.events.off(r,i)),X(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),X(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),X(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),X(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),X(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),X(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||ou.name,this.metadata=wx(e?.metadata),this.signConfig=e?.signConfig;const n=typeof e?.logger<"u"&&typeof e?.logger!="string"?e.logger:kt(Po({level:e?.logger||ou.logger}));this.core=e?.core||new VD(e),this.logger=Ke(n,this.name),this.session=new u5(this.core,this.logger),this.proposal=new c5(this.core,this.logger),this.pendingRequest=new l5(this.core,this.logger),this.engine=new a5(this),this.auth=new y5(this.core,this.logger)}static async init(e){const n=new lu(e);return await n.initialize(),n}get context(){return Je(this.logger)}get pairing(){return this.core.pairing.pairings}async initialize(){this.logger.trace("Initialized");try{await this.core.start(),await this.session.init(),await this.proposal.init(),await this.pendingRequest.init(),await this.auth.init(),await this.engine.init(),this.logger.info("SignClient Initialization Success")}catch(e){throw this.logger.info("SignClient Initialization Failure"),this.logger.error(e.message),e}}}const b5=lu;class Xg{constructor(e){this.opts=e}}class Qg{constructor(e){this.client=e}}const e0=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Fi(r?.chainId))return!1;const{namespace:a}=tr(r.chainId),c=e.find(u=>u.name.toLowerCase()===a.toLowerCase());if(!c)throw new Error(`Unsupported token namespace: ${a}`);if(!c.assetNamespaces.map(u=>u.toLowerCase()).includes(s?.toLowerCase()))throw new Error(`Unsupported token standard: ${s} for namespace: ${a}`);return!0},v5=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!e0({supportedNamespaces:e,token:r}))};var E5=Object.defineProperty,x5=(t,e,n)=>e in t?E5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,de=(t,e,n)=>x5(t,typeof e!="symbol"?e+"":e,n);class _5 extends Qg{constructor(e){var n;super(e),de(this,"signClient"),de(this,"tokens",[]),de(this,"paymentIntentsMap",new Map),de(this,"paymentIntentToTransactionsMap",new Map),de(this,"supportedNamespaces",Du),de(this,"logger"),de(this,"init",async()=>{var r,i;this.signClient=await b5.init({projectId:this.client.opts.projectId,metadata:{name:this.client.metadata.merchantName,description:this.client.metadata.description,url:this.client.metadata.url,icons:[this.client.metadata.logoIcon]},storageOptions:{database:((r=this.client.opts.storageOptions)==null?void 0:r.databaseName)||Iu.database},logger:(i=this.client.opts.loggerOptions)==null?void 0:i.signLevel});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest(JSON.stringify({id:ot(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}));this.logger.debug("Received supported namespaces/networks",{supportedNamespaces:s.result.namespaces}),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error("Failed to fetch supported namespaces/networks",s)}}),de(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug("Setting tokens",{tokens:i}),i.forEach(s=>{if(!e0({token:s,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid token: ${JSON.stringify(s)}`)}),await new Promise(s=>{this.tokens=i,s()}),this.logger.debug("Tokens set",{tokens:i})}),de(this,"createPaymentIntent",async r=>{const{paymentIntents:i}=r;if(this.logger.debug("Creating payment intent",{paymentIntents:i}),i.length===0)throw new Error("No payment intents provided");i.forEach(u=>{if(!v5({paymentIntent:u,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(u)}`)}),this.logger.debug("Payment intent validation success",{paymentIntents:i});const s=this.composeNamespaces(i),{uri:o,approval:a}=await this.signClient.connect({optionalNamespaces:s});if(this.logger.debug("Connected to the WalletConnect network",{uri:o}),!o)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001}}),new Error("Failed to connect to the WalletConnect network");const c=ot();this.paymentIntentsMap.set(c,i),this.logger.debug("Payment intents map set",{intentId:c,paymentIntents:i}),this.emit("await_approval",{approval:a,intentId:c}),this.logger.debug("Emitted await_approval event",{intentId:c}),this.emit("qr_ready",{uri:o}),this.logger.debug("Emitted qr_ready event",{uri:o})}),de(this,"restart",async r=>{if(this.logger.debug("Restarting",{params:r}),r!=null&&r.reinit){this.tokens=[],this.paymentIntentsMap.clear(),this.paymentIntentToTransactionsMap.clear(),this.logger.debug("Restarted: Cleared payment intents map and payment intent to transactions map");return}const i=Array.from(this.paymentIntentsMap.values()).flat();await this.createPaymentIntent({paymentIntents:i}),this.logger.debug("Restarted: Created payment intent flow from the beginning",{paymentIntents:i})}),de(this,"emit",(r,i)=>(this.logger.debug("Emit",{event:r,args:i}),this.client.events.emit(r,i))),de(this,"on",(r,i)=>(this.logger.debug("On",{event:r,listener:i}),this.client.events.on(r,i))),de(this,"once",(r,i)=>(this.logger.debug("Once",{event:r,listener:i}),this.client.events.once(r,i))),de(this,"off",(r,i)=>(this.logger.debug("Off",{event:r,listener:i}),this.client.events.off(r,i))),de(this,"removeListener",(r,i)=>(this.logger.debug("Remove listener",{event:r,listener:i}),this.client.events.removeListener(r,i))),de(this,"prepareTransactionsFromPaymentIntents",async r=>{this.logger.debug("Preparing transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic});const{intentId:i,session:s}=r,o=this.paymentIntentsMap.get(i);if(!o)throw new Error(`Payment intents not found for id: ${i}`);const a=[];for(const h of o){const{token:f,amount:p,recipient:d}=h,{namespace:g}=tr(f.network.chainId),y=s.namespaces[g].accounts.find(_=>_.includes(`${f.network.chainId}:`));if(!y)throw new Error(`Address not found in session for chain id: ${f.network.chainId}, approved addresses: ${s.namespaces[g].accounts.join(", ")}`);a.push({asset:`${f.network.chainId}/${f.standard.toLowerCase()}:${f.address}`,recipient:d,amount:p,sender:y})}this.logger.debug("Prepared transactions from payment intents",{intentId:r.intentId,sessionTopic:r.session.topic,transactions:a});const c={id:ot(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:a}};this.logger.debug("Fetching wc_pos_buildTransactions",{payload:c});const u=await this.fetchRpcRequest(JSON.stringify(c));this.logger.debug("Received wc_pos_buildTransactions",{response:u});const l=u.result.transactions;return this.paymentIntentToTransactionsMap.set(i,l),this.logger.debug("Payment intent to transactions map set",{intentId:r.intentId,transactions:l}),l}),de(this,"onSessionConnected",async r=>{const{intentId:i,session:s}=r;this.logger.debug("On session connected",{intentId:i,sessionTopic:s.topic}),this.emit("connected",{session:s}),this.logger.debug("Emitted connected event");try{const o=await this.prepareTransactionsFromPaymentIntents({intentId:i,session:s});this.logger.debug("Transactions prepared",{transactions:o}),this.sendTransactionsToWallet({transactions:o,session:s,intentId:i})}catch(o){this.logger.error(o)}}),de(this,"sendTransactionsToWallet",async r=>{const{transactions:i,session:s,intentId:o}=r;this.logger.debug("Sending transactions to wallet",{transactions:i,sessionTopic:s.topic,intentId:o});const a=this.paymentIntentsMap.get(o);if(!a)throw new Error(`Payment intents not found for id: ${o}`);for(let c=0;c<i.length;c++){const u=i[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u}),this.logger.debug("Emitted payment_requested event",{transactionId:u.id});let h;try{h=await this.signClient.request({topic:s.topic,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug("Wallet responded to payment request",{transactionId:u.id,result:h})}catch(f){throw this.logger.error("error",f),this.emit("payment_rejected",{error:{message:f?.message,code:4001},paymentIntent:l}),f}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:h}),this.logger.debug("Emitted payment_broadcasted event",{transactionId:u.id}),this.awaitPaymentConfirmed({transaction:u,result:h}),await new Promise(f=>setTimeout(f,1e3))}catch(h){this.logger.error("error",h)}}}),de(this,"awaitPaymentConfirmed",async r=>{try{const{transaction:i,result:s}=r;this.logger.debug("Awaiting payment confirmed",{transactionId:i.id,result:s});const o={id:ot(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let a=0,c;for(;!c;){if(a>=Au)throw new Error(`Transaction status not found for id: ${i.id}`);a++;const u=await this.fetchRpcRequest(JSON.stringify(o));if(this.logger.debug("Received wc_pos_checkTransaction",{transactionId:i.id,response:u}),u.result.status==="CONFIRMED"){this.logger.debug("Transaction status confirmed",{response:u}),this.emit("payment_successful",{transaction:i,result:s}),c=u.result;break}else if(u.result.status==="FAILED"){this.logger.debug("Transaction failed",{response:u}),this.emit("payment_failed",{error:{message:u.result.error,code:4001},transaction:s}),c=u.result;break}else u.result.status==="PENDING"&&(this.logger.debug("Transaction pending",{response:u}),await new Promise(l=>setTimeout(l,u.result.checkIn||1e3)))}}catch(i){this.logger.error("Error while awaiting payment confirmations",i)}}),de(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,intentId:i})=>{try{this.logger.debug("On await_approval",{intentId:i});const s=await r();this.onSessionConnected({intentId:i,session:s})}catch(s){this.logger.error("Error while awaiting approval",s),this.emit("connection_rejected",{error:{message:s?.message,code:4001}})}})}),de(this,"fetchRpcRequest",async r=>{var i,s,o,a,c;this.logger.debug("Fetching RPC request",{url:this.getRpcUrl(),payload:r});const u=await fetch(this.getRpcUrl(),{method:"POST",body:r});let l;try{l=await u.json()}catch(h){this.logger.error("Error while getting json data from RPC response",h)}if(this.logger.debug("Received RPC request response",{data:l}),!u.ok||l.error){const h=((i=l.error)==null?void 0:i.code)||-18900,f=(s=wo)!=null&&s[h]?`${(o=wo)==null?void 0:o[h]}: ${(a=l.error)==null?void 0:a.message}`:(c=l.error)==null?void 0:c.message;throw this.emit("payment_failed",{error:{message:f,code:h},transaction:""}),new Error(f)}return l}),de(this,"getRpcUrl",()=>Ou({projectId:this.client.opts.projectId})),this.signClient={},this.logger=kt({name:this.client.name,level:(n=this.client.opts.loggerOptions)==null?void 0:n.posLevel}),this.setupEventHandlers()}composeNamespaces(e){this.logger.debug("Composing namespaces",{paymentIntents:e});const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=tr(s.chainId),a=this.supportedNamespaces.find(c=>c.name===o);if(!a)throw new Error(`Namespace not supported: ${o}`);n[o]={methods:a.methods,chains:[...((i=n[o])==null?void 0:i.chains)||[],s.chainId],events:a.events}}),this.logger.debug("Composed namespaces",{namespaces:n}),n}}var I5=Object.defineProperty,S5=(t,e,n)=>e in t?I5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ut=(t,e,n)=>S5(t,typeof e!="symbol"?e+"":e,n);class po extends Xg{constructor(e){super(e),Ut(this,"name"),Ut(this,"events",new Ve.exports),Ut(this,"engine"),Ut(this,"metadata"),Ut(this,"on",(n,r)=>this.engine.on(n,r)),Ut(this,"once",(n,r)=>this.engine.once(n,r)),Ut(this,"off",(n,r)=>this.engine.off(n,r)),Ut(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),Ut(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ut(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),Ut(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.signClient.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=yo,this.engine=new _5(this)}static async init(e){const n=new po(e);return await n.initialize(),n}async initialize(){try{await this.engine.init(),this.engine.signClient.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.signClient.logger.info("POSClient Initialization Failure"),this.engine.signClient.logger.error(e.message),e}}}const A5=po;be.CLIENT_CONTEXT=yo,be.CLIENT_STORAGE_OPTIONS=Iu,be.CLIENT_STORAGE_PREFIX=g0,be.DEFAULT_NAMESPACES=Du,be.IPOSClient=Xg,be.IPOSClientEngine=Qg,be.MAX_TRANSACTION_STATUS_CHECKS=Au,be.POSClient=A5,be.POS_CLIENT_VERSION=Su,be.PROTOCOL=_u,be.PROTOCOL_VERSION=p0,be.RPC_ERROR_CODES=wo,be.RPC_URL=Ou,be.default=po,Object.defineProperty(be,"__esModule",{value:!0})});
|
|
42
42
|
//# sourceMappingURL=index.umd.js.map
|