@walletconnect/pos-client 1.0.1 → 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.umd.js +12 -12
- package/dist/index.umd.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +6 -6
package/dist/index.umd.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Se,nn){typeof exports=="object"&&typeof module<"u"?nn(exports):typeof define=="function"&&define.amd?define(["exports"],nn):(Se=typeof globalThis<"u"?globalThis:Se||self,nn(Se["@walletconnect/pos-client"]={}))})(this,function(Se){"use strict";var nn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gl(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 rt={exports:{}},
|
|
1
|
+
(function(Se,nn){typeof exports=="object"&&typeof module<"u"?nn(exports):typeof define=="function"&&define.amd?define(["exports"],nn):(Se=typeof globalThis<"u"?globalThis:Se||self,nn(Se["@walletconnect/pos-client"]={}))})(this,function(Se){"use strict";var nn=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Gl(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 rt={exports:{}},ti=typeof Reflect=="object"?Reflect:null,Wl=ti&&typeof ti.apply=="function"?ti.apply:function(e,n,r){return Function.prototype.apply.call(e,n,r)},zs;ti&&typeof ti.ownKeys=="function"?zs=ti.ownKeys:Object.getOwnPropertySymbols?zs=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:zs=function(e){return Object.getOwnPropertyNames(e)};function Zy(t){console&&console.warn&&console.warn(t)}var Zl=Number.isNaN||function(e){return e!==e};function pe(){pe.init.call(this)}rt.exports=pe,rt.exports.once=Qy,pe.EventEmitter=pe,pe.prototype._events=void 0,pe.prototype._eventsCount=0,pe.prototype._maxListeners=void 0;var Yl=10;function Vs(t){if(typeof t!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof t)}Object.defineProperty(pe,"defaultMaxListeners",{enumerable:!0,get:function(){return Yl},set:function(t){if(typeof t!="number"||t<0||Zl(t))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+t+".");Yl=t}}),pe.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},pe.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||Zl(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 Xl(t){return t._maxListeners===void 0?pe.defaultMaxListeners:t._maxListeners}pe.prototype.getMaxListeners=function(){return Xl(this)},pe.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")Wl(c,this,n);else for(var u=c.length,l=nf(c,u),r=0;r<u;++r)Wl(l[r],this,n);return!0};function Jl(t,e,n,r){var i,s,o;if(Vs(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=Xl(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,Zy(a)}return t}pe.prototype.addListener=function(e,n){return Jl(this,e,n,!1)},pe.prototype.on=pe.prototype.addListener,pe.prototype.prependListener=function(e,n){return Jl(this,e,n,!0)};function Yy(){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 Ql(t,e,n){var r={fired:!1,wrapFn:void 0,target:t,type:e,listener:n},i=Yy.bind(r);return i.listener=n,r.wrapFn=i,i}pe.prototype.once=function(e,n){return Vs(n),this.on(e,Ql(this,e,n)),this},pe.prototype.prependOnceListener=function(e,n){return Vs(n),this.prependListener(e,Ql(this,e,n)),this},pe.prototype.removeListener=function(e,n){var r,i,s,o,a;if(Vs(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():Xy(r,s),r.length===1&&(i[e]=r[0]),i.removeListener!==void 0&&this.emit("removeListener",e,a||n)}return this},pe.prototype.off=pe.prototype.removeListener,pe.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 ef(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?Jy(i):nf(i,i.length)}pe.prototype.listeners=function(e){return ef(this,e,!0)},pe.prototype.rawListeners=function(e){return ef(this,e,!1)},pe.listenerCount=function(t,e){return typeof t.listenerCount=="function"?t.listenerCount(e):tf.call(t,e)},pe.prototype.listenerCount=tf;function tf(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}pe.prototype.eventNames=function(){return this._eventsCount>0?zs(this._events):[]};function nf(t,e){for(var n=new Array(e),r=0;r<e;++r)n[r]=t[r];return n}function Xy(t,e){for(;e+1<t.length;e++)t[e]=t[e+1];t.pop()}function Jy(t){for(var e=new Array(t.length),n=0;n<e.length;++n)e[n]=t[n].listener||t[n];return e}function Qy(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))}rf(t,e,s,{once:!0}),e!=="error"&&eb(t,i,{once:!0})})}function eb(t,e,n){typeof t.on=="function"&&rf(t,"error",e,n)}function rf(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 sf="wc",tb=2,Da="POSClient",nb=`${sf}@2:${Da}:`,$a={database:":memory:",customStoragePrefix:"@walletconnect/pos-client"},of="1.0.0",af=50,Ta="error",cf=[{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"}],uf=({projectId:t,deviceId:e})=>`https://rpc.walletconnect.org/v1/json-rpc?projectId=${t}&st=node&sv=js-pos-${of}&deviceId=${e}`,Pa={"-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 H={};/*! *****************************************************************************
|
|
2
2
|
Copyright (c) Microsoft Corporation.
|
|
3
3
|
|
|
4
4
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -11,20 +11,20 @@
|
|
|
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 Ra=function(t,e){return Ra=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])},Ra(t,e)};function rb(t,e){Ra(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Na=function(){return Na=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},Na.apply(this,arguments)};function ib(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 sb(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 ob(t,e){return function(n,r){e(n,r,t)}}function ab(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function cb(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 ub(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 lb(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function fb(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Ca(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function lf(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 hb(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(lf(arguments[e]));return t}function db(){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 Ui(t){return this instanceof Ui?(this.v=t,this):new Ui(t)}function pb(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(d){r[d]&&(i[d]=function(h){return new Promise(function(p,g){s.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ui?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function gb(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:Ui(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function yb(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Ca=="function"?Ca(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(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 bb(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function wb(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 mb(t){return t&&t.__esModule?t:{default:t}}function vb(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Eb(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 xb=Object.freeze({__proto__:null,__extends:rb,get __assign(){return Na},__rest:ib,__decorate:sb,__param:ob,__metadata:ab,__awaiter:cb,__generator:ub,__createBinding:lb,__exportStar:fb,__values:Ca,__read:lf,__spread:hb,__spreadArrays:db,__await:Ui,__asyncGenerator:pb,__asyncDelegator:gb,__asyncValues:yb,__makeTemplateObject:bb,__importStar:wb,__importDefault:mb,__classPrivateFieldGet:vb,__classPrivateFieldSet:Eb}),zs=Gl(xb),Ua={},Fi={},ff;function _b(){if(ff)return Fi;ff=1,Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return Fi.delay=t,Fi}var Ir={},Fa={},Sr={},hf;function Ib(){return hf||(hf=1,Object.defineProperty(Sr,"__esModule",{value:!0}),Sr.ONE_THOUSAND=Sr.ONE_HUNDRED=void 0,Sr.ONE_HUNDRED=100,Sr.ONE_THOUSAND=1e3),Sr}var La={},df;function Sb(){return df||(df=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}(La)),La}var pf;function gf(){return pf||(pf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zs;e.__exportStar(Ib(),t),e.__exportStar(Sb(),t)}(Fa)),Fa}var yf;function Ob(){if(yf)return Ir;yf=1,Object.defineProperty(Ir,"__esModule",{value:!0}),Ir.fromMiliseconds=Ir.toMiliseconds=void 0;const t=gf();function e(r){return r*t.ONE_THOUSAND}Ir.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return Ir.fromMiliseconds=n,Ir}var bf;function Bb(){return bf||(bf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zs;e.__exportStar(_b(),t),e.__exportStar(Ob(),t)}(Ua)),Ua}var ei={},wf;function Ab(){if(wf)return ei;wf=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.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 ei.Watch=t,ei.default=t,ei}var ka={},Li={},mf;function Db(){if(mf)return Li;mf=1,Object.defineProperty(Li,"__esModule",{value:!0}),Li.IWatch=void 0;class t{}return Li.IWatch=t,Li}var vf;function $b(){return vf||(vf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),zs.__exportStar(Db(),t)}(ka)),ka}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=zs;e.__exportStar(Bb(),t),e.__exportStar(Ab(),t),e.__exportStar($b(),t),e.__exportStar(gf(),t)})(H);class Or{}class Tb extends Or{constructor(e){super()}}const Ef=H.FIVE_SECONDS,Br={pulse:"heartbeat_pulse"};class qa extends Tb{constructor(e){super(e),this.events=new rt.exports.EventEmitter,this.interval=Ef,this.interval=e?.interval||Ef}static async init(e){const n=new qa(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(),H.toMiliseconds(this.interval))}pulse(){this.events.emit(Br.pulse)}}const Pb=/"(?:_|\\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*:/,Rb=/"(?: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*:/,Nb=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Cb(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Ub(t);return}return e}function Ub(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Vs(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(!Nb.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Pb.test(t)||Rb.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Cb)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Fb(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ne(t,...e){try{return Fb(t(...e))}catch(n){return Promise.reject(n)}}function Lb(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function kb(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Ks(t){if(Lb(t))return String(t);if(kb(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Ks(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ma="base64:";function qb(t){return typeof t=="string"?t:Ma+zb(t)}function Mb(t){return typeof t!="string"||!t.startsWith(Ma)?t:jb(t.slice(Ma.length))}function jb(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function zb(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function ht(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Vb(...t){return ht(t.join(":"))}function Hs(t){return t=ht(t),t?t+":":""}function Kb(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 Hb(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function i$(t){return t}const Gb="memory",Wb=()=>{const t=new Map;return{name:Gb,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 Zb(t={}){const e={mounts:{"":t.driver||Wb()},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=ht(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 xf(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 d=new Map,h=p=>{let g=d.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},d.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",m=ht(g?p:p.key),B=g?void 0:p.value,$=g||!p.options?l:{...l,...p.options},x=n(m);h(x).items.push({key:m,value:B,relativeKey:x.relativeKey,options:$})}return Promise.all([...d.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return Ne(d.hasItem,f,l)},getItem(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return Ne(d.getItem,f,l).then(h=>Vs(h))},getItems(u,l={}){return a(u,l,f=>f.driver.getItems?Ne(f.driver.getItems,f.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(h=>({key:Vb(f.base,h.key),value:Vs(h.value)}))):Promise.all(f.items.map(d=>Ne(f.driver.getItem,d.relativeKey,d.options).then(h=>({key:d.key,value:Vs(h)})))))},getItemRaw(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return d.getItemRaw?Ne(d.getItemRaw,f,l):Ne(d.getItem,f,l).then(h=>Mb(h))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=ht(u);const{relativeKey:d,driver:h}=n(u);h.setItem&&(await Ne(h.setItem,d,Ks(l),f),h.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return Ne(f.driver.setItems,f.items.map(d=>({key:d.relativeKey,value:Ks(d.value),options:d.options})),l);f.driver.setItem&&await Promise.all(f.items.map(d=>Ne(f.driver.setItem,d.relativeKey,Ks(d.value),d.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=ht(u);const{relativeKey:d,driver:h}=n(u);if(h.setItemRaw)await Ne(h.setItemRaw,d,l,f);else if(h.setItem)await Ne(h.setItem,d,qb(l),f);else return;h.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=ht(u);const{relativeKey:f,driver:d}=n(u);d.removeItem&&(await Ne(d.removeItem,f,l),(l.removeMeta||l.removeMata)&&await Ne(d.removeItem,f+"$",l),d.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=ht(u);const{relativeKey:f,driver:d}=n(u),h=Object.create(null);if(d.getMeta&&Object.assign(h,await Ne(d.getMeta,f,l)),!l.nativeOnly){const p=await Ne(d.getItem,f+"$",l).then(g=>Vs(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(h,p))}return h},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Hs(u);const f=r(u,!0);let d=[];const h=[];let p=!0;for(const m of f){m.driver.flags?.maxDepth||(p=!1);const B=await Ne(m.driver.getKeys,m.relativeBase,l);for(const $ of B){const x=m.mountpoint+ht($);d.some(_=>x.startsWith(_))||h.push(x)}d=[m.mountpoint,...d.filter($=>!$.startsWith(m.mountpoint))]}const g=l.maxDepth!==void 0&&!p;return h.filter(m=>(!g||Kb(m,l.maxDepth))&&Hb(m,u))},async clear(u,l={}){u=Hs(u),await Promise.all(r(u,!1).map(async f=>{if(f.driver.clear)return Ne(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const d=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(d.map(h=>f.driver.removeItem(h,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>_f(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=Hs(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,d)=>d.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(xf(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=Hs(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await _f(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=ht(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=ht(u),r(u,l.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,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 xf(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function _f(t){typeof t.dispose=="function"&&await Ne(t.dispose)}function Ar(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function If(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=Ar(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let ja;function ki(){return ja||(ja=If("keyval-store","keyval")),ja}function Sf(t,e=ki()){return e("readonly",n=>Ar(n.get(t)))}function Yb(t,e,n=ki()){return n("readwrite",r=>(r.put(e,t),Ar(r.transaction)))}function Xb(t,e=ki()){return e("readwrite",n=>(n.delete(t),Ar(n.transaction)))}function Jb(t=ki()){return t("readwrite",e=>(e.clear(),Ar(e.transaction)))}function Qb(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},Ar(t.transaction)}function ew(t=ki()){return t("readonly",e=>{if(e.getAllKeys)return Ar(e.getAllKeys());const n=[];return Qb(e,r=>n.push(r.key)).then(()=>n)})}const tw=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),nw=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 ti(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return nw(t)}catch{return t}}function qi(t){return typeof t=="string"?t:tw(t)||""}const rw="idb-keyval";var iw=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=If(t.dbName,t.storeName)),{name:rw,options:t,async hasItem(i){return!(typeof await Sf(n(i),r)>"u")},async getItem(i){return await Sf(n(i),r)??null},setItem(i,s){return Yb(n(i),s,r)},removeItem(i){return Xb(n(i),r)},getKeys(){return ew(r)},clear(){return Jb(r)}}};const sw="WALLET_CONNECT_V2_INDEXED_DB",ow="keyvaluestorage";class aw{constructor(){this.indexedDb=Zb({driver:iw({dbName:sw,storeName:ow})})}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,qi(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var za=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Gs={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 za<"u"&&za.localStorage?Gs.exports=za.localStorage:typeof window<"u"&&window.localStorage?Gs.exports=window.localStorage:Gs.exports=new e})();function cw(t){var e;return[t[0],ti((e=t[1])!=null?e:"")]}class uw{constructor(){this.localStorage=Gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(cw)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return ti(n)}async setItem(e,n){this.localStorage.setItem(e,qi(n))}async removeItem(e){this.localStorage.removeItem(e)}}const lw="wc_storage_version",Of=1,fw=async(t,e,n)=>{const r=lw,i=await e.getItem(r);if(i&&i>=Of){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,Of),n(e),hw(t,o)},hw=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class dw{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new uw;this.storage=e;try{const n=new aw;fw(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}var rn={exports:{}};function pw(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var gw=yw;function yw(t,e,n){var r=n&&n.stringify||pw,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,d=t&&t.length||0,h=0;h<d;){if(t.charCodeAt(h)===37&&h+1<d){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Number(e[l]),f=h+2,h++;break;case 105:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Math.floor(Number(e[l])),f=h+2,h++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<h&&(u+=t.slice(f,h));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=h+2,h++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=h+2,h++;break}u+=r(e[l]),f=h+2,h++;break;case 115:if(l>=c)break;f<h&&(u+=t.slice(f,h)),u+=String(e[l]),f=h+2,h++;break;case 37:f<h&&(u+=t.slice(f,h)),u+="%",f=h+2,h++,l--;break}++l}++h}return f===-1?t:(f<d&&(u+=t.slice(f)),u)}const Bf=gw;rn.exports=gn;const Mi=Tw().console||{},bw={mapHttpRequest:Ws,mapHttpResponse:Ws,wrapRequestSerializer:Wa,wrapResponseSerializer:Wa,wrapErrorSerializer:Wa,req:Ws,res:Ws,err:Df,errWithCause:Df};function Vn(t,e){return t==="silent"?1/0:e.levels.values[t]}const Va=Symbol("pino.logFuncs"),Ka=Symbol("pino.hierarchy"),ww={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Af(t,e){const n={logger:e,parent:t[Ka]};e[Ka]=n}function mw(t,e,n){const r={};e.forEach(i=>{r[i]=n[i]?n[i]:Mi[i]||Mi[ww[i]||"log"]||ni}),t[Va]=r}function vw(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function gn(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||Mi;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=vw(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=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",u=Object.create(n);u.log||(u.log=ni),mw(u,a,n),Af({},u),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:d,set:h});const l={transmit:e,serialize:i,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:Aw(t),messageKey:t.messageKey||"msg",onChild:t.onChild||ni};u.levels=Ew(t),u.level=c,u.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=ni,u.serializers=r,u._serialize=i,u._stdErrSerialize=s,u.child=function(...g){return p.call(this,l,...g)},e&&(u._logEvent=Ga());function f(){return Vn(this.level,this)}function d(){return this._level}function h(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,Dr(this,l,u,"error"),Dr(this,l,u,"fatal"),Dr(this,l,u,"warn"),Dr(this,l,u,"info"),Dr(this,l,u,"debug"),Dr(this,l,u,"trace"),o.forEach(m=>{Dr(this,l,u,m)})}function p(g,m,B){if(!m)throw new Error("missing bindings for child Pino");B=B||{},i&&m.serializers&&(B.serializers=m.serializers);const $=B.serializers;if(i&&$){var x=Object.assign({},r,$),_=t.browser.serialize===!0?Object.keys(x):i;delete m.serializers,Ha([m],_,x,this._stdErrSerialize)}function T(C){this._childLevel=(C._childLevel|0)+1,this.bindings=m,x&&(this.serializers=x,this._serialize=_),e&&(this._logEvent=Ga([].concat(C._logEvent.bindings,m)))}T.prototype=this;const P=new T(this);return Af(this,P),P.child=function(...C){return p.call(this,g,...C)},P.level=B.level||this.level,g.onChild(P),P}return u}function Ew(t){const e=t.customLevels||{},n=Object.assign({},gn.levels.values,e),r=Object.assign({},gn.levels.labels,xw(e));return{values:n,labels:r}}function xw(t){const e={};return Object.keys(t).forEach(function(n){e[t[n]]=n}),e}gn.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"}},gn.stdSerializers=bw,gn.stdTimeFunctions=Object.assign({},{nullTime:$f,epochTime:Tf,unixTime:Dw,isoTime:$w});function _w(t){const e=[];t.bindings&&e.push(t.bindings);let n=t[Ka];for(;n.parent;)n=n.parent,n.logger.bindings&&e.push(n.logger.bindings);return e.reverse()}function Dr(t,e,n,r){if(Object.defineProperty(t,r,{value:Vn(t.level,n)>Vn(r,n)?ni:n[Va][r],writable:!0,enumerable:!0,configurable:!0}),t[r]===ni){if(!e.transmit)return;const s=e.transmit.level||t.level,o=Vn(s,n);if(Vn(r,n)<o)return}t[r]=Sw(t,e,n,r);const i=_w(t);i.length!==0&&(t[r]=Iw(i,t[r]))}function Iw(t,e){return function(){return e.apply(this,[...t,...arguments])}}function Sw(t,e,n,r){return function(i){return function(){const s=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Mi?Mi:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var u=!1;if(e.serialize&&(Ha(o,this._serialize,this.serializers,this._stdErrSerialize),u=!0),e.asObject||e.formatters?i.call(a,...Ow(this,r,o,s,e)):i.apply(a,o),e.transmit){const l=e.transmit.level||t._level,f=Vn(l,n),d=Vn(r,n);if(d<f)return;Bw(this,{ts:s,methodLevel:r,methodValue:d,transmitLevel:l,transmitValue:n.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Vn(t._level,n)},o,u)}}}(t[Va][r])}function Ow(t,e,n,r,i){const{level:s,log:o=f=>f}=i.formatters||{},a=n.slice();let c=a[0];const u={};let l=(t._childLevel|0)+1;if(l<1&&(l=1),r&&(u.time=r),s){const f=s(e,t.levels.values[e]);Object.assign(u,f)}else u.level=t.levels.values[e];if(i.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[o(u),...a]}else{if(c!==null&&typeof c=="object"){for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?Bf(a.shift(),a):void 0}else typeof c=="string"&&(c=Bf(a.shift(),a));return c!==void 0&&(u[i.messageKey]=c),[o(u)]}}function Ha(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=gn.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i])&&e)for(const s in t[i])e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function Bw(t,e,n,r=!1){const i=e.send,s=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,u=t._logEvent.bindings;r||Ha(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=n.filter(function(l){return u.indexOf(l)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,i(o,t._logEvent,c),t._logEvent=Ga(u)}function Ga(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Df(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function Aw(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?$f:Tf}function Ws(){return{}}function Wa(t){return t}function ni(){}function $f(){return!1}function Tf(){return Date.now()}function Dw(){return Math.round(Date.now()/1e3)}function $w(){return new Date(Date.now()).toISOString()}function Tw(){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)||{}}}rn.exports.default=gn;var Pw=rn.exports.pino=gn;const Rw={level:"info"},Zs="custom_context",Za=1e3*1024;var Nw=Object.defineProperty,Cw=(t,e,n)=>e in t?Nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kn=(t,e,n)=>Cw(t,typeof e!="symbol"?e+"":e,n);class Uw{constructor(e){Kn(this,"nodeValue"),Kn(this,"sizeInBytes"),Kn(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class Pf{constructor(e){Kn(this,"lengthInNodes"),Kn(this,"sizeInBytes"),Kn(this,"head"),Kn(this,"tail"),Kn(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new Uw(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}const Fw=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n);function Rf(t){return typeof t=="string"?t:Fw(t)||""}var Lw=Object.defineProperty,kw=(t,e,n)=>e in t?Lw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ys=(t,e,n)=>kw(t,typeof e!="symbol"?e+"":e,n);class Nf{constructor(e,n=Za){Ys(this,"logs"),Ys(this,"level"),Ys(this,"levelValue"),Ys(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=rn.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Pf(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===rn.exports.levels.values.error?console.error(e):n===rn.exports.levels.values.warn?console.warn(e):n===rn.exports.levels.values.debug?console.debug(e):n===rn.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Rf({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 Pf(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Rf({extraMetadata:e})),new Blob(n,{type:"application/json"})}}var qw=Object.defineProperty,Mw=(t,e,n)=>e in t?qw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jw=(t,e,n)=>Mw(t,typeof e!="symbol"?e+"":e,n);class zw{constructor(e,n=Za){jw(this,"baseChunkLogger"),this.baseChunkLogger=new Nf(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}var Vw=Object.defineProperty,Kw=(t,e,n)=>e in t?Vw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hw=(t,e,n)=>Kw(t,typeof e!="symbol"?e+"":e,n);class Gw{constructor(e,n=Za){Hw(this,"baseChunkLogger"),this.baseChunkLogger=new Nf(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 Ww=Object.defineProperty,Zw=Object.defineProperties,Yw=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,Xw=Object.prototype.hasOwnProperty,Jw=Object.prototype.propertyIsEnumerable,Uf=(t,e,n)=>e in t?Ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Xs=(t,e)=>{for(var n in e||(e={}))Xw.call(e,n)&&Uf(t,n,e[n]);if(Cf)for(var n of Cf(e))Jw.call(e,n)&&Uf(t,n,e[n]);return t},Js=(t,e)=>Zw(t,Yw(e));function Qw(t){return Js(Xs({},t),{level:t?.level||Rw.level})}function em(t,e,n=Zs){return t[n]=e,t}function dt(t,e=Zs){return t[e]||""}function tm(t,e,n=Zs){const r=dt(t,n);return r.trim()?`${r}/${e}`:e}function Ot(t,e,n=Zs){const r=tm(t,e,n),i=t.child({context:r});return em(i,r,n)}function nm(t){var e,n;const r=new zw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:rn.exports(Js(Xs({},t.opts),{level:"trace",browser:Js(Xs({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function rm(t){var e;const n=new Gw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:rn.exports(Js(Xs({},t.opts),{level:"trace"}),n),chunkLoggerController:n}}function Ff(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?nm(t):rm(t)}var im=Object.defineProperty,sm=(t,e,n)=>e in t?im(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Lf=(t,e,n)=>sm(t,typeof e!="symbol"?e+"":e,n);class om extends Or{constructor(e){super(),this.opts=e,Lf(this,"protocol","wc"),Lf(this,"version",2)}}var am=Object.defineProperty,cm=(t,e,n)=>e in t?am(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,um=(t,e,n)=>cm(t,typeof e!="symbol"?e+"":e,n);class lm extends Or{constructor(e,n){super(),this.core=e,this.logger=n,um(this,"records",new Map)}}class fm{constructor(e,n){this.logger=e,this.core=n}}class hm extends Or{constructor(e,n){super(),this.relayer=e,this.logger=n}}class dm extends Or{constructor(e){super()}}class pm{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class gm extends Or{constructor(e,n){super(),this.relayer=e,this.logger=n}}class ym extends Or{constructor(e,n){super(),this.core=e,this.logger=n}}class bm{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class wm{constructor(e,n){this.projectId=e,this.logger=n}}class mm{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var vm=Object.defineProperty,Em=(t,e,n)=>e in t?vm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kf=(t,e,n)=>Em(t,typeof e!="symbol"?e+"":e,n);class xm{constructor(e){this.opts=e,kf(this,"protocol","wc"),kf(this,"version",2)}}class _m{constructor(e){this.client=e}}function Im(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function qf(t,...e){if(!Im(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 Mf(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 Sm(t,e){qf(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const ri=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ya=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Om(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function jf(t){return typeof t=="string"&&(t=Om(t)),qf(t),t}class Bm{clone(){return this._cloneInto()}}function Am(t){const e=r=>t().update(jf(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function zf(t=32){if(ri&&typeof ri.getRandomValues=="function")return ri.getRandomValues(new Uint8Array(t));if(ri&&typeof ri.randomBytes=="function")return ri.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Dm(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 $m extends Bm{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=Ya(this.buffer)}update(e){Mf(this);const{view:n,buffer:r,blockLen:i}=this;e=jf(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=Ya(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){Mf(this),Sm(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;Dm(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Ya(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 Qs=BigInt(2**32-1),Xa=BigInt(32);function Vf(t,e=!1){return e?{h:Number(t&Qs),l:Number(t>>Xa&Qs)}:{h:Number(t>>Xa&Qs)|0,l:Number(t&Qs)|0}}function Tm(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}=Vf(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const Pm=(t,e)=>BigInt(t>>>0)<<Xa|BigInt(e>>>0),Rm=(t,e,n)=>t>>>n,Nm=(t,e,n)=>t<<32-n|e>>>n,Cm=(t,e,n)=>t>>>n|e<<32-n,Um=(t,e,n)=>t<<32-n|e>>>n,Fm=(t,e,n)=>t<<64-n|e>>>n-32,Lm=(t,e,n)=>t>>>n-32|e<<64-n,km=(t,e)=>e,qm=(t,e)=>t,Mm=(t,e,n)=>t<<n|e>>>32-n,jm=(t,e,n)=>e<<n|t>>>32-n,zm=(t,e,n)=>e<<n-32|t>>>64-n,Vm=(t,e,n)=>t<<n-32|e>>>64-n;function Km(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const Hm=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Gm=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Wm=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Zm=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ym=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Xm=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,ne={fromBig:Vf,split:Tm,toBig:Pm,shrSH:Rm,shrSL:Nm,rotrSH:Cm,rotrSL:Um,rotrBH:Fm,rotrBL:Lm,rotr32H:km,rotr32L:qm,rotlSH:Mm,rotlSL:jm,rotlBH:zm,rotlBL:Vm,add:Km,add3L:Hm,add3H:Gm,add4L:Wm,add4H:Zm,add5H:Xm,add5L:Ym},[Jm,Qm]=ne.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))),Hn=new Uint32Array(80),Gn=new Uint32Array(80);class e2 extends $m{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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)Hn[x]=e.getUint32(n),Gn[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=Hn[x-15]|0,T=Gn[x-15]|0,P=ne.rotrSH(_,T,1)^ne.rotrSH(_,T,8)^ne.shrSH(_,T,7),C=ne.rotrSL(_,T,1)^ne.rotrSL(_,T,8)^ne.shrSL(_,T,7),U=Hn[x-2]|0,D=Gn[x-2]|0,j=ne.rotrSH(U,D,19)^ne.rotrBH(U,D,61)^ne.shrSH(U,D,6),M=ne.rotrSL(U,D,19)^ne.rotrBL(U,D,61)^ne.shrSL(U,D,6),E=ne.add4L(C,M,Gn[x-7],Gn[x-16]),b=ne.add4H(E,P,j,Hn[x-7],Hn[x-16]);Hn[x]=b|0,Gn[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=ne.rotrSH(f,d,14)^ne.rotrSH(f,d,18)^ne.rotrBH(f,d,41),T=ne.rotrSL(f,d,14)^ne.rotrSL(f,d,18)^ne.rotrBL(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=ne.add5L($,T,C,Qm[x],Gn[x]),D=ne.add5H(U,B,_,P,Jm[x],Hn[x]),j=U|0,M=ne.rotrSH(r,i,28)^ne.rotrBH(r,i,34)^ne.rotrBH(r,i,39),E=ne.rotrSL(r,i,28)^ne.rotrBL(r,i,34)^ne.rotrBL(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ne.add(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=ne.add3L(j,E,v);r=ne.add3H(y,D,M,b),i=y|0}({h:r,l:i}=ne.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ne.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ne.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ne.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ne.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ne.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ne.add(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=ne.add(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){Hn.fill(0),Gn.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 t2=Am(()=>new e2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ja=BigInt(0),Kf=BigInt(1),n2=BigInt(2);function Qa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ec(t){if(!Qa(t))throw new Error("Uint8Array expected")}function tc(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const r2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function nc(t){ec(t);let e="";for(let n=0;n<t.length;n++)e+=r2[t[n]];return e}function Hf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ja:BigInt("0x"+t)}const yn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gf(t){if(t>=yn._0&&t<=yn._9)return t-yn._0;if(t>=yn.A&&t<=yn.F)return t-(yn.A-10);if(t>=yn.a&&t<=yn.f)return t-(yn.a-10)}function Wf(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=Gf(t.charCodeAt(s)),a=Gf(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 i2(t){return Hf(nc(t))}function eo(t){return ec(t),Hf(nc(Uint8Array.from(t).reverse()))}function Zf(t,e){return Wf(t.toString(16).padStart(e*2,"0"))}function rc(t,e){return Zf(t,e).reverse()}function bn(t,e,n){let r;if(typeof e=="string")try{r=Wf(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Qa(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 Yf(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];ec(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 ic=t=>typeof t=="bigint"&&Ja<=t;function s2(t,e,n){return ic(t)&&ic(e)&&ic(n)&&e<=t&&t<n}function ji(t,e,n,r){if(!s2(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function o2(t){let e;for(e=0;t>Ja;t>>=Kf,e+=1);return e}const a2=t=>(n2<<BigInt(t-1))-Kf,c2={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"||Qa(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 sc(t,e,n={}){const r=(i,s,o)=>{const a=c2[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 Xf(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 Ce=BigInt(0),_e=BigInt(1),$r=BigInt(2),u2=BigInt(3),oc=BigInt(4),Jf=BigInt(5),Qf=BigInt(8);function De(t,e){const n=t%e;return n>=Ce?n:e+n}function l2(t,e,n){if(e<Ce)throw new Error("invalid exponent, negatives unsupported");if(n<=Ce)throw new Error("invalid modulus");if(n===_e)return Ce;let r=_e;for(;e>Ce;)e&_e&&(r=r*t%n),t=t*t%n,e>>=_e;return r}function sn(t,e,n){let r=t;for(;e-- >Ce;)r*=r,r%=n;return r}function eh(t,e){if(t===Ce)throw new Error("invert: expected non-zero number");if(e<=Ce)throw new Error("invert: expected positive modulus, got "+e);let n=De(t,e),r=e,i=Ce,s=_e;for(;n!==Ce;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==_e)throw new Error("invert: does not exist");return De(i,e)}function f2(t){const e=(t-_e)/$r;let n,r,i;for(n=t-_e,r=0;n%$r===Ce;n/=$r,r++);for(i=$r;i<t&&l2(i,e,t)!==t-_e;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+_e)/oc;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+_e)/$r;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 d=1;for(let p=o.sqr(f);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const h=o.pow(u,_e<<BigInt(c-d-1));u=o.sqr(h),l=o.mul(l,h),f=o.mul(f,u),c=d}return l}}function h2(t){if(t%oc===u2){const e=(t+_e)/oc;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%Qf===Jf){const e=(t-Jf)/Qf;return function(n,r){const i=n.mul(r,$r),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,$r),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 f2(t)}const d2=(t,e)=>(De(t,e)&_e)===_e,p2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function g2(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=p2.reduce((r,i)=>(r[i]="function",r),e);return sc(t,n)}function y2(t,e,n){if(n<Ce)throw new Error("invalid exponent, negatives unsupported");if(n===Ce)return t.ONE;if(n===_e)return e;let r=t.ONE,i=e;for(;n>Ce;)n&_e&&(r=t.mul(r,i)),i=t.sqr(i),n>>=_e;return r}function b2(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 th(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function nh(t,e,n=!1,r={}){if(t<=Ce)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=th(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:a2(i),ZERO:Ce,ONE:_e,create:c=>De(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ce<=c&&c<t},is0:c=>c===Ce,isOdd:c=>(c&_e)===_e,neg:c=>De(-c,t),eql:(c,u)=>c===u,sqr:c=>De(c*c,t),add:(c,u)=>De(c+u,t),sub:(c,u)=>De(c-u,t),mul:(c,u)=>De(c*u,t),pow:(c,u)=>y2(a,c,u),div:(c,u)=>De(c*eh(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>eh(c,t),sqrt:r.sqrt||(c=>(o||(o=h2(t)),o(a,c))),invertBatch:c=>b2(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?rc(c,s):Zf(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?eo(c):i2(c)}});return Object.freeze(a)}const rh=BigInt(0),to=BigInt(1);function ac(t,e){const n=e.negate();return t?n:e}function ih(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function cc(t,e){ih(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function w2(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 m2(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 uc=new WeakMap,sh=new WeakMap;function lc(t){return sh.get(t)||1}function v2(t,e){return{constTimeNegate:ac,hasPrecomputes(n){return lc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>rh;)r&to&&(i=i.add(s)),s=s.double(),r>>=to;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=cc(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}=cc(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let d=0;d<s;d++){const h=d*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=to);const g=h,m=h+Math.abs(p)-1,B=d%2!==0,$=p<0;p===0?c=c.add(ac(B,r[g])):a=a.add(ac($,r[m]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=cc(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let f=0;f<o;f++){const d=f*a;if(i===rh)break;let h=Number(i&c);if(i>>=l,h>a&&(h-=u,i+=to),h===0)continue;let p=r[d+Math.abs(h)-1];h<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=uc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&uc.set(r,i(s))),s},wNAFCached(n,r,i){const s=lc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=lc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){ih(r,e),sh.set(n,r),uc.delete(n)}}}function E2(t,e,n,r){if(w2(n,t),m2(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=o2(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 h=0;h<r.length;h++){const p=r[h],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(n[h])}let d=i;for(let h=c.length-1,p=i;h>0;h--)p=p.add(c[h]),d=d.add(p);if(l=l.add(d),f!==0)for(let h=0;h<o;h++)l=l.double()}return l}function x2(t){return g2(t.Fp),sc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...th(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Ht=BigInt(0),pt=BigInt(1),no=BigInt(2),_2=BigInt(8),I2={zip215:!0};function S2(t){const e=x2(t);return sc(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function O2(t){const e=S2(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=no<<BigInt(a*8)-pt,l=n.create,f=nh(e.n,e.nBitLength),d=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(y*n.inv(w))}}catch{return{isValid:!1,value:Ht}}}),h=e.adjustScalarBytes||(y=>y),p=e.domain||((y,w,I)=>{if(tc("phflag",I),w.length||I)throw new Error("Contexts/pre-hash are not supported");return y});function g(y,w){ji("coordinate "+y,w,Ht,u)}function m(y){if(!(y instanceof x))throw new Error("ExtendedPoint expected")}const B=Xf((y,w)=>{const{ex:I,ey:O,ez:S}=y,A=y.is0();w==null&&(w=A?_2:n.inv(S));const R=l(I*w),L=l(O*w),F=l(S*w);if(A)return{x:Ht,y:pt};if(F!==pt)throw new Error("invZ was invalid");return{x:R,y:L}}),$=Xf(y=>{const{a:w,d:I}=e;if(y.is0())throw new Error("bad point: ZERO");const{ex:O,ey:S,ez:A,et:R}=y,L=l(O*O),F=l(S*S),k=l(A*A),N=l(k*k),q=l(L*w),z=l(k*l(q+F)),W=l(N+l(I*l(L*F)));if(z!==W)throw new Error("bad point: equation left != right (1)");const K=l(O*S),Z=l(A*R);if(K!==Z)throw new Error("bad point: equation left != right (2)");return!0});class x{constructor(w,I,O,S){this.ex=w,this.ey=I,this.ez=O,this.et=S,g("x",w),g("y",I),g("z",O),g("t",S),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof x)throw new Error("extended point not allowed");const{x:I,y:O}=w||{};return g("x",I),g("y",O),new x(I,O,pt,l(I*O))}static normalizeZ(w){const I=n.invertBatch(w.map(O=>O.ez));return w.map((O,S)=>O.toAffine(I[S])).map(x.fromAffine)}static msm(w,I){return E2(x,f,w,I)}_setWindowSize(w){P.setWindowSize(this,w)}assertValidity(){$(this)}equals(w){m(w);const{ex:I,ey:O,ez:S}=this,{ex:A,ey:R,ez:L}=w,F=l(I*L),k=l(A*S),N=l(O*L),q=l(R*S);return F===k&&N===q}is0(){return this.equals(x.ZERO)}negate(){return new x(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:I,ey:O,ez:S}=this,A=l(I*I),R=l(O*O),L=l(no*l(S*S)),F=l(w*A),k=I+O,N=l(l(k*k)-A-R),q=F+R,z=q-L,W=F-R,K=l(N*z),Z=l(q*W),Q=l(N*W),ee=l(z*q);return new x(K,Z,ee,Q)}add(w){m(w);const{a:I,d:O}=e,{ex:S,ey:A,ez:R,et:L}=this,{ex:F,ey:k,ez:N,et:q}=w;if(I===BigInt(-1)){const jy=l((A-S)*(k+F)),zy=l((A+S)*(k-F)),Hl=l(zy-jy);if(Hl===Ht)return this.double();const Vy=l(R*no*q),Ky=l(L*no*N),Hy=Ky+Vy,Gy=zy+jy,Wy=Ky-Vy,e$=l(Hy*Hl),t$=l(Gy*Wy),n$=l(Hy*Wy),r$=l(Hl*Gy);return new x(e$,t$,r$,n$)}const z=l(S*F),W=l(A*k),K=l(L*O*q),Z=l(R*N),Q=l((S+A)*(F+k)-z-W),ee=Z-K,ie=Z+K,he=l(W-I*z),Ee=l(Q*ee),zn=l(ie*he),Aa=l(Q*he),QD=l(ee*ie);return new x(Ee,zn,QD,Aa)}subtract(w){return this.add(w.negate())}wNAF(w){return P.wNAFCached(this,w,x.normalizeZ)}multiply(w){const I=w;ji("scalar",I,pt,r);const{p:O,f:S}=this.wNAF(I);return x.normalizeZ([O,S])[0]}multiplyUnsafe(w,I=x.ZERO){const O=w;return ji("scalar",O,Ht,r),O===Ht?T:this.is0()||O===pt?this:P.wNAFCachedUnsafe(this,O,x.normalizeZ,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,r).is0()}toAffine(w){return B(this,w)}clearCofactor(){const{h:w}=e;return w===pt?this:this.multiplyUnsafe(w)}static fromHex(w,I=!1){const{d:O,a:S}=e,A=n.BYTES;w=bn("pointHex",w,A),tc("zip215",I);const R=w.slice(),L=w[A-1];R[A-1]=L&-129;const F=eo(R),k=I?u:n.ORDER;ji("pointHex.y",F,Ht,k);const N=l(F*F),q=l(N-pt),z=l(O*N-S);let{isValid:W,value:K}=d(q,z);if(!W)throw new Error("Point.fromHex: invalid y coordinate");const Z=(K&pt)===pt,Q=(L&128)!==0;if(!I&&K===Ht&&Q)throw new Error("Point.fromHex: x=0 and x_0=1");return Q!==Z&&(K=l(-K)),x.fromAffine({x:K,y:F})}static fromPrivateKey(w){return D(w).point}toRawBytes(){const{x:w,y:I}=this.toAffine(),O=rc(I,n.BYTES);return O[O.length-1]|=w&pt?128:0,O}toHex(){return nc(this.toRawBytes())}}x.BASE=new x(e.Gx,e.Gy,pt,l(e.Gx*e.Gy)),x.ZERO=new x(Ht,pt,pt,Ht);const{BASE:_,ZERO:T}=x,P=v2(x,a*8);function C(y){return De(y,r)}function U(y){return C(eo(y))}function D(y){const w=n.BYTES;y=bn("private key",y,w);const I=bn("hashed private key",s(y),2*w),O=h(I.slice(0,w)),S=I.slice(w,2*w),A=U(O),R=_.multiply(A),L=R.toRawBytes();return{head:O,prefix:S,scalar:A,point:R,pointBytes:L}}function j(y){return D(y).pointBytes}function M(y=new Uint8Array,...w){const I=Yf(...w);return U(s(p(I,bn("context",y),!!i)))}function E(y,w,I={}){y=bn("message",y),i&&(y=i(y));const{prefix:O,scalar:S,pointBytes:A}=D(w),R=M(I.context,O,y),L=_.multiply(R).toRawBytes(),F=M(I.context,L,A,y),k=C(R+F*S);ji("signature.s",k,Ht,r);const N=Yf(L,rc(k,n.BYTES));return bn("result",N,n.BYTES*2)}const b=I2;function v(y,w,I,O=b){const{context:S,zip215:A}=O,R=n.BYTES;y=bn("signature",y,2*R),w=bn("message",w),I=bn("publicKey",I,R),A!==void 0&&tc("zip215",A),i&&(w=i(w));const L=eo(y.slice(R,2*R));let F,k,N;try{F=x.fromHex(I,A),k=x.fromHex(y.slice(0,R),A),N=_.multiplyUnsafe(L)}catch{return!1}if(!A&&F.isSmallOrder())return!1;const q=M(S,k.toRawBytes(),F.toRawBytes(),w);return k.add(F.multiplyUnsafe(q)).subtract(N).clearCofactor().equals(x.ZERO)}return _._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:E,verify:v,ExtendedPoint:x,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(n.BYTES),precompute(y=8,w=x.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const fc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),oh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const B2=BigInt(1),ah=BigInt(2);BigInt(3);const A2=BigInt(5),D2=BigInt(8);function $2(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=fc,o=t*t%s*t%s,a=sn(o,ah,s)*o%s,c=sn(a,B2,s)*t%s,u=sn(c,A2,s)*c%s,l=sn(u,e,s)*u%s,f=sn(l,n,s)*l%s,d=sn(f,r,s)*f%s,h=sn(d,i,s)*d%s,p=sn(h,i,s)*d%s,g=sn(p,e,s)*u%s;return{pow_p_5_8:sn(g,ah,s)*t%s,b2:o}}function T2(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function P2(t,e){const n=fc,r=De(e*e*e,n),i=De(r*r*e,n),s=$2(t*i).pow_p_5_8;let o=De(t*r*s,n);const a=De(e*o*o,n),c=o,u=De(o*oh,n),l=a===t,f=a===De(-t,n),d=a===De(-t*oh,n);return l&&(o=c),(f||d)&&(o=u),d2(o,n)&&(o=De(-o,n)),{isValid:l||f,value:o}}const R2=nh(fc,void 0,!0),N2={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:R2,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:D2,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:t2,randomBytes:zf,adjustScalarBytes:T2,uvRatio:P2},ch=O2(N2),C2="EdDSA",U2="JWT",ro=".",io="base64url",uh="utf8",lh="utf8",F2=":",L2="did",k2="key",fh="base58btc",q2="z",M2="K36",j2=32;function hc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function hh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?hc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function dh(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=hh(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return hc(n)}function z2(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var V2=z2,K2=V2;const ph=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")},H2=t=>new TextEncoder().encode(t),G2=t=>new TextDecoder().decode(t);class W2{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 Z2{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 gh(this,e)}}class Y2{constructor(e){this.decoders=e}or(e){return gh(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 gh=(t,e)=>new Y2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class X2{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new W2(e,n,r),this.decoder=new Z2(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const so=({name:t,prefix:e,encode:n,decode:r})=>new X2(t,e,n,r),zi=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=K2(n,e);return so({prefix:t,name:e,encode:r,decode:s=>ph(i(s))})},J2=(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},Q2=(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},ke=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>so({prefix:e,name:t,encode(i){return Q2(i,r,n)},decode(i){return J2(i,r,n,t)}}),ev=so({prefix:"\0",name:"identity",encode:t=>G2(t),decode:t=>H2(t)});var tv=Object.freeze({__proto__:null,identity:ev});const nv=ke({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rv=Object.freeze({__proto__:null,base2:nv});const iv=ke({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sv=Object.freeze({__proto__:null,base8:iv});const ov=zi({prefix:"9",name:"base10",alphabet:"0123456789"});var av=Object.freeze({__proto__:null,base10:ov});const cv=ke({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uv=ke({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lv=Object.freeze({__proto__:null,base16:cv,base16upper:uv});const fv=ke({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hv=ke({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dv=ke({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pv=ke({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gv=ke({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yv=ke({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bv=ke({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wv=ke({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mv=ke({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vv=Object.freeze({__proto__:null,base32:fv,base32upper:hv,base32pad:dv,base32padupper:pv,base32hex:gv,base32hexupper:yv,base32hexpad:bv,base32hexpadupper:wv,base32z:mv});const Ev=zi({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xv=zi({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _v=Object.freeze({__proto__:null,base36:Ev,base36upper:xv});const Iv=zi({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sv=zi({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ov=Object.freeze({__proto__:null,base58btc:Iv,base58flickr:Sv});const Bv=ke({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Av=ke({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dv=ke({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$v=ke({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Tv=Object.freeze({__proto__:null,base64:Bv,base64pad:Av,base64url:Dv,base64urlpad:$v});const yh=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}"),Pv=yh.reduce((t,e,n)=>(t[n]=e,t),[]),Rv=yh.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Nv(t){return t.reduce((e,n)=>(e+=Pv[n],e),"")}function Cv(t){const e=[];for(const n of t){const r=Rv[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Uv=so({prefix:"\u{1F680}",name:"base256emoji",encode:Nv,decode:Cv});var Fv=Object.freeze({__proto__:null,base256emoji:Uv}),Lv=wh,bh=128,kv=127,qv=~kv,Mv=Math.pow(2,31);function wh(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Mv;)e[n++]=t&255|bh,t/=128;for(;t&qv;)e[n++]=t&255|bh,t>>>=7;return e[n]=t|0,wh.bytes=n-r+1,e}var jv=dc,zv=128,mh=127;function dc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw dc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&mh)<<i:(o&mh)*Math.pow(2,i),i+=7}while(o>=zv);return dc.bytes=s-r,n}var Vv=Math.pow(2,7),Kv=Math.pow(2,14),Hv=Math.pow(2,21),Gv=Math.pow(2,28),Wv=Math.pow(2,35),Zv=Math.pow(2,42),Yv=Math.pow(2,49),Xv=Math.pow(2,56),Jv=Math.pow(2,63),Qv=function(t){return t<Vv?1:t<Kv?2:t<Hv?3:t<Gv?4:t<Wv?5:t<Zv?6:t<Yv?7:t<Xv?8:t<Jv?9:10},eE={encode:Lv,decode:jv,encodingLength:Qv},vh=eE;const Eh=(t,e,n=0)=>(vh.encode(t,e,n),e),xh=t=>vh.encodingLength(t),pc=(t,e)=>{const n=e.byteLength,r=xh(t),i=r+xh(n),s=new Uint8Array(i+n);return Eh(t,s,0),Eh(n,s,r),s.set(e,i),new tE(t,n,e,s)};class tE{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const _h=({name:t,code:e,encode:n})=>new nE(t,e,n);class nE{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?pc(this.code,n):n.then(r=>pc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ih=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),rE=_h({name:"sha2-256",code:18,encode:Ih("SHA-256")}),iE=_h({name:"sha2-512",code:19,encode:Ih("SHA-512")});var sE=Object.freeze({__proto__:null,sha256:rE,sha512:iE});const Sh=0,oE="identity",Oh=ph;var aE=Object.freeze({__proto__:null,identity:{code:Sh,name:oE,encode:Oh,digest:t=>pc(Sh,Oh(t))}});new TextEncoder,new TextDecoder;const Bh={...tv,...rv,...sv,...av,...lv,...vv,..._v,...Ov,...Tv,...Fv};({...sE,...aE});function Ah(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Dh=Ah("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),gc=Ah("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=hh(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),$h={utf8:Dh,"utf-8":Dh,hex:Bh.base16,latin1:gc,ascii:gc,binary:gc,...Bh};function oo(t,e="utf8"){const n=$h[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 ii(t,e="utf8"){const n=$h[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?hc(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Th(t){return ti(oo(ii(t,io),uh))}function ao(t){return oo(ii(qi(t),uh),io)}function Ph(t){const e=ii(M2,fh),n=q2+oo(dh([e,t]),fh);return[L2,k2,n].join(F2)}function cE(t){return oo(t,io)}function uE(t){return ii(t,io)}function lE(t){return ii([ao(t.header),ao(t.payload)].join(ro),lh)}function fE(t){return[ao(t.header),ao(t.payload),cE(t.signature)].join(ro)}function yc(t){const e=t.split(ro),n=Th(e[0]),r=Th(e[1]),i=uE(e[2]),s=ii(e.slice(0,2).join(ro),lh);return{header:n,payload:r,signature:i,data:s}}function Rh(t=zf(j2)){const e=ch.getPublicKey(t);return{secretKey:dh([t,e]),publicKey:e}}async function hE(t,e,n,r,i=H.fromMiliseconds(Date.now())){const s={alg:C2,typ:U2},o=Ph(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=lE({header:s,payload:c}),l=ch.sign(u,r.secretKey.slice(0,32));return fE({header:s,payload:c,signature:l})}var Nh=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))},dE=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),pE=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),gE=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}(),yE=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),bE=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),wE=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,mE=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Ch=3,vE=[["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",wE]],Uh=[["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 EE(t){return t?Fh(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new bE:typeof navigator<"u"?Fh(navigator.userAgent):IE()}function xE(t){return t!==""&&vE.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 Fh(t){var e=xE(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new yE;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<Ch&&(i=Nh(Nh([],i,!0),SE(Ch-i.length),!0)):i=[];var s=i.join("."),o=_E(t),a=mE.exec(t);return a&&a[1]?new gE(n,s,o,a[1]):new dE(n,s,o)}function _E(t){for(var e=0,n=Uh.length;e<n;e++){var r=Uh[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function IE(){var t=typeof process<"u"&&process.version;return t?new pE(process.version.slice(1)):null}function SE(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var we={};Object.defineProperty(we,"__esModule",{value:!0}),we.getLocalStorage=we.getLocalStorageOrThrow=we.getCrypto=we.getCryptoOrThrow=Lh=we.getLocation=we.getLocationOrThrow=bc=we.getNavigator=we.getNavigatorOrThrow=Pr=we.getDocument=we.getDocumentOrThrow=we.getFromWindowOrThrow=we.getFromWindow=void 0;function Tr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}we.getFromWindow=Tr;function si(t){const e=Tr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}we.getFromWindowOrThrow=si;function OE(){return si("document")}we.getDocumentOrThrow=OE;function BE(){return Tr("document")}var Pr=we.getDocument=BE;function AE(){return si("navigator")}we.getNavigatorOrThrow=AE;function DE(){return Tr("navigator")}var bc=we.getNavigator=DE;function $E(){return si("location")}we.getLocationOrThrow=$E;function TE(){return Tr("location")}var Lh=we.getLocation=TE;function PE(){return si("crypto")}we.getCryptoOrThrow=PE;function RE(){return Tr("crypto")}we.getCrypto=RE;function NE(){return si("localStorage")}we.getLocalStorageOrThrow=NE;function CE(){return Tr("localStorage")}we.getLocalStorage=CE;var wc={};Object.defineProperty(wc,"__esModule",{value:!0});var kh=wc.getWindowMetadata=void 0;const qh=we;function UE(){let t,e;try{t=qh.getDocumentOrThrow(),e=qh.getLocationOrThrow()}catch{return null}function n(){const f=t.getElementsByTagName("link"),d=[];for(let h=0;h<f.length;h++){const p=f[h],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const m=p.getAttribute("href");if(m)if(m.toLowerCase().indexOf("https:")===-1&&m.toLowerCase().indexOf("http:")===-1&&m.indexOf("//")!==0){let B=e.protocol+"//"+e.host;if(m.indexOf("/")===0)B+=m;else{const $=e.pathname.split("/");$.pop();const x=$.join("/");B+=x+"/"+m}d.push(B)}else if(m.indexOf("//")===0){const B=e.protocol+m;d.push(B)}else d.push(m)}}return d}function r(...f){const d=t.getElementsByTagName("meta");for(let h=0;h<d.length;h++){const p=d[h],g=["itemprop","property","name"].map(m=>p.getAttribute(m)).filter(m=>m?f.includes(m):!1);if(g.length&&g){const m=p.getAttribute("content");if(m)return m}}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}}kh=wc.getWindowMetadata=UE;const FE="0.1.1";function LE(){return FE}class ye extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof ye){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 ye&&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(`
|
|
15
|
-
`);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${LE()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Mh(this,e)}}function Mh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Mh(t.cause,e):e?null:t}const oi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function co(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ai(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function wn(t,...e){if(!co(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 jh(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ai(t.outputLen),ai(t.blockLen)}function ci(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 zh(t,e){wn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function kE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Wn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function mc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function on(t,e){return t<<32-e|t>>>e}const qE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ME(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function jE(t){for(let e=0;e<t.length;e++)t[e]=ME(t[e]);return t}const Vh=qE?t=>t:jE,Kh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ui(t){if(wn(t),Kh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=zE[t[n]];return e}const mn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hh(t){if(t>=mn._0&&t<=mn._9)return t-mn._0;if(t>=mn.A&&t<=mn.F)return t-(mn.A-10);if(t>=mn.a&&t<=mn.f)return t-(mn.a-10)}function uo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Kh)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=Hh(t.charCodeAt(s)),a=Hh(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 vc(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function lo(t){return typeof t=="string"&&(t=vc(t)),wn(t),t}function vn(...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}class Ec{}function fo(t){const e=r=>t().update(lo(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ho(t=32){if(oi&&typeof oi.getRandomValues=="function")return oi.getRandomValues(new Uint8Array(t));if(oi&&typeof oi.randomBytes=="function")return Uint8Array.from(oi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function VE(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 KE(t,e,n){return t&e^~t&n}function HE(t,e,n){return t&e^t&n^e&n}class Gh extends Ec{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=mc(this.buffer)}update(e){ci(this),e=lo(e),wn(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=mc(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){ci(this),zh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Wn(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;VE(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=mc(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 En=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),We=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),po=BigInt(2**32-1),Wh=BigInt(32);function GE(t,e=!1){return e?{h:Number(t&po),l:Number(t>>Wh&po)}:{h:Number(t>>Wh&po)|0,l:Number(t&po)|0}}function Zh(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}=GE(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Yh=(t,e,n)=>t>>>n,Xh=(t,e,n)=>t<<32-n|e>>>n,li=(t,e,n)=>t>>>n|e<<32-n,fi=(t,e,n)=>t<<32-n|e>>>n,go=(t,e,n)=>t<<64-n|e>>>n-32,yo=(t,e,n)=>t>>>n-32|e<<64-n,WE=(t,e,n)=>t<<n|e>>>32-n,ZE=(t,e,n)=>e<<n|t>>>32-n,YE=(t,e,n)=>e<<n-32|t>>>64-n,XE=(t,e,n)=>t<<n-32|e>>>64-n;function xn(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const JE=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),QE=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,e3=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),t3=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,n3=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),r3=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,i3=BigInt(0),Vi=BigInt(1),s3=BigInt(2),o3=BigInt(7),a3=BigInt(256),c3=BigInt(113),Jh=[],Qh=[],ed=[];for(let t=0,e=Vi,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Jh.push(2*(5*r+n)),Qh.push((t+1)*(t+2)/2%64);let i=i3;for(let s=0;s<7;s++)e=(e<<Vi^(e>>o3)*c3)%a3,e&s3&&(i^=Vi<<(Vi<<BigInt(s))-Vi);ed.push(i)}const td=Zh(ed,!0),u3=td[0],l3=td[1],nd=(t,e,n)=>n>32?YE(t,e,n):WE(t,e,n),rd=(t,e,n)=>n>32?XE(t,e,n):ZE(t,e,n);function f3(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=nd(u,l,1)^n[a],d=rd(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Qh[o],c=nd(i,s,a),u=rd(i,s,a),l=Jh[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]^=u3[r],t[1]^=l3[r]}Wn(n)}class xc extends Ec{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,ai(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=kE(this.state)}clone(){return this._cloneInto()}keccak(){Vh(this.state32),f3(this.state32,this.rounds),Vh(this.state32),this.posOut=0,this.pos=0}update(e){ci(this),e=lo(e),wn(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){ci(this,!1),wn(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 ai(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zh(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,Wn(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new xc(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 h3=(t,e,n)=>fo(()=>new xc(e,t,n)),d3=h3(1,136,256/8),p3=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]),Zn=new Uint32Array(64);class g3 extends Gh{constructor(e=32){super(64,e,8,!1),this.A=En[0]|0,this.B=En[1]|0,this.C=En[2]|0,this.D=En[3]|0,this.E=En[4]|0,this.F=En[5]|0,this.G=En[6]|0,this.H=En[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)Zn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=Zn[f-15],h=Zn[f-2],p=on(d,7)^on(d,18)^d>>>3,g=on(h,17)^on(h,19)^h>>>10;Zn[f]=g+Zn[f-7]+p+Zn[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 d=on(a,6)^on(a,11)^on(a,25),h=l+d+KE(a,c,u)+p3[f]+Zn[f]|0,g=(on(r,2)^on(r,13)^on(r,22))+HE(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+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(){Wn(Zn)}destroy(){this.set(0,0,0,0,0,0,0,0),Wn(this.buffer)}}const id=Zh(["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))),y3=id[0],b3=id[1],Yn=new Uint32Array(80),Xn=new Uint32Array(80);class sd extends Gh{constructor(e=64){super(128,e,16,!1),this.Ah=We[0]|0,this.Al=We[1]|0,this.Bh=We[2]|0,this.Bl=We[3]|0,this.Ch=We[4]|0,this.Cl=We[5]|0,this.Dh=We[6]|0,this.Dl=We[7]|0,this.Eh=We[8]|0,this.El=We[9]|0,this.Fh=We[10]|0,this.Fl=We[11]|0,this.Gh=We[12]|0,this.Gl=We[13]|0,this.Hh=We[14]|0,this.Hl=We[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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)Yn[x]=e.getUint32(n),Xn[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=Yn[x-15]|0,T=Xn[x-15]|0,P=li(_,T,1)^li(_,T,8)^Yh(_,T,7),C=fi(_,T,1)^fi(_,T,8)^Xh(_,T,7),U=Yn[x-2]|0,D=Xn[x-2]|0,j=li(U,D,19)^go(U,D,61)^Yh(U,D,6),M=fi(U,D,19)^yo(U,D,61)^Xh(U,D,6),E=e3(C,M,Xn[x-7],Xn[x-16]),b=t3(E,P,j,Yn[x-7],Yn[x-16]);Yn[x]=b|0,Xn[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=li(f,d,14)^li(f,d,18)^go(f,d,41),T=fi(f,d,14)^fi(f,d,18)^yo(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=n3($,T,C,b3[x],Xn[x]),D=r3(U,B,_,P,y3[x],Yn[x]),j=U|0,M=li(r,i,28)^go(r,i,34)^go(r,i,39),E=fi(r,i,28)^yo(r,i,34)^yo(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=xn(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=JE(j,E,v);r=QE(y,D,M,b),i=y|0}({h:r,l:i}=xn(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=xn(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=xn(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=xn(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=xn(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=xn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=xn(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=xn(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){Wn(Yn,Xn)}destroy(){Wn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class w3 extends sd{constructor(){super(48),this.Ah=Ge[0]|0,this.Al=Ge[1]|0,this.Bh=Ge[2]|0,this.Bl=Ge[3]|0,this.Ch=Ge[4]|0,this.Cl=Ge[5]|0,this.Dh=Ge[6]|0,this.Dl=Ge[7]|0,this.Eh=Ge[8]|0,this.El=Ge[9]|0,this.Fh=Ge[10]|0,this.Fl=Ge[11]|0,this.Gh=Ge[12]|0,this.Gl=Ge[13]|0,this.Hh=Ge[14]|0,this.Hl=Ge[15]|0}}const hi=fo(()=>new g3),m3=fo(()=>new sd),v3=fo(()=>new w3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _c=BigInt(0),bo=BigInt(1);function Ki(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Jn(t){if(!Ki(t))throw new Error("Uint8Array expected")}function Hi(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function wo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function od(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?_c:BigInt("0x"+t)}const ad=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",E3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rr(t){if(Jn(t),ad)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=E3[t[n]];return e}const _n={_0:48,_9:57,A:65,F:70,a:97,f:102};function cd(t){if(t>=_n._0&&t<=_n._9)return t-_n._0;if(t>=_n.A&&t<=_n.F)return t-(_n.A-10);if(t>=_n.a&&t<=_n.f)return t-(_n.a-10)}function mo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(ad)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=cd(t.charCodeAt(s)),a=cd(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 it(t){return od(Rr(t))}function ud(t){return Jn(t),od(Rr(Uint8Array.from(t).reverse()))}function $e(t,e){return mo(t.toString(16).padStart(e*2,"0"))}function ld(t,e){return $e(t,e).reverse()}function Ze(t,e,n){let r;if(typeof e=="string")try{r=mo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Ki(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 Ie(...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}function Ic(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Sc=t=>typeof t=="bigint"&&_c<=t;function Oc(t,e,n){return Sc(t)&&Sc(e)&&Sc(n)&&e<=t&&t<n}function di(t,e,n,r){if(!Oc(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Gi(t){let e;for(e=0;t>_c;t>>=bo,e+=1);return e}function x3(t,e){return t>>BigInt(e)&bo}const Nr=t=>(bo<<BigInt(t))-bo,Bc=t=>new Uint8Array(t),fd=t=>Uint8Array.from(t);function _3(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=Bc(t),i=Bc(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...f)=>n(i,r,...f),c=(f=Bc(0))=>{i=a(fd([0]),f),r=a(),f.length!==0&&(i=a(fd([1]),f),r=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){r=a();const h=r.slice();d.push(h),f+=r.length}return Ie(...d)};return(f,d)=>{o(),c(f);let h;for(;!(h=d(u()));)c();return o(),h}}const I3={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"||Ki(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 Wi(t,e,n={}){const r=(i,s,o)=>{const a=I3[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}const hd=()=>{throw new Error("not implemented")};function Ac(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}}function S3(t,e){if(wd(t)>e)throw new G3({givenSize:wd(t),maxSize:e})}const In={zero:48,nine:57,A:65,F:70,a:97,f:102};function dd(t){if(t>=In.zero&&t<=In.nine)return t-In.zero;if(t>=In.A&&t<=In.F)return t-(In.A-10);if(t>=In.a&&t<=In.f)return t-(In.a-10)}function O3(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new W3({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 Dc(t,e){if(On(t)>e)throw new F3({givenSize:On(t),maxSize:e})}function B3(t,e){if(typeof e=="number"&&e>0&&e>On(t)-1)throw new bd({offset:e,position:"start",size:On(t)})}function A3(t,e,n){if(typeof e=="number"&&typeof n=="number"&&On(t)!==n-e)throw new bd({offset:n,position:"end",size:On(t)})}function pd(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 L3({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const D3="#__bigint";function $c(t,e,n){return JSON.stringify(t,(r,i)=>typeof e=="function"?e(r,i):typeof i=="bigint"?i.toString()+D3:i,n)}const $3=new TextEncoder,T3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function P3(t,e={}){const{strict:n=!1}=e;if(!t)throw new gd(t);if(typeof t!="string")throw new gd(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new yd(t);if(!t.startsWith("0x"))throw new yd(t)}function Tc(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function Pc(t){return t instanceof Uint8Array?Zi(t):Array.isArray(t)?Zi(new Uint8Array(t)):t}function R3(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Dc(n,e.size),Eo(n,e.size)):n}function Zi(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=T3[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(Dc(r,e.size),Rc(r,e.size)):r}function vo(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 U3({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?Eo(c,r):c}function N3(t,e={}){return Zi($3.encode(t),e)}function Eo(t,e){return pd(t,{dir:"left",size:e})}function Rc(t,e){return pd(t,{dir:"right",size:e})}function Sn(t,e,n,r={}){const{strict:i}=r;B3(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return i&&A3(s,e,n),s}function On(t){return Math.ceil((t.length-2)/2)}function C3(t,e={}){const{strict:n=!1}=e;try{return P3(t,{strict:n}),!0}catch{return!1}}class U3 extends ye{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 gd extends ye{constructor(e){super(`Value \`${typeof e=="object"?$c(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class yd extends ye{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class F3 extends ye{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 bd extends ye{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class L3 extends ye{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const k3=new TextEncoder;function q3(t){if(!(t instanceof Uint8Array)){if(!t)throw new xo(t);if(typeof t!="object")throw new xo(t);if(!("BYTES_PER_ELEMENT"in t))throw new xo(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new xo(t)}}function M3(t){return t instanceof Uint8Array?t:typeof t=="string"?z3(t):j3(t)}function j3(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function z3(t,e={}){const{size:n}=e;let r=t;n&&(Dc(t,n),r=Rc(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=dd(i.charCodeAt(c++)),l=dd(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new ye(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function V3(t,e={}){const{size:n}=e,r=k3.encode(t);return typeof n=="number"?(S3(r,n),K3(r,n)):r}function K3(t,e){return O3(t,{dir:"right",size:e})}function wd(t){return t.length}function H3(t){try{return q3(t),!0}catch{return!1}}class xo extends ye{constructor(e){super(`Value \`${typeof e=="object"?$c(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class G3 extends ye{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 W3 extends ye{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function md(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=d3(M3(t));return n==="Bytes"?r:Zi(r)}class Z3 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 Nc={checksum:new Z3(8192)}.checksum;function vd(t,e={}){const{compressed:n}=e,{prefix:r,x:i,y:s}=t;if(n===!1||typeof i=="bigint"&&typeof s=="bigint"){if(r!==4)throw new xd({prefix:r,cause:new t8});return}if(n===!0||typeof i=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new xd({prefix:r,cause:new e8});return}throw new Q3({publicKey:t})}function Y3(t){const e=(()=>{if(C3(t))return Ed(t);if(H3(t))return X3(t);const{prefix:n,x:r,y:i}=t;return typeof r=="bigint"&&typeof i=="bigint"?{prefix:n??4,x:r,y:i}:{prefix:n,x:r}})();return vd(e),e}function X3(t){return Ed(Zi(t))}function Ed(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new n8({publicKey:t});if(t.length===130){const r=BigInt(Sn(t,0,32)),i=BigInt(Sn(t,32,64));return{prefix:4,x:r,y:i}}if(t.length===132){const r=Number(Sn(t,0,1)),i=BigInt(Sn(t,1,33)),s=BigInt(Sn(t,33,65));return{prefix:r,x:i,y:s}}const e=Number(Sn(t,0,1)),n=BigInt(Sn(t,1,33));return{prefix:e,x:n}}function J3(t,e={}){vd(t);const{prefix:n,x:r,y:i}=t,{includePrefix:s=!0}=e;return Tc(s?vo(n,{size:1}):"0x",vo(r,{size:32}),typeof i=="bigint"?vo(i,{size:32}):"0x")}class Q3 extends ye{constructor({publicKey:e}){super(`Value \`${$c(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class xd extends ye{constructor({prefix:e,cause:n}){super(`Prefix "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class e8 extends ye{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class t8 extends ye{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class n8 extends ye{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${On(Pc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const r8=/^0x[a-fA-F0-9]{40}$/;function Cc(t,e={}){const{strict:n=!0}=e;if(!r8.test(t))throw new Id({address:t,cause:new o8});if(n){if(t.toLowerCase()===t)return;if(_d(t)!==t)throw new Id({address:t,cause:new a8})}}function _d(t){if(Nc.has(t))return Nc.get(t);Cc(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=md(V3(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 Nc.set(t,i),i}function i8(t,e={}){const{checksum:n=!1}=e;return Cc(t),n?_d(t):t}function s8(t,e={}){const n=md(`0x${J3(t).slice(4)}`).substring(26);return i8(`0x${n}`,e)}class Id extends ye{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 o8 extends ye{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 a8 extends ye{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const c8=/^(.*)\[([0-9]*)\]$/,u8=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,l8=/^(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 Uc(t,e){if(t.length!==e.length)throw new h8({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(Uc.encode(i,s))}return Tc(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return Cc(c),Eo(c.toLowerCase(),i?32:0)}if(n==="string")return N3(r);if(n==="bytes")return r;if(n==="bool")return Eo(R3(r),i?32:1);const s=n.match(l8);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return vo(r,{size:i?32:f,signed:u==="int"})}const o=n.match(u8);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(r.length-2)/2)throw new f8({expectedSize:Number.parseInt(u,10),value:r});return Rc(r,i?32:0)}const a=n.match(c8);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let f=0;f<r.length;f++)l.push(e(u,r[f],!0));return l.length===0?"0x":Tc(...l)}throw new d8(n)}t.encode=e})(Uc||(Uc={}));class f8 extends ye{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${On(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class h8 extends ye{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
|
|
16
|
-
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class d8 extends ye{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 Sd extends Ec{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,jh(e);const r=lo(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),Wn(s)}update(e){return ci(this),this.iHash.update(e),this}digestInto(e){ci(this),wn(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 Fc=(t,e,n)=>new Sd(t,e).update(n).digest();Fc.create=(t,e)=>new Sd(t,e);const gt=BigInt(0),st=BigInt(1),Cr=BigInt(2),p8=BigInt(3),Od=BigInt(4),Bd=BigInt(5),Ad=BigInt(8);function ot(t,e){const n=t%e;return n>=gt?n:e+n}function Ct(t,e,n){let r=t;for(;e-- >gt;)r*=r,r%=n;return r}function Lc(t,e){if(t===gt)throw new Error("invert: expected non-zero number");if(e<=gt)throw new Error("invert: expected positive modulus, got "+e);let n=ot(t,e),r=e,i=gt,s=st;for(;n!==gt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==st)throw new Error("invert: does not exist");return ot(i,e)}function Dd(t,e){const n=(t.ORDER+st)/Od,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function g8(t,e){const n=(t.ORDER-Bd)/Ad,r=t.mul(e,Cr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Cr),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 y8(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-st,n=0;for(;e%Cr===gt;)e/=Cr,n++;let r=Cr;const i=Qn(t);for(;Io(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Dd;let s=i.pow(r,e);const o=(e+st)/Cr;return function(c,u){if(c.is0(u))return u;if(Io(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const m=st<<BigInt(l-p-1),B=c.pow(f,m);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function b8(t){return t%Od===p8?Dd:t%Ad===Bd?g8:y8(t)}const w8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $d(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=w8.reduce((r,i)=>(r[i]="function",r),e);return Wi(t,n)}function _o(t,e,n){if(n<gt)throw new Error("invalid exponent, negatives unsupported");if(n===gt)return t.ONE;if(n===st)return e;let r=t.ONE,i=e;for(;n>gt;)n&st&&(r=t.mul(r,i)),i=t.sqr(i),n>>=st;return r}function Ur(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 Io(t,e){const n=(t.ORDER-st)/Cr,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 Td(t,e){e!==void 0&&ai(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function Qn(t,e,n=!1,r={}){if(t<=gt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Td(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:Nr(i),ZERO:gt,ONE:st,create:c=>ot(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return gt<=c&&c<t},is0:c=>c===gt,isOdd:c=>(c&st)===st,neg:c=>ot(-c,t),eql:(c,u)=>c===u,sqr:c=>ot(c*c,t),add:(c,u)=>ot(c+u,t),sub:(c,u)=>ot(c-u,t),mul:(c,u)=>ot(c*u,t),pow:(c,u)=>_o(a,c,u),div:(c,u)=>ot(c*Lc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Lc(c,t),sqrt:r.sqrt||(c=>(o||(o=b8(t)),o(a,c))),toBytes:c=>n?ld(c,s):$e(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?ud(c):it(c)},invertBatch:c=>Ur(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function Pd(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 kc(t){const e=Pd(t);return e+Math.ceil(e/2)}function Rd(t,e,n=!1){const r=t.length,i=Pd(e),s=kc(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ud(t):it(t),a=ot(o,e-st)+st;return n?ld(a,i):$e(a,i)}const Nd=BigInt(0),qc=BigInt(1);function Mc(t,e){const n=e.negate();return t?n:e}function Cd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jc(t,e){Cd(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Nr(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Ud(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+=qc);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function m8(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 v8(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 zc=new WeakMap,Fd=new WeakMap;function Vc(t){return Fd.get(t)||1}function E8(t,e){return{constTimeNegate:Mc,hasPrecomputes(n){return Vc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Nd;)r&qc&&(i=i.add(s)),s=s.double(),r>>=qc;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=jc(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=jc(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Ud(i,c,a);i=u,f?o=o.add(Mc(h,r[p])):s=s.add(Mc(d,r[l]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=jc(n,e);for(let a=0;a<o.windows&&i!==Nd;a++){const{nextN:c,offset:u,isZero:l,isNeg:f}=Ud(i,a,o);if(i=c,!l){const d=r[u];s=s.add(f?d.negate():d)}}return s},getPrecomputes(n,r,i){let s=zc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&zc.set(r,i(s))),s},wNAFCached(n,r,i){const s=Vc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Vc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Cd(r,e),Fd.set(n,r),zc.delete(n)}}}function x8(t,e,n,r){m8(n,t),v8(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=Gi(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Nr(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Ld(t){return $d(t.Fp),Wi(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Td(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function kd(t){t.lowS!==void 0&&Hi("lowS",t.lowS),t.prehash!==void 0&&Hi("prehash",t.prehash)}function _8(t){const e=Ld(t);Wi(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 I8 extends Error{constructor(e=""){super(e)}}const Bn={Err:I8,_tlv:{encode:(t,e)=>{const{Err:n}=Bn;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=wo(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?wo(i.length/2|128):"";return wo(t)+s+i+e},decode(t,e){const{Err:n}=Bn;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}=Bn;if(t<Gt)throw new e("integer: negative integers are not allowed");let n=wo(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}=Bn;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 it(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Bn,i=Ze("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}=Bn,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 Kc(t,e){return Rr($e(t,e))}const Gt=BigInt(0),ge=BigInt(1),er=BigInt(2),Yi=BigInt(3),Hc=BigInt(4);function Gc(t){const e=_8(t),{Fp:n}=e,r=Qn(e.n,e.nBitLength),i=e.toBytes||((x,_,T)=>{const P=_.toAffine();return Ie(Uint8Array.from([4]),n.toBytes(P.x),n.toBytes(P.y))}),s=e.fromBytes||(x=>{const _=x.subarray(1),T=n.fromBytes(_.subarray(0,n.BYTES)),P=n.fromBytes(_.subarray(n.BYTES,2*n.BYTES));return{x:T,y:P}});function o(x){const{a:_,b:T}=e,P=n.sqr(x),C=n.mul(P,x);return n.add(n.add(C,n.mul(x,_)),T)}function a(x,_){const T=n.sqr(_),P=o(x);return n.eql(T,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,Yi),Hc),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(x){return Oc(x,ge,e.n)}function f(x){const{allowedPrivateKeyLengths:_,nByteLength:T,wrapPrivateKey:P,n:C}=e;if(_&&typeof x!="bigint"){if(Ki(x)&&(x=Rr(x)),typeof x!="string"||!_.includes(x.length))throw new Error("invalid private key");x=x.padStart(T*2,"0")}let U;try{U=typeof x=="bigint"?x:it(Ze("private key",x,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof x)}return P&&(U=ot(U,C)),di("private key",U,ge,C),U}function d(x){if(!(x instanceof g))throw new Error("ProjectivePoint expected")}const h=Ac((x,_)=>{const{px:T,py:P,pz:C}=x;if(n.eql(C,n.ONE))return{x:T,y:P};const U=x.is0();_==null&&(_=U?n.ONE:n.inv(C));const D=n.mul(T,_),j=n.mul(P,_),M=n.mul(C,_);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:D,y:j}}),p=Ac(x=>{if(x.is0()){if(e.allowInfinityPoint&&!n.is0(x.py))return;throw new Error("bad point: ZERO")}const{x:_,y:T}=x.toAffine();if(!n.isValid(_)||!n.isValid(T))throw new Error("bad point: x or y not FE");if(!a(_,T))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(_,T,P){if(_==null||!n.isValid(_))throw new Error("x required");if(T==null||!n.isValid(T)||n.is0(T))throw new Error("y required");if(P==null||!n.isValid(P))throw new Error("z required");this.px=_,this.py=T,this.pz=P,Object.freeze(this)}static fromAffine(_){const{x:T,y:P}=_||{};if(!_||!n.isValid(T)||!n.isValid(P))throw new Error("invalid affine point");if(_ instanceof g)throw new Error("projective point not allowed");const C=U=>n.eql(U,n.ZERO);return C(T)&&C(P)?g.ZERO:new g(T,P,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(_){const T=Ur(n,_.map(P=>P.pz));return _.map((P,C)=>P.toAffine(T[C])).map(g.fromAffine)}static fromHex(_){const T=g.fromAffine(s(Ze("pointHex",_)));return T.assertValidity(),T}static fromPrivateKey(_){return g.BASE.multiply(f(_))}static msm(_,T){return x8(g,r,_,T)}_setWindowSize(_){$.setWindowSize(this,_)}assertValidity(){p(this)}hasEvenY(){const{y:_}=this.toAffine();if(n.isOdd)return!n.isOdd(_);throw new Error("Field doesn't support isOdd")}equals(_){d(_);const{px:T,py:P,pz:C}=this,{px:U,py:D,pz:j}=_,M=n.eql(n.mul(T,j),n.mul(U,C)),E=n.eql(n.mul(P,j),n.mul(D,C));return M&&E}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:_,b:T}=e,P=n.mul(T,Yi),{px:C,py:U,pz:D}=this;let j=n.ZERO,M=n.ZERO,E=n.ZERO,b=n.mul(C,C),v=n.mul(U,U),y=n.mul(D,D),w=n.mul(C,U);return w=n.add(w,w),E=n.mul(C,D),E=n.add(E,E),j=n.mul(_,E),M=n.mul(P,y),M=n.add(j,M),j=n.sub(v,M),M=n.add(v,M),M=n.mul(j,M),j=n.mul(w,j),E=n.mul(P,E),y=n.mul(_,y),w=n.sub(b,y),w=n.mul(_,w),w=n.add(w,E),E=n.add(b,b),b=n.add(E,b),b=n.add(b,y),b=n.mul(b,w),M=n.add(M,b),y=n.mul(U,D),y=n.add(y,y),b=n.mul(y,w),j=n.sub(j,b),E=n.mul(y,v),E=n.add(E,E),E=n.add(E,E),new g(j,M,E)}add(_){d(_);const{px:T,py:P,pz:C}=this,{px:U,py:D,pz:j}=_;let M=n.ZERO,E=n.ZERO,b=n.ZERO;const v=e.a,y=n.mul(e.b,Yi);let w=n.mul(T,U),I=n.mul(P,D),O=n.mul(C,j),S=n.add(T,P),A=n.add(U,D);S=n.mul(S,A),A=n.add(w,I),S=n.sub(S,A),A=n.add(T,C);let R=n.add(U,j);return A=n.mul(A,R),R=n.add(w,O),A=n.sub(A,R),R=n.add(P,C),M=n.add(D,j),R=n.mul(R,M),M=n.add(I,O),R=n.sub(R,M),b=n.mul(v,A),M=n.mul(y,O),b=n.add(M,b),M=n.sub(I,b),b=n.add(I,b),E=n.mul(M,b),I=n.add(w,w),I=n.add(I,w),O=n.mul(v,O),A=n.mul(y,A),I=n.add(I,O),O=n.sub(w,O),O=n.mul(v,O),A=n.add(A,O),w=n.mul(I,A),E=n.add(E,w),w=n.mul(R,A),M=n.mul(S,M),M=n.sub(M,w),w=n.mul(S,I),b=n.mul(R,b),b=n.add(b,w),new g(M,E,b)}subtract(_){return this.add(_.negate())}is0(){return this.equals(g.ZERO)}wNAF(_){return $.wNAFCached(this,_,g.normalizeZ)}multiplyUnsafe(_){const{endo:T,n:P}=e;di("scalar",_,Gt,P);const C=g.ZERO;if(_===Gt)return C;if(this.is0()||_===ge)return this;if(!T||$.hasPrecomputes(this))return $.wNAFCachedUnsafe(this,_,g.normalizeZ);let{k1neg:U,k1:D,k2neg:j,k2:M}=T.splitScalar(_),E=C,b=C,v=this;for(;D>Gt||M>Gt;)D&ge&&(E=E.add(v)),M&ge&&(b=b.add(v)),v=v.double(),D>>=ge,M>>=ge;return U&&(E=E.negate()),j&&(b=b.negate()),b=new g(n.mul(b.px,T.beta),b.py,b.pz),E.add(b)}multiply(_){const{endo:T,n:P}=e;di("scalar",_,ge,P);let C,U;if(T){const{k1neg:D,k1:j,k2neg:M,k2:E}=T.splitScalar(_);let{p:b,f:v}=this.wNAF(j),{p:y,f:w}=this.wNAF(E);b=$.constTimeNegate(D,b),y=$.constTimeNegate(M,y),y=new g(n.mul(y.px,T.beta),y.py,y.pz),C=b.add(y),U=v.add(w)}else{const{p:D,f:j}=this.wNAF(_);C=D,U=j}return g.normalizeZ([C,U])[0]}multiplyAndAddUnsafe(_,T,P){const C=g.BASE,U=(j,M)=>M===Gt||M===ge||!j.equals(C)?j.multiplyUnsafe(M):j.multiply(M),D=U(this,T).add(U(_,P));return D.is0()?void 0:D}toAffine(_){return h(this,_)}isTorsionFree(){const{h:_,isTorsionFree:T}=e;if(_===ge)return!0;if(T)return T(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:_,clearCofactor:T}=e;return _===ge?this:T?T(g,this):this.multiplyUnsafe(e.h)}toRawBytes(_=!0){return Hi("isCompressed",_),this.assertValidity(),i(g,this,_)}toHex(_=!0){return Hi("isCompressed",_),Rr(this.toRawBytes(_))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:m,nBitLength:B}=e,$=E8(g,m?Math.ceil(B/2):B);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:f,weierstrassEquation:o,isWithinCurveOrder:l}}function S8(t){const e=Ld(t);return Wi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function O8(t){const e=S8(t),{Fp:n,n:r,nByteLength:i,nBitLength:s}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(y){return ot(y,r)}function u(y){return Lc(y,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:d,isWithinCurveOrder:h}=Gc({...e,toBytes(y,w,I){const O=w.toAffine(),S=n.toBytes(O.x),A=Ie;return Hi("isCompressed",I),I?A(Uint8Array.from([w.hasEvenY()?2:3]),S):A(Uint8Array.from([4]),S,n.toBytes(O.y))},fromBytes(y){const w=y.length,I=y[0],O=y.subarray(1);if(w===o&&(I===2||I===3)){const S=it(O);if(!Oc(S,ge,n.ORDER))throw new Error("Point is not on curve");const A=d(S);let R;try{R=n.sqrt(A)}catch(k){const N=k instanceof Error?": "+k.message:"";throw new Error("Point is not on curve"+N)}const L=(R&ge)===ge;return(I&1)===1!==L&&(R=n.neg(R)),{x:S,y:R}}else if(w===a&&I===4){const S=n.fromBytes(O.subarray(0,n.BYTES)),A=n.fromBytes(O.subarray(n.BYTES,2*n.BYTES));return{x:S,y:A}}else{const S=o,A=a;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+A+", got "+w)}}});function p(y){const w=r>>ge;return y>w}function g(y){return p(y)?c(-y):y}const m=(y,w,I)=>it(y.slice(w,I));class B{constructor(w,I,O){di("r",w,ge,r),di("s",I,ge,r),this.r=w,this.s=I,O!=null&&(this.recovery=O),Object.freeze(this)}static fromCompact(w){const I=i;return w=Ze("compactSignature",w,I*2),new B(m(w,0,I),m(w,I,2*I))}static fromDER(w){const{r:I,s:O}=Bn.toSig(Ze("DER",w));return new B(I,O)}assertValidity(){}addRecoveryBit(w){return new B(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:O,recovery:S}=this,A=C(Ze("msgHash",w));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");const R=S===2||S===3?I+e.n:I;if(R>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const L=(S&1)===0?"02":"03",F=l.fromHex(L+Kc(R,n.BYTES)),k=u(R),N=c(-A*k),q=c(O*k),z=l.BASE.multiplyAndAddUnsafe(F,N,q);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new B(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return mo(this.toDERHex())}toDERHex(){return Bn.hexFromSig(this)}toCompactRawBytes(){return mo(this.toCompactHex())}toCompactHex(){const w=i;return Kc(this.r,w)+Kc(this.s,w)}}const $={isValidPrivateKey(y){try{return f(y),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const y=kc(e.n);return Rd(e.randomBytes(y),e.n)},precompute(y=8,w=l.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}};function x(y,w=!0){return l.fromPrivateKey(y).toRawBytes(w)}function _(y){if(typeof y=="bigint")return!1;if(y instanceof l)return!0;const I=Ze("key",y).length,O=n.BYTES,S=O+1,A=2*O+1;if(!(e.allowedPrivateKeyLengths||i===S))return I===S||I===A}function T(y,w,I=!0){if(_(y)===!0)throw new Error("first arg must be private key");if(_(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(f(y)).toRawBytes(I)}const P=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const w=it(y),I=y.length*8-s;return I>0?w>>BigInt(I):w},C=e.bits2int_modN||function(y){return c(P(y))},U=Nr(s);function D(y){return di("num < 2^"+s,y,Gt,U),$e(y,i)}function j(y,w,I=M){if(["recovered","canonical"].some(K=>K in I))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:S}=e;let{lowS:A,prehash:R,extraEntropy:L}=I;A==null&&(A=!0),y=Ze("msgHash",y),kd(I),R&&(y=Ze("prehashed msgHash",O(y)));const F=C(y),k=f(w),N=[D(k),D(F)];if(L!=null&&L!==!1){const K=L===!0?S(n.BYTES):L;N.push(Ze("extraEntropy",K))}const q=Ie(...N),z=F;function W(K){const Z=P(K);if(!h(Z))return;const Q=u(Z),ee=l.BASE.multiply(Z).toAffine(),ie=c(ee.x);if(ie===Gt)return;const he=c(Q*c(z+ie*k));if(he===Gt)return;let Ee=(ee.x===ie?0:2)|Number(ee.y&ge),zn=he;return A&&p(he)&&(zn=g(he),Ee^=1),new B(ie,zn,Ee)}return{seed:q,k2sig:W}}const M={lowS:e.lowS,prehash:!1},E={lowS:e.lowS,prehash:!1};function b(y,w,I=M){const{seed:O,k2sig:S}=j(y,w,I),A=e;return _3(A.hash.outputLen,A.nByteLength,A.hmac)(O,S)}l.BASE._setWindowSize(8);function v(y,w,I,O=E){const S=y;w=Ze("msgHash",w),I=Ze("publicKey",I);const{lowS:A,prehash:R,format:L}=O;if(kd(O),"strict"in O)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 F=typeof S=="string"||Ki(S),k=!F&&!L&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!F&&!k)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,q;try{if(k&&(N=new B(S.r,S.s)),F){try{L!=="compact"&&(N=B.fromDER(S))}catch(Ee){if(!(Ee instanceof Bn.Err))throw Ee}!N&&L!=="der"&&(N=B.fromCompact(S))}q=l.fromHex(I)}catch{return!1}if(!N||A&&N.hasHighS())return!1;R&&(w=e.hash(w));const{r:z,s:W}=N,K=C(w),Z=u(W),Q=c(K*Z),ee=c(z*Z),ie=l.BASE.multiplyAndAddUnsafe(q,Q,ee)?.toAffine();return ie?c(ie.x)===z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:T,sign:b,verify:v,ProjectivePoint:l,Signature:B,utils:$}}function B8(t,e){const n=t.ORDER;let r=Gt;for(let p=n-ge;p%er===Gt;p/=er)r+=ge;const i=r,s=er<<i-ge-ge,o=s*er,a=(n-ge)/o,c=(a-ge)/er,u=o-ge,l=s,f=t.pow(e,a),d=t.pow(e,(a+ge)/er);let h=(p,g)=>{let m=f,B=t.pow(g,u),$=t.sqr(B);$=t.mul($,g);let x=t.mul(p,$);x=t.pow(x,c),x=t.mul(x,B),B=t.mul(x,g),$=t.mul(x,p);let _=t.mul($,B);x=t.pow(_,l);let T=t.eql(x,t.ONE);B=t.mul($,d),x=t.mul(_,m),$=t.cmov(B,$,T),_=t.cmov(x,_,T);for(let P=i;P>ge;P--){let C=P-er;C=er<<C-ge;let U=t.pow(_,C);const D=t.eql(U,t.ONE);B=t.mul($,m),m=t.mul(m,m),U=t.mul(_,m),$=t.cmov(B,$,D),_=t.cmov(U,_,D)}return{isValid:T,value:$}};if(t.ORDER%Hc===Yi){const p=(t.ORDER-Yi)/Hc,g=t.sqrt(t.neg(e));h=(m,B)=>{let $=t.sqr(B);const x=t.mul(m,B);$=t.mul($,x);let _=t.pow($,p);_=t.mul(_,x);const T=t.mul(_,g),P=t.mul(t.sqr(_),B),C=t.eql(P,m);let U=t.cmov(T,_,C);return{isValid:C,value:U}}}return h}function qd(t,e){if($d(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=B8(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,u,l,f;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:d,value:h}=n(s,u);f=t.mul(i,r),f=t.mul(f,h),l=t.cmov(l,o,d),f=t.cmov(f,h,d);const p=t.isOdd(r)===t.isOdd(f);f=t.cmov(t.neg(f),f,p);const g=Ur(t,[a],!0)[0];return l=t.mul(l,g),{x:l,y:f}}}function A8(t){return{hash:t,hmac:(e,...n)=>Fc(t,e,vn(...n)),randomBytes:ho}}function So(t,e){const n=r=>O8({...t,...A8(r)});return{...n(e),create:n}}const D8=it;function tr(t,e){if(Xi(t),Xi(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 $8(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 Xi(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function T8(t,e,n,r){Jn(t),Jn(e),Xi(n),e.length>255&&(e=r(Ie(Ic("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=Ie(e,tr(e.length,1)),c=tr(0,s),u=tr(n,2),l=new Array(o),f=r(Ie(c,t,u,tr(0,1),a));l[0]=r(Ie(f,tr(1,1),a));for(let h=1;h<=o;h++){const p=[$8(f,l[h-1]),tr(h+1,1),a];l[h]=r(Ie(...p))}return Ie(...l).slice(0,n)}function P8(t,e,n,r,i){if(Jn(t),Jn(e),Xi(n),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(Ic("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(tr(n,2)).update(e).update(tr(e.length,1)).digest()}function Md(t,e,n){Wi(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;Jn(t),Xi(e);const u=typeof c=="string"?Ic(c):c,l=r.toString(2).length,f=Math.ceil((l+i)/8),d=e*s*f;let h;if(a==="xmd")h=T8(t,u,d,o);else if(a==="xof")h=P8(t,u,d,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const p=new Array(e);for(let g=0;g<e;g++){const m=new Array(s);for(let B=0;B<s;B++){const $=f*(B+g*s),x=h.subarray($,$+f);m[B]=ot(D8(x),r)}p[g]=m}return p}function jd(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(f=>f.reduce((d,h)=>t.add(t.mul(d,r),h))),[u,l]=Ur(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}function zd(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=Md(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=Md(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 Vd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Kd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),R8=BigInt(0),N8=BigInt(1),Wc=BigInt(2),Hd=(t,e)=>(t+e/Wc)/e;function C8(t){const e=Vd,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=Ct(l,n,e)*l%e,d=Ct(f,n,e)*l%e,h=Ct(d,Wc,e)*u%e,p=Ct(h,i,e)*h%e,g=Ct(p,s,e)*p%e,m=Ct(g,a,e)*g%e,B=Ct(m,c,e)*m%e,$=Ct(B,a,e)*g%e,x=Ct($,n,e)*l%e,_=Ct(x,o,e)*p%e,T=Ct(_,r,e)*u%e,P=Ct(T,Wc,e);if(!Zc.eql(Zc.sqr(P),t))throw new Error("Cannot find square root");return P}const Zc=Qn(Vd,void 0,void 0,{sqrt:C8}),U8=So({a:R8,b:BigInt(7),Fp:Zc,n:Kd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Kd,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-N8*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Hd(s*t,e),c=Hd(-r*t,e);let u=ot(t-a*n-c*i,e),l=ot(-a*r-c*s,e);const f=u>o,d=l>o;if(f&&(u=e-u),d&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},hi);function F8(t){if(t.length!==130&&t.length!==132)throw new k8({signature:t});const e=BigInt(Sn(t,0,32)),n=BigInt(Sn(t,32,64)),r=(()=>{const i=+`0x${t.slice(130)}`;if(!Number.isNaN(i))try{return L8(i)}catch{throw new q8({value:i})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function L8(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new M8({value:t})}class k8 extends ye{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${On(Pc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class q8 extends ye{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class M8 extends ye{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}Object.freeze({1:0n,2:1n,3:2n,4:3n,5:4n,6:5n,7:6n,8:7n,9:8n,A:9n,B:10n,C:11n,D:12n,E:13n,F:14n,G:15n,H:16n,J:17n,K:18n,L:19n,M:20n,N:21n,P:22n,Q:23n,R:24n,S:25n,T:26n,U:27n,V:28n,W:29n,X:30n,Y:31n,Z:32n,a:33n,b:34n,c:35n,d:36n,e:37n,f:38n,g:39n,h:40n,i:41n,j:42n,k:43n,m:44n,n:45n,o:46n,p:47n,q:48n,r:49n,s:50n,t:51n,u:52n,v:53n,w:54n,x:55n,y:56n,z:57n}),Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[e,t.charCodeAt(0)]),{...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[t.charCodeAt(0),e]))},En.slice();const j8=BigInt(0),Oo=BigInt(1),Gd=BigInt(2),pi=BigInt(3);function z8(t){const e=[];for(;t>Oo;t>>=Oo)(t&Oo)===j8?e.unshift(0):(t&pi)===pi?(e.unshift(-1),t+=Oo):e.unshift(1);return e}function V8(t){const{Fp:e,Fr:n,Fp2:r,Fp6:i,Fp12:s}=t.fields,o=t.params.xNegative,a=t.params.twistType,c=Gc({n:n.ORDER,...t.G1}),u=Object.assign(c,zd(c.ProjectivePoint,t.G1.mapToCurve,{...t.htfDefaults,...t.G1.htfDefaults})),l=Gc({n:n.ORDER,...t.G2}),f=Object.assign(l,zd(l.ProjectivePoint,t.G2.mapToCurve,{...t.htfDefaults,...t.G2.htfDefaults}));let d;if(a==="multiplicative")d=(F,k,N,q,z,W)=>s.mul014(q,F,r.mul(k,z),r.mul(N,W));else if(a==="divisive")d=(F,k,N,q,z,W)=>s.mul034(q,r.mul(N,W),r.mul(k,z),F);else throw new Error("bls: unknown twist type");const h=r.div(r.ONE,r.mul(r.ONE,Gd));function p(F,k,N,q){const z=r.sqr(N),W=r.sqr(q),K=r.mulByB(r.mul(W,pi)),Z=r.mul(K,pi),Q=r.sub(r.sub(r.sqr(r.add(N,q)),W),z),ee=r.sub(K,z),ie=r.mul(r.sqr(k),pi),he=r.neg(Q);return F.push([ee,ie,he]),k=r.mul(r.mul(r.mul(r.sub(z,Z),k),N),h),N=r.sub(r.sqr(r.mul(r.add(z,Z),h)),r.mul(r.sqr(K),pi)),q=r.mul(z,Q),{Rx:k,Ry:N,Rz:q}}function g(F,k,N,q,z,W){const K=r.sub(N,r.mul(W,q)),Z=r.sub(k,r.mul(z,q)),Q=r.sub(r.mul(K,z),r.mul(Z,W)),ee=r.neg(K),ie=Z;F.push([Q,ee,ie]);const he=r.sqr(Z),Ee=r.mul(he,Z),zn=r.mul(he,k),Aa=r.add(r.sub(Ee,r.mul(zn,Gd)),r.mul(r.sqr(K),q));return k=r.mul(Z,Aa),N=r.sub(r.mul(r.sub(zn,Aa),K),r.mul(Ee,N)),q=r.mul(q,Ee),{Rx:k,Ry:N,Rz:q}}const m=z8(t.params.ateLoopSize),B=Ac(F=>{const k=F,{x:N,y:q}=k.toAffine(),z=N,W=q,K=r.neg(q);let Z=z,Q=W,ee=r.ONE;const ie=[];for(const he of m){const Ee=[];({Rx:Z,Ry:Q,Rz:ee}=p(Ee,Z,Q,ee)),he&&({Rx:Z,Ry:Q,Rz:ee}=g(Ee,Z,Q,ee,z,he===-1?K:W)),ie.push(Ee)}if(t.postPrecompute){const he=ie[ie.length-1];t.postPrecompute(Z,Q,ee,z,W,g.bind(null,he))}return ie});function $(F,k=!1){let N=s.ONE;if(F.length){const q=F[0][0].length;for(let z=0;z<q;z++){N=s.sqr(N);for(const[W,K,Z]of F)for(const[Q,ee,ie]of W[z])N=d(Q,ee,ie,N,K,Z)}}return o&&(N=s.conjugate(N)),k?s.finalExponentiate(N):N}function x(F,k=!0){const N=[];u.ProjectivePoint.normalizeZ(F.map(({g1:q})=>q)),f.ProjectivePoint.normalizeZ(F.map(({g2:q})=>q));for(const{g1:q,g2:z}of F){if(q.equals(u.ProjectivePoint.ZERO)||z.equals(f.ProjectivePoint.ZERO))throw new Error("pairing is not available for ZERO point");q.assertValidity(),z.assertValidity();const W=q.toAffine();N.push([B(z),W.x,W.y])}return $(N,k)}function _(F,k,N=!0){return x([{g1:F,g2:k}],N)}const T={randomPrivateKey:()=>{const F=kc(n.ORDER);return Rd(t.randomBytes(F),n.ORDER)},calcPairingPrecomputes:B},{ShortSignature:P}=t.G1,{Signature:C}=t.G2;function U(F){return F instanceof u.ProjectivePoint?F:u.ProjectivePoint.fromHex(F)}function D(F,k){return F instanceof u.ProjectivePoint?F:u.hashToCurve(Ze("point",F),k)}function j(F){return F instanceof f.ProjectivePoint?F:C.fromHex(F)}function M(F,k){return F instanceof f.ProjectivePoint?F:f.hashToCurve(Ze("point",F),k)}function E(F){return u.ProjectivePoint.fromPrivateKey(F).toRawBytes(!0)}function b(F){return f.ProjectivePoint.fromPrivateKey(F).toRawBytes(!0)}function v(F,k,N){const q=M(F,N);q.assertValidity();const z=q.multiply(u.normPrivateKeyToScalar(k));return F instanceof f.ProjectivePoint?z:C.toRawBytes(z)}function y(F,k,N){const q=D(F,N);q.assertValidity();const z=q.multiply(u.normPrivateKeyToScalar(k));return F instanceof u.ProjectivePoint?z:P.toRawBytes(z)}function w(F,k,N,q){const z=U(N),W=M(k,q),K=u.ProjectivePoint.BASE,Z=j(F),Q=x([{g1:z.negate(),g2:W},{g1:K,g2:Z}]);return s.eql(Q,s.ONE)}function I(F,k,N,q){const z=j(N),W=D(k,q),K=f.ProjectivePoint.BASE,Z=U(F),Q=x([{g1:W,g2:z},{g1:Z,g2:K.negate()}]);return s.eql(Q,s.ONE)}function O(F){if(!Array.isArray(F)||F.length===0)throw new Error("expected non-empty array")}function S(F){O(F);const N=F.map(U).reduce((q,z)=>q.add(z),u.ProjectivePoint.ZERO);return F[0]instanceof u.ProjectivePoint?(N.assertValidity(),N):N.toRawBytes(!0)}function A(F){O(F);const N=F.map(j).reduce((q,z)=>q.add(z),f.ProjectivePoint.ZERO);return F[0]instanceof f.ProjectivePoint?(N.assertValidity(),N):C.toRawBytes(N)}function R(F){O(F);const N=F.map(U).reduce((q,z)=>q.add(z),u.ProjectivePoint.ZERO);return F[0]instanceof u.ProjectivePoint?(N.assertValidity(),N):P.toRawBytes(N)}function L(F,k,N,q){if(O(k),N.length!==k.length)throw new Error("amount of public keys and messages should be equal");const z=j(F),W=k.map(ee=>M(ee,q)),K=N.map(U),Z=new Map;for(let ee=0;ee<K.length;ee++){const ie=K[ee],he=W[ee];let Ee=Z.get(he);Ee===void 0&&(Ee=[],Z.set(he,Ee)),Ee.push(ie)}const Q=[];try{for(const[ee,ie]of Z){const he=ie.reduce((Ee,zn)=>Ee.add(zn));Q.push({g1:he,g2:ee})}return Q.push({g1:u.ProjectivePoint.BASE.negate(),g2:z}),s.eql(x(Q),s.ONE)}catch{return!1}}return u.ProjectivePoint.BASE._setWindowSize(4),{getPublicKey:E,getPublicKeyForShortSignatures:b,sign:v,signShortSignature:y,verify:w,verifyBatch:L,verifyShortSignature:I,aggregatePublicKeys:S,aggregateSignatures:A,aggregateShortSignatures:R,millerLoopBatch:$,pairing:_,pairingBatch:x,G1:u,G2:f,Signature:C,ShortSignature:P,fields:{Fr:n,Fp:e,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:t.params.ateLoopSize,r:t.params.r,G1b:t.G1.b,G2b:t.G2.b},utils:T}}const K8=BigInt(0),gi=BigInt(1),An=BigInt(2),Wd=BigInt(3);function Yc(t,e,n,r,i=1,s){const o=BigInt(s===void 0?r:s),a=n**BigInt(r),c=[];for(let u=0;u<i;u++){const l=BigInt(u+1),f=[];for(let d=0,h=gi;d<r;d++){const p=(l*h-l)/o%a;f.push(t.pow(e,p)),h*=n}c.push(f)}return c}function H8(t,e,n){const r=e.pow(n,(t.ORDER-gi)/Wd),i=e.pow(n,(t.ORDER-gi)/An);function s(d,h){const p=e.mul(e.frobeniusMap(d,1),r),g=e.mul(e.frobeniusMap(h,1),i);return[p,g]}const o=e.pow(n,(t.ORDER**An-gi)/Wd),a=e.pow(n,(t.ORDER**An-gi)/An);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(d,h){return[e.mul(d,o),e.neg(h)]}const u=d=>(h,p)=>{const g=p.toAffine(),m=d(g.x,g.y);return h.fromAffine({x:m[0],y:m[1]})},l=u(s),f=u(c);return{psi:s,psi2:c,G2psi:l,G2psi2:f,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:a}}function G8(t){const{ORDER:e}=t,n=Qn(e),r=n.create(t.NONRESIDUE||BigInt(-1)),i=n.div(n.ONE,An),s=Yc(n,r,n.ORDER,2)[0],o=({c0:E,c1:b},{c0:v,c1:y})=>({c0:n.add(E,v),c1:n.add(b,y)}),a=({c0:E,c1:b},{c0:v,c1:y})=>({c0:n.sub(E,v),c1:n.sub(b,y)}),c=({c0:E,c1:b},v)=>{if(typeof v=="bigint")return{c0:n.mul(E,v),c1:n.mul(b,v)};const{c0:y,c1:w}=v;let I=n.mul(E,y),O=n.mul(b,w);const S=n.sub(I,O),A=n.sub(n.mul(n.add(E,b),n.add(y,w)),n.add(I,O));return{c0:S,c1:A}},u=({c0:E,c1:b})=>{const v=n.add(E,b),y=n.sub(E,b),w=n.add(E,E);return{c0:n.mul(v,y),c1:n.mul(w,b)}},l=E=>{if(E.length!==2)throw new Error("invalid tuple");const b=E.map(v=>n.create(v));return{c0:b[0],c1:b[1]}},f=e*e,d=l(t.FP2_NONRESIDUE),h={ORDER:f,isLE:n.isLE,NONRESIDUE:d,BITS:Gi(f),BYTES:Math.ceil(Gi(f)/8),MASK:Nr(Gi(f)),ZERO:{c0:n.ZERO,c1:n.ZERO},ONE:{c0:n.ONE,c1:n.ZERO},create:E=>E,isValid:({c0:E,c1:b})=>typeof E=="bigint"&&typeof b=="bigint",is0:({c0:E,c1:b})=>n.is0(E)&&n.is0(b),eql:({c0:E,c1:b},{c0:v,c1:y})=>n.eql(E,v)&&n.eql(b,y),neg:({c0:E,c1:b})=>({c0:n.neg(E),c1:n.neg(b)}),pow:(E,b)=>_o(h,E,b),invertBatch:E=>Ur(h,E),add:o,sub:a,mul:c,sqr:u,addN:o,subN:a,mulN:c,sqrN:u,div:(E,b)=>h.mul(E,typeof b=="bigint"?n.inv(n.create(b)):h.inv(b)),inv:({c0:E,c1:b})=>{const v=n.inv(n.create(E*E+b*b));return{c0:n.mul(v,n.create(E)),c1:n.mul(v,n.create(-b))}},sqrt:E=>{if(t.Fp2sqrt)return t.Fp2sqrt(E);const{c0:b,c1:v}=E;if(n.is0(v))return Io(n,b)===1?h.create({c0:n.sqrt(b),c1:n.ZERO}):h.create({c0:n.ZERO,c1:n.sqrt(n.div(b,r))});const y=n.sqrt(n.sub(n.sqr(b),n.mul(n.sqr(v),r)));let w=n.mul(n.add(y,b),i);Io(n,w)===-1&&(w=n.sub(w,y));const O=n.sqrt(w),S=h.create({c0:O,c1:n.div(n.mul(v,i),O)});if(!h.eql(h.sqr(S),E))throw new Error("Cannot find square root");const A=S,R=h.neg(A),{re:L,im:F}=h.reim(A),{re:k,im:N}=h.reim(R);return F>N||F===N&&L>k?A:R},isOdd:E=>{const{re:b,im:v}=h.reim(E),y=b%An,w=b===K8,I=v%An;return BigInt(y||w&&I)==gi},fromBytes(E){if(E.length!==h.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:n.fromBytes(E.subarray(0,n.BYTES)),c1:n.fromBytes(E.subarray(n.BYTES))}},toBytes:({c0:E,c1:b})=>Ie(n.toBytes(E),n.toBytes(b)),cmov:({c0:E,c1:b},{c0:v,c1:y},w)=>({c0:n.cmov(E,v,w),c1:n.cmov(b,y,w)}),reim:({c0:E,c1:b})=>({re:E,im:b}),mulByNonresidue:({c0:E,c1:b})=>h.mul({c0:E,c1:b},d),mulByB:t.Fp2mulByB,fromBigTuple:l,frobeniusMap:({c0:E,c1:b},v)=>({c0:E,c1:n.mul(b,s[v%2])})},p=({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>({c0:h.add(E,y),c1:h.add(b,w),c2:h.add(v,I)}),g=({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>({c0:h.sub(E,y),c1:h.sub(b,w),c2:h.sub(v,I)}),m=({c0:E,c1:b,c2:v},y)=>{if(typeof y=="bigint")return{c0:h.mul(E,y),c1:h.mul(b,y),c2:h.mul(v,y)};const{c0:w,c1:I,c2:O}=y,S=h.mul(E,w),A=h.mul(b,I),R=h.mul(v,O);return{c0:h.add(S,h.mulByNonresidue(h.sub(h.mul(h.add(b,v),h.add(I,O)),h.add(A,R)))),c1:h.add(h.sub(h.mul(h.add(E,b),h.add(w,I)),h.add(S,A)),h.mulByNonresidue(R)),c2:h.sub(h.add(A,h.mul(h.add(E,v),h.add(w,O))),h.add(S,R))}},B=({c0:E,c1:b,c2:v})=>{let y=h.sqr(E),w=h.mul(h.mul(E,b),An),I=h.mul(h.mul(b,v),An),O=h.sqr(v);return{c0:h.add(h.mulByNonresidue(I),y),c1:h.add(h.mulByNonresidue(O),w),c2:h.sub(h.sub(h.add(h.add(w,h.sqr(h.add(h.sub(E,b),v))),I),y),O)}},[$,x]=Yc(h,d,n.ORDER,6,2,3),_={ORDER:h.ORDER,isLE:h.isLE,BITS:3*h.BITS,BYTES:3*h.BYTES,MASK:Nr(3*h.BITS),ZERO:{c0:h.ZERO,c1:h.ZERO,c2:h.ZERO},ONE:{c0:h.ONE,c1:h.ZERO,c2:h.ZERO},create:E=>E,isValid:({c0:E,c1:b,c2:v})=>h.isValid(E)&&h.isValid(b)&&h.isValid(v),is0:({c0:E,c1:b,c2:v})=>h.is0(E)&&h.is0(b)&&h.is0(v),neg:({c0:E,c1:b,c2:v})=>({c0:h.neg(E),c1:h.neg(b),c2:h.neg(v)}),eql:({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>h.eql(E,y)&&h.eql(b,w)&&h.eql(v,I),sqrt:hd,div:(E,b)=>_.mul(E,typeof b=="bigint"?n.inv(n.create(b)):_.inv(b)),pow:(E,b)=>_o(_,E,b),invertBatch:E=>Ur(_,E),add:p,sub:g,mul:m,sqr:B,addN:p,subN:g,mulN:m,sqrN:B,inv:({c0:E,c1:b,c2:v})=>{let y=h.sub(h.sqr(E),h.mulByNonresidue(h.mul(v,b))),w=h.sub(h.mulByNonresidue(h.sqr(v)),h.mul(E,b)),I=h.sub(h.sqr(b),h.mul(E,v)),O=h.inv(h.add(h.mulByNonresidue(h.add(h.mul(v,w),h.mul(b,I))),h.mul(E,y)));return{c0:h.mul(O,y),c1:h.mul(O,w),c2:h.mul(O,I)}},fromBytes:E=>{if(E.length!==_.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:h.fromBytes(E.subarray(0,h.BYTES)),c1:h.fromBytes(E.subarray(h.BYTES,2*h.BYTES)),c2:h.fromBytes(E.subarray(2*h.BYTES))}},toBytes:({c0:E,c1:b,c2:v})=>Ie(h.toBytes(E),h.toBytes(b),h.toBytes(v)),cmov:({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I},O)=>({c0:h.cmov(E,y,O),c1:h.cmov(b,w,O),c2:h.cmov(v,I,O)}),fromBigSix:E=>{if(!Array.isArray(E)||E.length!==6)throw new Error("invalid Fp6 usage");return{c0:h.fromBigTuple(E.slice(0,2)),c1:h.fromBigTuple(E.slice(2,4)),c2:h.fromBigTuple(E.slice(4,6))}},frobeniusMap:({c0:E,c1:b,c2:v},y)=>({c0:h.frobeniusMap(E,y),c1:h.mul(h.frobeniusMap(b,y),$[y%6]),c2:h.mul(h.frobeniusMap(v,y),x[y%6])}),mulByFp2:({c0:E,c1:b,c2:v},y)=>({c0:h.mul(E,y),c1:h.mul(b,y),c2:h.mul(v,y)}),mulByNonresidue:({c0:E,c1:b,c2:v})=>({c0:h.mulByNonresidue(v),c1:E,c2:b}),mul1:({c0:E,c1:b,c2:v},y)=>({c0:h.mulByNonresidue(h.mul(v,y)),c1:h.mul(E,y),c2:h.mul(b,y)}),mul01({c0:E,c1:b,c2:v},y,w){let I=h.mul(E,y),O=h.mul(b,w);return{c0:h.add(h.mulByNonresidue(h.sub(h.mul(h.add(b,v),w),O)),I),c1:h.sub(h.sub(h.mul(h.add(y,w),h.add(E,b)),I),O),c2:h.add(h.sub(h.mul(h.add(E,v),y),I),O)}}},T=Yc(h,d,n.ORDER,12,1,6)[0],P=({c0:E,c1:b},{c0:v,c1:y})=>({c0:_.add(E,v),c1:_.add(b,y)}),C=({c0:E,c1:b},{c0:v,c1:y})=>({c0:_.sub(E,v),c1:_.sub(b,y)}),U=({c0:E,c1:b},v)=>{if(typeof v=="bigint")return{c0:_.mul(E,v),c1:_.mul(b,v)};let{c0:y,c1:w}=v,I=_.mul(E,y),O=_.mul(b,w);return{c0:_.add(I,_.mulByNonresidue(O)),c1:_.sub(_.mul(_.add(E,b),_.add(y,w)),_.add(I,O))}},D=({c0:E,c1:b})=>{let v=_.mul(E,b);return{c0:_.sub(_.sub(_.mul(_.add(_.mulByNonresidue(b),E),_.add(E,b)),v),_.mulByNonresidue(v)),c1:_.add(v,v)}};function j(E,b){const v=h.sqr(E),y=h.sqr(b);return{first:h.add(h.mulByNonresidue(y),v),second:h.sub(h.sub(h.sqr(h.add(E,b)),v),y)}}const M={ORDER:h.ORDER,isLE:_.isLE,BITS:2*_.BITS,BYTES:2*_.BYTES,MASK:Nr(2*_.BITS),ZERO:{c0:_.ZERO,c1:_.ZERO},ONE:{c0:_.ONE,c1:_.ZERO},create:E=>E,isValid:({c0:E,c1:b})=>_.isValid(E)&&_.isValid(b),is0:({c0:E,c1:b})=>_.is0(E)&&_.is0(b),neg:({c0:E,c1:b})=>({c0:_.neg(E),c1:_.neg(b)}),eql:({c0:E,c1:b},{c0:v,c1:y})=>_.eql(E,v)&&_.eql(b,y),sqrt:hd,inv:({c0:E,c1:b})=>{let v=_.inv(_.sub(_.sqr(E),_.mulByNonresidue(_.sqr(b))));return{c0:_.mul(E,v),c1:_.neg(_.mul(b,v))}},div:(E,b)=>M.mul(E,typeof b=="bigint"?n.inv(n.create(b)):M.inv(b)),pow:(E,b)=>_o(M,E,b),invertBatch:E=>Ur(M,E),add:P,sub:C,mul:U,sqr:D,addN:P,subN:C,mulN:U,sqrN:D,fromBytes:E=>{if(E.length!==M.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:_.fromBytes(E.subarray(0,_.BYTES)),c1:_.fromBytes(E.subarray(_.BYTES))}},toBytes:({c0:E,c1:b})=>Ie(_.toBytes(E),_.toBytes(b)),cmov:({c0:E,c1:b},{c0:v,c1:y},w)=>({c0:_.cmov(E,v,w),c1:_.cmov(b,y,w)}),fromBigTwelve:E=>({c0:_.fromBigSix(E.slice(0,6)),c1:_.fromBigSix(E.slice(6,12))}),frobeniusMap(E,b){const{c0:v,c1:y,c2:w}=_.frobeniusMap(E.c1,b),I=T[b%12];return{c0:_.frobeniusMap(E.c0,b),c1:_.create({c0:h.mul(v,I),c1:h.mul(y,I),c2:h.mul(w,I)})}},mulByFp2:({c0:E,c1:b},v)=>({c0:_.mulByFp2(E,v),c1:_.mulByFp2(b,v)}),conjugate:({c0:E,c1:b})=>({c0:E,c1:_.neg(b)}),mul014:({c0:E,c1:b},v,y,w)=>{let I=_.mul01(E,v,y),O=_.mul1(b,w);return{c0:_.add(_.mulByNonresidue(O),I),c1:_.sub(_.sub(_.mul01(_.add(b,E),v,h.add(y,w)),I),O)}},mul034:({c0:E,c1:b},v,y,w)=>{const I=_.create({c0:h.mul(E.c0,v),c1:h.mul(E.c1,v),c2:h.mul(E.c2,v)}),O=_.mul01(b,y,w),S=_.mul01(_.add(E,b),h.add(v,y),w);return{c0:_.add(_.mulByNonresidue(O),I),c1:_.sub(S,_.add(I,O))}},_cyclotomicSquare:t.Fp12cyclotomicSquare,_cyclotomicExp:t.Fp12cyclotomicExp,finalExponentiate:t.Fp12finalExponentiate};return{Fp:n,Fp2:h,Fp6:_,Fp4Square:j,Fp12:M}}const at=BigInt(0),Bo=BigInt(1),Ue=BigInt(2),Ao=BigInt(3),Ji=BigInt(4),nr=BigInt("0xd201000000010000"),W8=Gi(nr),{Fp:X,Fp2:J,Fp6:Xc,Fp4Square:Jc,Fp12:re}=G8({ORDER:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),FP2_NONRESIDUE:[Bo,Bo],Fp2mulByB:({c0:t,c1:e})=>{const n=X.mul(t,Ji),r=X.mul(e,Ji);return{c0:X.sub(n,r),c1:X.add(n,r)}},Fp12cyclotomicSquare:({c0:t,c1:e})=>{const{c0:n,c1:r,c2:i}=t,{c0:s,c1:o,c2:a}=e,{first:c,second:u}=Jc(n,o),{first:l,second:f}=Jc(s,i),{first:d,second:h}=Jc(r,a),p=J.mulByNonresidue(h);return{c0:Xc.create({c0:J.add(J.mul(J.sub(c,n),Ue),c),c1:J.add(J.mul(J.sub(l,r),Ue),l),c2:J.add(J.mul(J.sub(d,i),Ue),d)}),c1:Xc.create({c0:J.add(J.mul(J.add(p,s),Ue),p),c1:J.add(J.mul(J.add(u,o),Ue),u),c2:J.add(J.mul(J.add(f,a),Ue),f)})}},Fp12cyclotomicExp(t,e){let n=re.ONE;for(let r=W8-1;r>=0;r--)n=re._cyclotomicSquare(n),x3(e,r)&&(n=re.mul(n,t));return n},Fp12finalExponentiate:t=>{const e=nr,n=re.div(re.frobeniusMap(t,6),t),r=re.mul(re.frobeniusMap(n,2),n),i=re.conjugate(re._cyclotomicExp(r,e)),s=re.mul(re.conjugate(re._cyclotomicSquare(r)),i),o=re.conjugate(re._cyclotomicExp(s,e)),a=re.conjugate(re._cyclotomicExp(o,e)),c=re.mul(re.conjugate(re._cyclotomicExp(a,e)),re._cyclotomicSquare(i)),u=re.conjugate(re._cyclotomicExp(c,e)),l=re.frobeniusMap(re.mul(i,a),2),f=re.frobeniusMap(re.mul(o,r),3),d=re.frobeniusMap(re.mul(c,re.conjugate(r)),1),h=re.mul(re.mul(u,re.conjugate(s)),r);return re.mul(re.mul(re.mul(l,f),d),h)}}),Zd=Qn(BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")),Z8=jd(J,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(t=>t.map(e=>J.fromBigTuple(e.map(BigInt))))),Y8=jd(X,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),X8=qd(J,{A:J.create({c0:X.create(at),c1:X.create(BigInt(240))}),B:J.create({c0:X.create(BigInt(1012)),c1:X.create(BigInt(1012))}),Z:J.create({c0:X.create(BigInt(-2)),c1:X.create(BigInt(-1))})}),J8=qd(X,{A:X.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:X.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:X.create(BigInt(11))}),{G2psi:Yd,G2psi2:Q8}=H8(X,J,J.div(J.ONE,J.NONRESIDUE)),Qc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:X.ORDER,m:2,k:128,expand:"xmd",hash:hi}),Do=Qi(X.toBytes(at),{infinity:!0,compressed:!0});function $o(t){t=t.slice();const e=t[0]&224,n=!!(e>>7&1),r=!!(e>>6&1),i=!!(e>>5&1);return t[0]&=31,{compressed:n,infinity:r,sort:i,value:t}}function Qi(t,e){if(t[0]&224)throw new Error("setMask: non-empty mask");return e.compressed&&(t[0]|=128),e.infinity&&(t[0]|=64),e.sort&&(t[0]|=32),t}function Xd(t){t.assertValidity();const e=t.equals(Wt.G1.ProjectivePoint.ZERO),{x:n,y:r}=t.toAffine();if(e)return Do.slice();const i=X.ORDER,s=!!(r*Ue/i);return Qi($e(n,X.BYTES),{compressed:!0,sort:s})}function Jd(t){t.assertValidity();const e=X.BYTES;if(t.equals(Wt.G2.ProjectivePoint.ZERO))return Ie(Do,$e(at,e));const{x:n,y:r}=t.toAffine(),{re:i,im:s}=J.reim(n),{re:o,im:a}=J.reim(r),u=!!((a>at?a*Ue:o*Ue)/X.ORDER&Bo),l=i;return Ie(Qi($e(s,e),{sort:u,compressed:!0}),$e(l,e))}const Wt=V8({fields:{Fp:X,Fp2:J,Fp6:Xc,Fp12:re,Fr:Zd},G1:{Fp:X,h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"),a:X.ZERO,b:Ji,htfDefaults:{...Qc,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(t,e)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new t(X.mul(e.px,n),e.py,e.pz);return e.multiplyUnsafe(nr).negate().multiplyUnsafe(nr).equals(r)},clearCofactor:(t,e)=>e.multiplyUnsafe(nr).add(e),mapToCurve:t=>{const{x:e,y:n}=J8(X.create(t[0]));return Y8(e,n)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=$o(t);if(i.length===48&&e){const s=X.ORDER,o=it(i),a=X.create(o&X.MASK);if(n){if(a!==at)throw new Error("G1: non-empty compressed point at infinity");return{x:at,y:at}}const c=X.add(X.pow(a,Ao),X.create(Wt.params.G1b));let u=X.sqrt(c);if(!u)throw new Error("invalid compressed G1 point");return u*Ue/s!==BigInt(r)&&(u=X.neg(u)),{x:X.create(a),y:X.create(u)}}else if(i.length===96&&!e){const s=it(i.subarray(0,X.BYTES)),o=it(i.subarray(X.BYTES));if(n){if(s!==at||o!==at)throw new Error("G1: non-empty point at infinity");return Wt.G1.ProjectivePoint.ZERO.toAffine()}return{x:X.create(s),y:X.create(o)}}else throw new Error("invalid point G1, expected 48/96 bytes")},toBytes:(t,e,n)=>{const r=e.equals(t.ZERO),{x:i,y:s}=e.toAffine();if(n){if(r)return Do.slice();const o=X.ORDER,a=!!(s*Ue/o);return Qi($e(i,X.BYTES),{compressed:!0,sort:a})}else return r?Ie(new Uint8Array([64]),new Uint8Array(2*X.BYTES-1)):Ie($e(i,X.BYTES),$e(s,X.BYTES))},ShortSignature:{fromHex(t){const{infinity:e,sort:n,value:r}=$o(Ze("signatureHex",t,48)),i=X.ORDER,s=it(r);if(e)return Wt.G1.ProjectivePoint.ZERO;const o=X.create(s&X.MASK),a=X.add(X.pow(o,Ao),X.create(Wt.params.G1b));let c=X.sqrt(a);if(!c)throw new Error("invalid compressed G1 point");const u=BigInt(n);c*Ue/i!==u&&(c=X.neg(c));const l=Wt.G1.ProjectivePoint.fromAffine({x:o,y:c});return l.assertValidity(),l},toRawBytes(t){return Xd(t)},toHex(t){return Rr(Xd(t))}}},G2:{Fp:J,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),Gx:J.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:J.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")]),a:J.ZERO,b:J.fromBigTuple([Ji,Ji]),hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Qc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:t=>{const{x:e,y:n}=X8(J.fromBigTuple(t));return Z8(e,n)},isTorsionFree:(t,e)=>e.multiplyUnsafe(nr).negate().equals(Yd(t,e)),clearCofactor:(t,e)=>{const n=nr;let r=e.multiplyUnsafe(n).negate(),i=Yd(t,e),s=e.double();return s=Q8(t,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(e)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=$o(t);if(!e&&!n&&r||!e&&n&&r||r&&n&&e)throw new Error("invalid encoding flag: "+(t[0]&224));const s=X.BYTES,o=(a,c,u)=>it(a.slice(c,u));if(i.length===96&&e){const a=Wt.params.G2b,c=X.ORDER;if(n){if(i.reduce((g,m)=>g!==0?m+1:m,0)>0)throw new Error("invalid compressed G2 point");return{x:J.ZERO,y:J.ZERO}}const u=o(i,0,s),l=o(i,s,2*s),f=J.create({c0:X.create(l),c1:X.create(u)}),d=J.add(J.pow(f,Ao),a);let h=J.sqrt(d);const p=h.c1===at?h.c0*Ue/c:h.c1*Ue/c?Bo:at;return h=r&&p>0?h:J.neg(h),{x:f,y:h}}else if(i.length===192&&!e){if(n){if(i.reduce((f,d)=>f!==0?d+1:d,0)>0)throw new Error("invalid uncompressed G2 point");return{x:J.ZERO,y:J.ZERO}}const a=o(i,0,s),c=o(i,s,2*s),u=o(i,2*s,3*s),l=o(i,3*s,4*s);return{x:J.fromBigTuple([c,a]),y:J.fromBigTuple([l,u])}}else throw new Error("invalid point G2, expected 96/192 bytes")},toBytes:(t,e,n)=>{const{BYTES:r,ORDER:i}=X,s=e.equals(t.ZERO),{x:o,y:a}=e.toAffine();if(n){if(s)return Ie(Do,$e(at,r));const c=!!(a.c1===at?a.c0*Ue/i:a.c1*Ue/i);return Ie(Qi($e(o.c1,r),{compressed:!0,sort:c}),$e(o.c0,r))}else{if(s)return Ie(new Uint8Array([64]),new Uint8Array(4*r-1));const{re:c,im:u}=J.reim(o),{re:l,im:f}=J.reim(a);return Ie($e(u,r),$e(c,r),$e(f,r),$e(l,r))}},Signature:{fromHex(t){const{infinity:e,sort:n,value:r}=$o(Ze("signatureHex",t)),i=X.ORDER,s=r.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, must be 96 or 192");const o=it(r.slice(0,s)),a=it(r.slice(s));if(e)return Wt.G2.ProjectivePoint.ZERO;const c=X.create(o&X.MASK),u=X.create(a),l=J.create({c0:u,c1:c}),f=J.add(J.pow(l,Ao),Wt.params.G2b);let d=J.sqrt(f);if(!d)throw new Error("Failed to find a square root");const{re:h,im:p}=J.reim(d),g=BigInt(n),m=p>at&&p*Ue/i!==g,B=p===at&&h*Ue/i!==g;(m||B)&&(d=J.neg(d));const $=Wt.G2.ProjectivePoint.fromAffine({x:l,y:d});return $.assertValidity(),$},toRawBytes(t){return Jd(t)},toHex(t){return Rr(Jd(t))}}},params:{ateLoopSize:nr,r:Zd.ORDER,xNegative:!0,twistType:"multiplicative"},htfDefaults:Qc,hash:hi,randomBytes:ho});BigInt(0),BigInt(1),BigInt(2),BigInt(8),BigInt(0),BigInt(1),BigInt(2),BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),BigInt(0),BigInt(1),BigInt(2),BigInt(3),BigInt(5),BigInt(8);const eu=BigInt(0),tu=BigInt(1);function To(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Fr(t,e,n=""){const r=co(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 Po(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Qd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?eu:BigInt("0x"+t)}function Ro(t){return Qd(ui(t))}function ep(t){return wn(t),Qd(ui(Uint8Array.from(t).reverse()))}function nu(t,e){return uo(t.toString(16).padStart(e*2,"0"))}function tp(t,e){return nu(t,e).reverse()}function yt(t,e,n){let r;if(typeof e=="string")try{r=uo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(co(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 ru=t=>typeof t=="bigint"&&eu<=t;function ex(t,e,n){return ru(t)&&ru(e)&&ru(n)&&e<=t&&t<n}function tx(t,e,n,r){if(!ex(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function np(t){let e;for(e=0;t>eu;t>>=tu,e+=1);return e}const es=t=>(tu<<BigInt(t))-tu;function nx(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 p=[];for(;h<e;){s=u();const g=s.slice();p.push(g),h+=s.length}return vn(...p)};return(h,p)=>{c(),l(h);let g;for(;!(g=p(f()));)l();return c(),g}}function iu(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 rp(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 bt=BigInt(0),ct=BigInt(1),Lr=BigInt(2),ip=BigInt(3),sp=BigInt(4),op=BigInt(5),rx=BigInt(7),ap=BigInt(8),ix=BigInt(9),cp=BigInt(16);function Zt(t,e){const n=t%e;return n>=bt?n:e+n}function Ut(t,e,n){let r=t;for(;e-- >bt;)r*=r,r%=n;return r}function up(t,e){if(t===bt)throw new Error("invert: expected non-zero number");if(e<=bt)throw new Error("invert: expected positive modulus, got "+e);let n=Zt(t,e),r=e,i=bt,s=ct;for(;n!==bt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==ct)throw new Error("invert: does not exist");return Zt(i,e)}function su(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function lp(t,e){const n=(t.ORDER+ct)/sp,r=t.pow(e,n);return su(t,r,e),r}function sx(t,e){const n=(t.ORDER-op)/ap,r=t.mul(e,Lr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Lr),i),a=t.mul(s,t.sub(o,t.ONE));return su(t,a,e),a}function ox(t){const e=ts(t),n=fp(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+rx)/cp;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const g=a.eql(a.sqr(l),c),m=a.cmov(u,l,g);return su(a,m,c),m}}function fp(t){if(t<ip)throw new Error("sqrt is not defined for small field");let e=t-ct,n=0;for(;e%Lr===bt;)e/=Lr,n++;let r=Lr;const i=ts(t);for(;dp(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lp;let s=i.pow(r,e);const o=(e+ct)/Lr;return function(c,u){if(c.is0(u))return u;if(dp(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const m=ct<<BigInt(l-p-1),B=c.pow(f,m);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function ax(t){return t%sp===ip?lp:t%ap===op?sx:t%cp===ix?ox(t):fp(t)}const cx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ux(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=cx.reduce((r,i)=>(r[i]="function",r),e);return iu(t,n),t}function lx(t,e,n){if(n<bt)throw new Error("invalid exponent, negatives unsupported");if(n===bt)return t.ONE;if(n===ct)return e;let r=t.ONE,i=e;for(;n>bt;)n&ct&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ct;return r}function hp(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 dp(t,e){const n=(t.ORDER-ct)/Lr,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 pp(t,e){e!==void 0&&ai(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function ts(t,e,n=!1,r={}){if(t<=bt)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 d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=pp(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:es(c),ZERO:bt,ONE:ct,allowedLengths:a,create:d=>Zt(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return bt<=d&&d<t},is0:d=>d===bt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ct)===ct,neg:d=>Zt(-d,t),eql:(d,h)=>d===h,sqr:d=>Zt(d*d,t),add:(d,h)=>Zt(d+h,t),sub:(d,h)=>Zt(d-h,t),mul:(d,h)=>Zt(d*h,t),pow:(d,h)=>lx(f,d,h),div:(d,h)=>Zt(d*up(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>up(d,t),sqrt:s||(d=>(l||(l=ax(t)),l(f,d))),toBytes:d=>n?tp(d,u):nu(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const g=new Uint8Array(u);g.set(d,n?0:g.length-d.length),d=g}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?ep(d):Ro(d);if(o&&(p=Zt(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>hp(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function gp(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 yp(t){const e=gp(t);return e+Math.ceil(e/2)}function fx(t,e,n=!1){const r=t.length,i=gp(e),s=yp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ep(t):Ro(t),a=Zt(o,e-ct)+ct;return n?tp(a,i):nu(a,i)}const yi=BigInt(0),kr=BigInt(1);function No(t,e){const n=e.negate();return t?n:e}function ou(t,e){const n=hp(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function bp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function au(t,e){bp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=es(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function wp(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+=kr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function hx(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 dx(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 cu=new WeakMap,mp=new WeakMap;function uu(t){return mp.get(t)||1}function vp(t){if(t!==yi)throw new Error("invalid wNAF")}class px{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>yi;)n&kr&&(r=r.add(i)),i=i.double(),n>>=kr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=au(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=au(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=wp(r,a,o);r=c,l?s=s.add(No(d,n[h])):i=i.add(No(f,n[u]))}return vp(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=au(e,this.bits);for(let o=0;o<s.windows&&r!==yi;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=wp(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return vp(r),i}getPrecomputes(e,n,r){let i=cu.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),cu.set(n,i))),i}cached(e,n,r){const i=uu(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=uu(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){bp(n,this.bits),mp.set(e,n),cu.delete(e)}hasCache(e){return uu(e)!==1}}function gx(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>yi||r>yi;)n&kr&&(s=s.add(i)),r&kr&&(o=o.add(i)),i=i.double(),n>>=kr,r>>=kr;return{p1:s,p2:o}}function yx(t,e,n,r){hx(n,t),dx(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=np(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=es(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Ep(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ux(e),e}else return ts(t,{isLE:n})}function bx(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>yi))throw new Error(`CURVE.${c} must be positive bigint`)}const i=Ep(e.p,n.Fp,r),s=Ep(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 xp=(t,e)=>(t+(t>=0?e:-e)/_p)/e;function wx(t,e,n){const[[r,i],[s,o]]=e,a=xp(o*t,n),c=xp(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<$n,d=l<$n;f&&(u=-u),d&&(l=-l);const h=es(Math.ceil(np(n)/2))+bi;if(u<$n||u>=h||l<$n||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function lu(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function fu(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return To(n.lowS,"lowS"),To(n.prehash,"prehash"),n.format!==void 0&&lu(n.format),n}class mx extends Error{constructor(e=""){super(e)}}const Dn={Err:mx,_tlv:{encode:(t,e)=>{const{Err:n}=Dn;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=Po(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Po(i.length/2|128):"";return Po(t)+s+i+e},decode(t,e){const{Err:n}=Dn;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}=Dn;if(t<$n)throw new e("integer: negative integers are not allowed");let n=Po(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}=Dn;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 Ro(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Dn,i=yt("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}=Dn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},$n=BigInt(0),bi=BigInt(1),_p=BigInt(2),Co=BigInt(3),vx=BigInt(4);function wi(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=yt("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 Ex(t,e={}){const n=bx("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;iu(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=Sp(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,b,v){const{x:y,y:w}=b.toAffine(),I=r.toBytes(y);if(To(v,"isCompressed"),v){l();const O=!r.isOdd(w);return vn(Ip(O),I)}else return vn(Uint8Array.of(4),I,r.toBytes(w))}function d(E){Fr(E,void 0,"Point");const{publicKey:b,publicKeyUncompressed:v}=u,y=E.length,w=E[0],I=E.subarray(1);if(y===b&&(w===2||w===3)){const O=r.fromBytes(I);if(!r.isValid(O))throw new Error("bad point: is not on curve, wrong x");const S=g(O);let A;try{A=r.sqrt(S)}catch(F){const k=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+k)}l();const R=r.isOdd(A);return(w&1)===1!==R&&(A=r.neg(A)),{x:O,y:A}}else if(y===v&&w===4){const O=r.BYTES,S=r.fromBytes(I.subarray(0,O)),A=r.fromBytes(I.subarray(O,O*2));if(!m(S,A))throw new Error("bad point: is not on curve");return{x:S,y:A}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${v}`)}const h=e.toBytes||f,p=e.fromBytes||d;function g(E){const b=r.sqr(E),v=r.mul(b,E);return r.add(r.add(v,r.mul(E,s.a)),s.b)}function m(E,b){const v=r.sqr(b),y=g(E);return r.eql(v,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,Co),vx),$=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,$)))throw new Error("bad curve params: a or b");function x(E,b,v=!1){if(!r.isValid(b)||v&&r.is0(b))throw new Error(`bad point coordinate ${E}`);return b}function _(E){if(!(E instanceof D))throw new Error("ProjectivePoint expected")}function T(E){if(!c||!c.basises)throw new Error("no endo");return wx(E,c.basises,i.ORDER)}const P=rp((E,b)=>{const{X:v,Y:y,Z:w}=E;if(r.eql(w,r.ONE))return{x:v,y};const I=E.is0();b==null&&(b=I?r.ONE:r.inv(w));const O=r.mul(v,b),S=r.mul(y,b),A=r.mul(w,b);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:O,y:S}}),C=rp(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:v}=E.toAffine();if(!r.isValid(b)||!r.isValid(v))throw new Error("bad point: x or y not field elements");if(!m(b,v))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(E,b,v,y,w){return v=new D(r.mul(v.X,E),v.Y,v.Z),b=No(y,b),v=No(w,v),b.add(v)}class D{constructor(b,v,y){this.X=x("x",b),this.Y=x("y",v,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:v,y}=b||{};if(!b||!r.isValid(v)||!r.isValid(y))throw new Error("invalid affine point");if(b instanceof D)throw new Error("projective point not allowed");return r.is0(v)&&r.is0(y)?D.ZERO:new D(v,y,r.ONE)}static fromBytes(b){const v=D.fromAffine(p(Fr(b,void 0,"point")));return v.assertValidity(),v}static fromHex(b){return D.fromBytes(yt("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return M.createCache(this,b),v||this.multiply(Co),this}assertValidity(){C(this)}hasEvenY(){const{y:b}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(b)}equals(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b,A=r.eql(r.mul(v,S),r.mul(I,w)),R=r.eql(r.mul(y,S),r.mul(O,w));return A&&R}negate(){return new D(this.X,r.neg(this.Y),this.Z)}double(){const{a:b,b:v}=s,y=r.mul(v,Co),{X:w,Y:I,Z:O}=this;let S=r.ZERO,A=r.ZERO,R=r.ZERO,L=r.mul(w,w),F=r.mul(I,I),k=r.mul(O,O),N=r.mul(w,I);return N=r.add(N,N),R=r.mul(w,O),R=r.add(R,R),S=r.mul(b,R),A=r.mul(y,k),A=r.add(S,A),S=r.sub(F,A),A=r.add(F,A),A=r.mul(S,A),S=r.mul(N,S),R=r.mul(y,R),k=r.mul(b,k),N=r.sub(L,k),N=r.mul(b,N),N=r.add(N,R),R=r.add(L,L),L=r.add(R,L),L=r.add(L,k),L=r.mul(L,N),A=r.add(A,L),k=r.mul(I,O),k=r.add(k,k),L=r.mul(k,N),S=r.sub(S,L),R=r.mul(k,F),R=r.add(R,R),R=r.add(R,R),new D(S,A,R)}add(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b;let A=r.ZERO,R=r.ZERO,L=r.ZERO;const F=s.a,k=r.mul(s.b,Co);let N=r.mul(v,I),q=r.mul(y,O),z=r.mul(w,S),W=r.add(v,y),K=r.add(I,O);W=r.mul(W,K),K=r.add(N,q),W=r.sub(W,K),K=r.add(v,w);let Z=r.add(I,S);return K=r.mul(K,Z),Z=r.add(N,z),K=r.sub(K,Z),Z=r.add(y,w),A=r.add(O,S),Z=r.mul(Z,A),A=r.add(q,z),Z=r.sub(Z,A),L=r.mul(F,K),A=r.mul(k,z),L=r.add(A,L),A=r.sub(q,L),L=r.add(q,L),R=r.mul(A,L),q=r.add(N,N),q=r.add(q,N),z=r.mul(F,z),K=r.mul(k,K),q=r.add(q,z),z=r.sub(N,z),z=r.mul(F,z),K=r.add(K,z),N=r.mul(q,K),R=r.add(R,N),N=r.mul(Z,K),A=r.mul(W,A),A=r.sub(A,N),N=r.mul(W,q),L=r.mul(Z,L),L=r.add(L,N),new D(A,R,L)}subtract(b){return this.add(b.negate())}is0(){return this.equals(D.ZERO)}multiply(b){const{endo:v}=e;if(!i.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,w;const I=O=>M.cached(this,O,S=>ou(D,S));if(v){const{k1neg:O,k1:S,k2neg:A,k2:R}=T(b),{p:L,f:F}=I(S),{p:k,f:N}=I(R);w=F.add(N),y=U(v.beta,L,k,O,A)}else{const{p:O,f:S}=I(b);y=O,w=S}return ou(D,[y,w])[0]}multiplyUnsafe(b){const{endo:v}=e,y=this;if(!i.isValid(b))throw new Error("invalid scalar: out of range");if(b===$n||y.is0())return D.ZERO;if(b===bi)return y;if(M.hasCache(this))return this.multiply(b);if(v){const{k1neg:w,k1:I,k2neg:O,k2:S}=T(b),{p1:A,p2:R}=gx(D,y,I,S);return U(v.beta,A,R,w,O)}else return M.unsafe(y,b)}multiplyAndAddUnsafe(b,v,y){const w=this.multiplyUnsafe(v).add(b.multiplyUnsafe(y));return w.is0()?void 0:w}toAffine(b){return P(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return o===bi?!0:b?b(D,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return o===bi?this:b?b(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(b=!0){return To(b,"isCompressed"),this.assertValidity(),h(D,this,b)}toHex(b=!0){return ui(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return ou(D,b)}static msm(b,v){return yx(D,i,b,v)}static fromPrivateKey(b){return D.BASE.multiply(wi(i,b))}}D.BASE=new D(s.Gx,s.Gy,r.ONE),D.ZERO=new D(r.ZERO,r.ONE,r.ZERO),D.Fp=r,D.Fn=i;const j=i.BITS,M=new px(D,e.endo?Math.ceil(j/2):j);return D.BASE.precompute(8),D}function Ip(t){return Uint8Array.of(t?2:3)}function Sp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xx(t,e={}){const{Fn:n}=t,r=e.randomBytes||ho,i=Object.assign(Sp(t.Fp,n),{seed:yp(n.ORDER)});function s(h){try{return!!wi(n,h)}catch{return!1}}function o(h,p){const{publicKey:g,publicKeyUncompressed:m}=i;try{const B=h.length;return p===!0&&B!==g||p===!1&&B!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return fx(Fr(h,i.seed,"seed"),n.ORDER)}function c(h,p=!0){return t.BASE.multiply(wi(n,h)).toBytes(p)}function u(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:m}=i;if(n.allowedLengths||p===g)return;const B=yt("key",h).length;return B===g||B===m}function f(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const m=wi(n,h);return t.fromHex(p).multiply(m).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:h=>wi(n,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:i})}function _x(t,e,n={}){jh(e),iu(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||ho,i=n.hmac||((v,...y)=>Fc(e,v,vn(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=xx(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function m(v){const y=a>>bi;return v>y}function B(v,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return y}function $(v,y){lu(y);const w=h.signature,I=y==="compact"?w:y==="recovered"?w+1:void 0;return Fr(v,I,`${y} signature`)}class x{constructor(y,w,I){this.r=B("r",y),this.s=B("s",w),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(y,w=g){$(y,w);let I;if(w==="der"){const{r:R,s:L}=Dn.toSig(Fr(y));return new x(R,L)}w==="recovered"&&(I=y[0],w="compact",y=y.subarray(1));const O=o.BYTES,S=y.subarray(0,O),A=y.subarray(O,O*2);return new x(o.fromBytes(S),o.fromBytes(A),I)}static fromHex(y,w){return this.fromBytes(uo(y),w)}addRecoveryBit(y){return new x(this.r,this.s,y)}recoverPublicKey(y){const w=s.ORDER,{r:I,s:O,recovery:S}=this;if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");if(a*_p<w&&S>1)throw new Error("recovery id is ambiguous for h>1 curve");const R=S===2||S===3?I+a:I;if(!s.isValid(R))throw new Error("recovery id 2 or 3 invalid");const L=s.toBytes(R),F=t.fromBytes(vn(Ip((S&1)===0),L)),k=o.inv(R),N=T(yt("msgHash",y)),q=o.create(-N*k),z=o.create(O*k),W=t.BASE.multiplyUnsafe(q).add(F.multiplyUnsafe(z));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return m(this.s)}toBytes(y=g){if(lu(y),y==="der")return uo(Dn.hexFromSig(this));const w=o.toBytes(this.r),I=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return vn(Uint8Array.of(this.recovery),w,I)}return vn(w,I)}toHex(y){return ui(this.toBytes(y))}assertValidity(){}static fromCompact(y){return x.fromBytes(yt("sig",y),"compact")}static fromDER(y){return x.fromBytes(yt("sig",y),"der")}normalizeS(){return this.hasHighS()?new x(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return ui(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return ui(this.toBytes("compact"))}}const _=n.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const w=Ro(y),I=y.length*8-c;return I>0?w>>BigInt(I):w},T=n.bits2int_modN||function(y){return o.create(_(y))},P=es(c);function C(v){return tx("num < 2^"+c,v,$n,P),o.toBytes(v)}function U(v,y){return Fr(v,void 0,"message"),y?Fr(e(v),void 0,"prehashed message"):v}function D(v,y,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:I,prehash:O,extraEntropy:S}=fu(w,p);v=U(v,O);const A=T(v),R=wi(o,y),L=[C(R),C(A)];if(S!=null&&S!==!1){const q=S===!0?r(h.secretKey):S;L.push(yt("extraEntropy",q))}const F=vn(...L),k=A;function N(q){const z=_(q);if(!o.isValidNot0(z))return;const W=o.inv(z),K=t.BASE.multiply(z).toAffine(),Z=o.create(K.x);if(Z===$n)return;const Q=o.create(W*o.create(k+Z*R));if(Q===$n)return;let ee=(K.x===Z?0:2)|Number(K.y&bi),ie=Q;return I&&m(Q)&&(ie=o.neg(Q),ee^=1),new x(Z,ie,ee)}return{seed:F,k2sig:N}}function j(v,y,w={}){v=yt("message",v);const{seed:I,k2sig:O}=D(v,y,w);return nx(e.outputLen,o.BYTES,i)(I,O)}function M(v){let y;const w=typeof v=="string"||co(v),I=!w&&v!==null&&typeof v=="object"&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!w&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)y=new x(v.r,v.s);else if(w){try{y=x.fromBytes(yt("sig",v),"der")}catch(O){if(!(O instanceof Dn.Err))throw O}if(!y)try{y=x.fromBytes(yt("sig",v),"compact")}catch{return!1}}return y||!1}function E(v,y,w,I={}){const{lowS:O,prehash:S,format:A}=fu(I,p);if(w=yt("publicKey",w),y=U(yt("message",y),S),"strict"in I)throw new Error("options.strict was renamed to lowS");const R=A===void 0?M(v):x.fromBytes(yt("sig",v),A);if(R===!1)return!1;try{const L=t.fromBytes(w);if(O&&R.hasHighS())return!1;const{r:F,s:k}=R,N=T(y),q=o.inv(k),z=o.create(N*q),W=o.create(F*q),K=t.BASE.multiplyUnsafe(z).add(L.multiplyUnsafe(W));return K.is0()?!1:o.create(K.x)===F}catch{return!1}}function b(v,y,w={}){const{prehash:I}=fu(w,p);return y=U(y,I),x.fromBytes(v,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:j,verify:E,recoverPublicKey:b,Signature:x,hash:e})}function Ix(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=ts(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 Sx(t){const{CURVE:e,curveOpts:n}=Ix(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 Ox(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,pp(n.Fn.ORDER,n.Fn.BITS))})}function Bx(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Sx(t),s=Ex(e,n),o=_x(s,r,i);return Ox(t,o)}function Ax(t,e){const n=r=>Bx({...t,hash:r});return{...n(e),create:n}}vc("HashToScalar-");const hu={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Dx={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Op=BigInt(2);function $x(t){const e=hu.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=Ut(l,n,e)*l%e,d=Ut(f,n,e)*l%e,h=Ut(d,Op,e)*u%e,p=Ut(h,i,e)*h%e,g=Ut(p,s,e)*p%e,m=Ut(g,a,e)*g%e,B=Ut(m,c,e)*m%e,$=Ut(B,a,e)*g%e,x=Ut($,n,e)*l%e,_=Ut(x,o,e)*p%e,T=Ut(_,r,e)*u%e,P=Ut(T,Op,e);if(!du.eql(du.sqr(P),t))throw new Error("Cannot find square root");return P}const du=ts(hu.p,{sqrt:$x});Ax({...hu,Fp:du,lowS:!0,endo:Dx},hi);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function mi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function pu(t,...e){if(!mi(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 Bp(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 gu(t){if(typeof t!="function")throw new Error("function expected");return!0}function rr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function vi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Uo(t){if(!Array.isArray(t))throw new Error("array expected")}function Fo(t,e){if(!Bp(!0,e))throw new Error(`${t}: array of strings expected`)}function yu(t,e){if(!Bp(!1,e))throw new Error(`${t}: array of numbers expected`)}function wt(...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 Bt(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Fo("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Uo(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=>(Uo(i),i.map(s=>{rr("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function At(t=""){return rr("join",t),{encode:e=>(Fo("join.decode",e),e.join(t)),decode:e=>(rr("join.decode",e),e.split(t))}}function Lo(t,e="="){return vi(t),rr("padding",e),{encode(n){for(Fo("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Fo("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 Ap(t){return gu(t),{encode:e=>e,decode:e=>t(e)}}function Dp(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(Uo(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(vi(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,d=f+l;if(!Number.isSafeInteger(d)||f/e!==a||d-l!==f)throw new Error("convertRadix: carry overflow");const h=d/n;a=d%n;const p=Math.floor(h);if(s[u]=p,!Number.isSafeInteger(p)||p*n+a!==d)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 $p=(t,e)=>e===0?t:$p(e,t%e),ko=(t,e)=>t+(e-$p(t,e)),qo=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function bu(t,e,n,r){if(Uo(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(ko(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${ko(e,n)}`);let i=0,s=0;const o=qo[e],a=qo[n]-1,c=[];for(const u of t){if(vi(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=qo[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 Tx(t){vi(t);const e=2**8;return{encode:n=>{if(!mi(n))throw new Error("radix.encode input should be Uint8Array");return Dp(Array.from(n),e,t)},decode:n=>(yu("radix.decode",n),Uint8Array.from(Dp(n,t,e)))}}function Ft(t,e=!1){if(vi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(ko(8,t)>32||ko(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!mi(n))throw new Error("radix2.encode input should be Uint8Array");return bu(Array.from(n),8,t,!e)},decode:n=>(yu("radix2.decode",n),Uint8Array.from(bu(n,t,8,e)))}}function Tp(t){return gu(t),function(...e){try{return t.apply(null,e)}catch{}}}function Px(t,e){return vi(t),gu(e),{encode(n){if(!mi(n))throw new Error("checksum.encode: input should be Uint8Array");const r=e(n).slice(0,t),i=new Uint8Array(n.length+t);return i.set(n),i.set(r,n.length),i},decode(n){if(!mi(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-t),i=n.slice(-t),s=e(r).slice(0,t);for(let o=0;o<t;o++)if(s[o]!==i[o])throw new Error("Invalid checksum");return r}}}const Rx=wt(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Lo(5),At("")),Pp=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Rp=(t,e)=>{rr("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"})},wu=t=>wt(Tx(58),Bt(t),At("")),Nx=wu("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Cx=t=>wt(Px(4,e=>t(t(e))),Nx),mu=wt(Bt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),At("")),Np=[996825010,642813549,513874426,1027748829,705979059];function ns(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Np.length;r++)(e>>r&1)===1&&(n^=Np[r]);return n}function Cp(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=ns(i)^o>>5}i=ns(i);for(let s=0;s<r;s++)i=ns(i)^t.charCodeAt(s)&31;for(let s of e)i=ns(i)^s;for(let s=0;s<6;s++)i=ns(i);return i^=n,mu.encode(bu([i%qo[30]],30,5,!1))}function Up(t){const e=t==="bech32"?1:734539939,n=Ft(5),r=n.decode,i=n.encode,s=Tp(r);function o(f,d,h=90){rr("bech32.encode prefix",f),mi(d)&&(d=Array.from(d)),yu("bech32.encode",d);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+d.length;if(h!==!1&&g>h)throw new TypeError(`Length ${g} exceeds limit ${h}`);const m=f.toLowerCase(),B=Cp(m,d,e);return`${m}1${mu.encode(d)}${B}`}function a(f,d=90){rr("bech32.decode input",f);const h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);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 m=p.slice(0,g),B=p.slice(g+1);if(B.length<6)throw new Error("Data must be at least 6 characters long");const $=mu.decode(B).slice(0,-6),x=Cp(m,$,e);if(!B.endsWith(x))throw new Error(`Invalid checksum in ${f}: expected "${x}"`);return{prefix:m,words:$}}const c=Tp(a);function u(f){const{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:r(h)}}function l(f,d){return o(f,i(d))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const Ux=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fx={encode(t){return pu(t),t.toHex()},decode(t){return rr("hex",t),Uint8Array.fromHex(t)}};Cx(hi),vc("Bitcoin seed");function Lx(t){return s8(kx(t))}function kx(t){const{payload:e,signature:n}=t,{r,s:i,yParity:s}=n,a=new U8.Signature(BigInt(r),BigInt(i)).addRecoveryBit(s).recoverPublicKey(Pc(e).substring(2));return Y3(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Fp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mo(t,...e){if(!Fp(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 jo(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 Lp(t,e){Mo(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function rs(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function vu(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function qx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function is(t){if(typeof t=="string")t=Mx(t);else if(Fp(t))t=kp(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function kp(t){return Uint8Array.from(t)}const Tn=16,Eu=new Uint8Array(16),an=rs(Eu),jx=225,zx=(t,e,n,r)=>{const i=r&1;return{s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^jx<<24&-(i&1)}},Lt=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255|0;function Vx(t){t.reverse();const e=t[15]&1;let n=0;for(let r=0;r<t.length;r++){const i=t[r];t[r]=i>>>1|n,n=(i&1)<<7}return t[0]^=-e&225,t}const Kx=t=>t>64*1024?8:t>1024?4:2;class qp{constructor(e,n){this.blockLen=Tn,this.outputLen=Tn,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,e=is(e),Mo(e,16);const r=qx(e);let i=r.getUint32(0,!1),s=r.getUint32(4,!1),o=r.getUint32(8,!1),a=r.getUint32(12,!1);const c=[];for(let p=0;p<128;p++)c.push({s0:Lt(i),s1:Lt(s),s2:Lt(o),s3:Lt(a)}),{s0:i,s1:s,s2:o,s3:a}=zx(i,s,o,a);const u=Kx(n||1024);if(![1,2,4,8].includes(u))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=u;const f=128/u,d=this.windowSize=2**u,h=[];for(let p=0;p<f;p++)for(let g=0;g<d;g++){let m=0,B=0,$=0,x=0;for(let _=0;_<u;_++){if(!(g>>>u-_-1&1))continue;const{s0:P,s1:C,s2:U,s3:D}=c[u*p+_];m^=P,B^=C,$^=U,x^=D}h.push({s0:m,s1:B,s2:$,s3:x})}this.t=h}_updateBlock(e,n,r,i){e^=this.s0,n^=this.s1,r^=this.s2,i^=this.s3;const{W:s,t:o,windowSize:a}=this;let c=0,u=0,l=0,f=0;const d=(1<<s)-1;let h=0;for(const p of[e,n,r,i])for(let g=0;g<4;g++){const m=p>>>8*g&255;for(let B=8/s-1;B>=0;B--){const $=m>>>s*B&d,{s0:x,s1:_,s2:T,s3:P}=o[h*a+$];c^=x,u^=_,l^=T,f^=P,h+=1}}this.s0=c,this.s1=u,this.s2=l,this.s3=f}update(e){jo(this),e=is(e),Mo(e);const n=rs(e),r=Math.floor(e.length/Tn),i=e.length%Tn;for(let s=0;s<r;s++)this._updateBlock(n[s*4+0],n[s*4+1],n[s*4+2],n[s*4+3]);return i&&(Eu.set(e.subarray(r*Tn)),this._updateBlock(an[0],an[1],an[2],an[3]),vu(an)),this}destroy(){const{t:e}=this;for(const n of e)n.s0=0,n.s1=0,n.s2=0,n.s3=0}digestInto(e){jo(this),Lp(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=rs(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e}digest(){const e=new Uint8Array(Tn);return this.digestInto(e),this.destroy(),e}}class Hx extends qp{constructor(e,n){e=is(e),Mo(e);const r=Vx(kp(e));super(r,n),vu(r)}update(e){e=is(e),jo(this);const n=rs(e),r=e.length%Tn,i=Math.floor(e.length/Tn);for(let s=0;s<i;s++)this._updateBlock(Lt(n[s*4+3]),Lt(n[s*4+2]),Lt(n[s*4+1]),Lt(n[s*4+0]));return r&&(Eu.set(e.subarray(i*Tn)),this._updateBlock(Lt(an[3]),Lt(an[2]),Lt(an[1]),Lt(an[0])),vu(an)),this}digestInto(e){jo(this),Lp(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=rs(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e.reverse()}}function Mp(t){const e=(r,i)=>t(i,r.length).update(is(r)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(r,i)=>t(r,i),e}Mp((t,e)=>new qp(t,e)),Mp((t,e)=>new Hx(t,e));const jp=Qn(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Gx=jp.create(BigInt("-3")),Wx=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");So({a:Gx,b:Wx,Fp:jp,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},hi);const zp=Qn(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),Zx=zp.create(BigInt("-3")),Yx=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");So({a:Zx,b:Yx,Fp:zp,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},v3);const Vp=Qn(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),Xx=Vp.create(BigInt("-3")),Jx=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");So({a:Xx,b:Jx,Fp:Vp,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},m3);var Qx={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,f,d){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new i(l,f||c,d),p=n?n+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],l,f;if(this._eventsCount===0)return u;for(f in l=this._events)e.call(l,f)&&u.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},a.prototype.listeners=function(u){var l=n?n+u:u,f=this._events[l];if(!f)return[];if(f.fn)return[f.fn];for(var d=0,h=f.length,p=new Array(h);d<h;d++)p[d]=f[d].fn;return p},a.prototype.listenerCount=function(u){var l=n?n+u:u,f=this._events[l];return f?f.fn?1:f.length:0},a.prototype.emit=function(u,l,f,d,h,p){var g=n?n+u:u;if(!this._events[g])return!1;var m=this._events[g],B=arguments.length,$,x;if(m.fn){switch(m.once&&this.removeListener(u,m.fn,void 0,!0),B){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,l),!0;case 3:return m.fn.call(m.context,l,f),!0;case 4:return m.fn.call(m.context,l,f,d),!0;case 5:return m.fn.call(m.context,l,f,d,h),!0;case 6:return m.fn.call(m.context,l,f,d,h,p),!0}for(x=1,$=new Array(B-1);x<B;x++)$[x-1]=arguments[x];m.fn.apply(m.context,$)}else{var _=m.length,T;for(x=0;x<_;x++)switch(m[x].once&&this.removeListener(u,m[x].fn,void 0,!0),B){case 1:m[x].fn.call(m[x].context);break;case 2:m[x].fn.call(m[x].context,l);break;case 3:m[x].fn.call(m[x].context,l,f);break;case 4:m[x].fn.call(m[x].context,l,f,d);break;default:if(!$)for(T=1,$=new Array(B-1);T<B;T++)$[T-1]=arguments[T];m[x].fn.apply(m[x].context,$)}}return!0},a.prototype.on=function(u,l,f){return s(this,u,l,f,!1)},a.prototype.once=function(u,l,f){return s(this,u,l,f,!0)},a.prototype.removeListener=function(u,l,f,d){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return o(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!d||p.once)&&(!f||p.context===f)&&o(this,h);else{for(var g=0,m=[],B=p.length;g<B;g++)(p[g].fn!==l||d&&!p[g].once||f&&p[g].context!==f)&&m.push(p[g]);m.length?this._events[h]=m.length===1?m[0]:m:o(this,h)}return this},a.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&o(this,l)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a})(Qx);function e6(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,d=0;const h=u.length;for(;d!==h&&u[d]===0;)d++,l++;const p=(h-d)*s+1>>>0,g=new Uint8Array(p);for(;d!==h;){let $=u[d],x=0;for(let _=p-1;($!==0||x<f)&&_!==-1;_--,x++)$+=256*g[_]>>>0,g[_]=$%n>>>0,$=$/n>>>0;if($!==0)throw new Error("Non-zero carry");f=x,d++}let m=p-f;for(;m!==p&&g[m]===0;)m++;let B=r.repeat(l);for(;m<p;++m)B+=t.charAt(g[m]);return B}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,d=0;for(;u[l]===r;)f++,l++;const h=(u.length-l)*i+1>>>0,p=new Uint8Array(h);for(;l<u.length;){const $=u.charCodeAt(l);if($>255)return;let x=e[$];if(x===255)return;let _=0;for(let T=h-1;(x!==0||_<d)&&T!==-1;T--,_++)x+=n*p[T]>>>0,p[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");d=_,l++}let g=h-d;for(;g!==h&&p[g]===0;)g++;const m=new Uint8Array(f+(h-g));let B=f;for(;g!==h;)m[B++]=p[g++];return m}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 t6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ss=e6(t6);function n6(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 r6(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 i6=new TextEncoder,s6=50;function o6(t,e,n){i6.encodeInto(t,e.subarray(n))}function a6(t,e,n){t.length>s6?o6(t,e,n):r6(t,e,n)}const c6=4096;function Kp(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>=c6&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const u6=new TextDecoder,l6=200;function f6(t,e,n){const r=t.subarray(e,e+n);return u6.decode(r)}function h6(t,e,n){return n>l6?f6(t,e,n):Kp(t,e,n)}class zo{constructor(e,n){this.type=e,this.data=n}}class Dt extends Error{constructor(e){super(e);const n=Object.create(Dt.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Dt.name})}}const os=4294967295;function d6(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Hp(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Gp(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function p6(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const g6=-1,y6=4294967296-1,b6=17179869184-1;function w6({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=b6)if(e===0&&t<=y6){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),Hp(r,4,t),n}}function m6(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 v6(t){if(t instanceof Date){const e=m6(t);return w6(e)}else return null}function E6(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=Gp(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Dt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function x6(t){const e=E6(t);return new Date(e.sec*1e3+e.nsec/1e6)}const _6={type:g6,encode:v6,decode:x6};class Vo{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(_6)}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 zo(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 zo(o,s)}}}return e instanceof zo?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new zo(n,e)}}Vo.defaultCodec=new Vo;function I6(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function xu(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):I6(t)?new Uint8Array(t):Uint8Array.from(t)}const S6=100,O6=2048;class _u{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Vo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??S6,this.initialBufferSize=e?.initialBufferSize??O6,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 _u({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=n6(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),a6(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=xu(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),d6(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Hp(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 B6(t,e){return new _u(e).encodeSharedRef(t)}function Iu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const A6=16,D6=16;class $6{constructor(e=A6,n=D6){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=Kp(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Su="array",as="map_key",Wp="map_value",T6=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Dt("The type of key must be string or number but "+typeof t)};class P6{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=Su,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=as,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===Su){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===as||e.type===Wp){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 cs=-1,Ou=new DataView(new ArrayBuffer(0)),R6=new Uint8Array(Ou.buffer);try{Ou.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 Zp=new RangeError("Insufficient data"),N6=new $6;class Bu{constructor(e){this.totalPos=0,this.pos=0,this.view=Ou,this.bytes=R6,this.headByte=cs,this.stack=new P6,this.entered=!1,this.extensionCodec=e?.extensionCodec??Vo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??os,this.maxBinLength=e?.maxBinLength??os,this.maxArrayLength=e?.maxArrayLength??os,this.maxMapLength=e?.maxMapLength??os,this.maxExtLength=e?.maxExtLength??os,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:N6,this.mapKeyConverter=e?.mapKeyConverter??T6}clone(){return new Bu({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=cs,this.stack.reset()}setBuffer(e){const n=xu(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===cs&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=xu(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 ${Iu(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 Dt(`Unrecognized type byte: ${Iu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Su)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===as){if(n==="__proto__")throw new Dt("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Wp;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=as;continue e}}return n}}readHeadByte(){return this.headByte===cs&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=cs}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 Dt(`Unrecognized array type byte: ${Iu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Dt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Dt(`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 Dt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Zp;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=h6(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===as:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Dt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Zp;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 Dt(`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=p6(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Gp(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 C6(t,e){return new Bu(e).decode(t)}function Au(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Yp(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Au(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function us(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Yp(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Au(n)}function U6(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var F6=U6,L6=F6;const Xp=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")},k6=t=>new TextEncoder().encode(t),q6=t=>new TextDecoder().decode(t);class M6{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 j6{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 Jp(this,e)}}class z6{constructor(e){this.decoders=e}or(e){return Jp(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 Jp=(t,e)=>new z6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class V6{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new M6(e,n,r),this.decoder=new j6(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ko=({name:t,prefix:e,encode:n,decode:r})=>new V6(t,e,n,r),ls=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=L6(n,e);return Ko({prefix:t,name:e,encode:r,decode:s=>Xp(i(s))})},K6=(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},H6=(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},qe=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ko({prefix:e,name:t,encode(i){return H6(i,r,n)},decode(i){return K6(i,r,n,t)}}),G6=Ko({prefix:"\0",name:"identity",encode:t=>q6(t),decode:t=>k6(t)});var W6=Object.freeze({__proto__:null,identity:G6});const Z6=qe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y6=Object.freeze({__proto__:null,base2:Z6});const X6=qe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var J6=Object.freeze({__proto__:null,base8:X6});const Q6=ls({prefix:"9",name:"base10",alphabet:"0123456789"});var e4=Object.freeze({__proto__:null,base10:Q6});const t4=qe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),n4=qe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var r4=Object.freeze({__proto__:null,base16:t4,base16upper:n4});const i4=qe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),s4=qe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o4=qe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a4=qe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c4=qe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),u4=qe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),l4=qe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),f4=qe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),h4=qe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var d4=Object.freeze({__proto__:null,base32:i4,base32upper:s4,base32pad:o4,base32padupper:a4,base32hex:c4,base32hexupper:u4,base32hexpad:l4,base32hexpadupper:f4,base32z:h4});const p4=ls({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),g4=ls({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y4=Object.freeze({__proto__:null,base36:p4,base36upper:g4});const b4=ls({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),w4=ls({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var m4=Object.freeze({__proto__:null,base58btc:b4,base58flickr:w4});const v4=qe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),E4=qe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),x4=qe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_4=qe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var I4=Object.freeze({__proto__:null,base64:v4,base64pad:E4,base64url:x4,base64urlpad:_4});const Qp=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}"),S4=Qp.reduce((t,e,n)=>(t[n]=e,t),[]),O4=Qp.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function B4(t){return t.reduce((e,n)=>(e+=S4[n],e),"")}function A4(t){const e=[];for(const n of t){const r=O4[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const D4=Ko({prefix:"\u{1F680}",name:"base256emoji",encode:B4,decode:A4});var $4=Object.freeze({__proto__:null,base256emoji:D4}),T4=t0,e0=128,P4=127,R4=~P4,N4=Math.pow(2,31);function t0(t,e,n){e=e||[],n=n||0;for(var r=n;t>=N4;)e[n++]=t&255|e0,t/=128;for(;t&R4;)e[n++]=t&255|e0,t>>>=7;return e[n]=t|0,t0.bytes=n-r+1,e}var C4=Du,U4=128,n0=127;function Du(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Du.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&n0)<<i:(o&n0)*Math.pow(2,i),i+=7}while(o>=U4);return Du.bytes=s-r,n}var F4=Math.pow(2,7),L4=Math.pow(2,14),k4=Math.pow(2,21),q4=Math.pow(2,28),M4=Math.pow(2,35),j4=Math.pow(2,42),z4=Math.pow(2,49),V4=Math.pow(2,56),K4=Math.pow(2,63),H4=function(t){return t<F4?1:t<L4?2:t<k4?3:t<q4?4:t<M4?5:t<j4?6:t<z4?7:t<V4?8:t<K4?9:10},G4={encode:T4,decode:C4,encodingLength:H4},r0=G4;const i0=(t,e,n=0)=>(r0.encode(t,e,n),e),s0=t=>r0.encodingLength(t),$u=(t,e)=>{const n=e.byteLength,r=s0(t),i=r+s0(n),s=new Uint8Array(i+n);return i0(t,s,0),i0(n,s,r),s.set(e,i),new W4(t,n,e,s)};class W4{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const o0=({name:t,code:e,encode:n})=>new Z4(t,e,n);class Z4{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?$u(this.code,n):n.then(r=>$u(this.code,r))}else throw Error("Unknown type, must be binary type")}}const a0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Y4=o0({name:"sha2-256",code:18,encode:a0("SHA-256")}),X4=o0({name:"sha2-512",code:19,encode:a0("SHA-512")});var J4=Object.freeze({__proto__:null,sha256:Y4,sha512:X4});const c0=0,Q4="identity",u0=Xp;var e_=Object.freeze({__proto__:null,identity:{code:c0,name:Q4,encode:u0,digest:t=>$u(c0,u0(t))}});new TextEncoder,new TextDecoder;const l0={...W6,...Y6,...J6,...e4,...r4,...d4,...y4,...m4,...I4,...$4};({...J4,...e_});function f0(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const h0=f0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Tu=f0("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=Yp(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),d0={utf8:h0,"utf-8":h0,hex:l0.base16,latin1:Tu,ascii:Tu,binary:Tu,...l0};function kt(t,e="utf8"){const n=d0[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Au(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function mt(t,e="utf8"){const n=d0[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 t_={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"}},n_="Input must be an string, Buffer or Uint8Array";function r_(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(n_);return e}function i_(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Ho(t){return(4294967296+t).toString(16).substring(1)}function s_(t,e,n){let r=`
|
|
14
|
+
***************************************************************************** */var Ra=function(t,e){return Ra=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])},Ra(t,e)};function rb(t,e){Ra(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var Na=function(){return Na=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},Na.apply(this,arguments)};function ib(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 sb(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 ob(t,e){return function(n,r){e(n,r,t)}}function ab(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function cb(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 ub(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 lb(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function fb(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function Ca(t){var e=typeof Symbol=="function"&&Symbol.iterator,n=e&&t[e],r=0;if(n)return n.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function lf(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 hb(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(lf(arguments[e]));return t}function db(){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 ki(t){return this instanceof ki?(this.v=t,this):new ki(t)}function pb(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(d){r[d]&&(i[d]=function(h){return new Promise(function(p,g){s.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof ki?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function gb(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:ki(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function yb(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],n;return e?e.call(t):(t=typeof Ca=="function"?Ca(t):t[Symbol.iterator](),n={},r("next"),r("throw"),r("return"),n[Symbol.asyncIterator]=function(){return this},n);function r(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 bb(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function wb(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 mb(t){return t&&t.__esModule?t:{default:t}}function vb(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function Eb(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 xb=Object.freeze({__proto__:null,__extends:rb,get __assign(){return Na},__rest:ib,__decorate:sb,__param:ob,__metadata:ab,__awaiter:cb,__generator:ub,__createBinding:lb,__exportStar:fb,__values:Ca,__read:lf,__spread:hb,__spreadArrays:db,__await:ki,__asyncGenerator:pb,__asyncDelegator:gb,__asyncValues:yb,__makeTemplateObject:bb,__importStar:wb,__importDefault:mb,__classPrivateFieldGet:vb,__classPrivateFieldSet:Eb}),Ks=Gl(xb),Ua={},Li={},ff;function _b(){if(ff)return Li;ff=1,Object.defineProperty(Li,"__esModule",{value:!0}),Li.delay=void 0;function t(e){return new Promise(n=>{setTimeout(()=>{n(!0)},e)})}return Li.delay=t,Li}var Or={},Fa={},Br={},hf;function Ib(){return hf||(hf=1,Object.defineProperty(Br,"__esModule",{value:!0}),Br.ONE_THOUSAND=Br.ONE_HUNDRED=void 0,Br.ONE_HUNDRED=100,Br.ONE_THOUSAND=1e3),Br}var ka={},df;function Sb(){return df||(df=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}(ka)),ka}var pf;function gf(){return pf||(pf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ks;e.__exportStar(Ib(),t),e.__exportStar(Sb(),t)}(Fa)),Fa}var yf;function Ob(){if(yf)return Or;yf=1,Object.defineProperty(Or,"__esModule",{value:!0}),Or.fromMiliseconds=Or.toMiliseconds=void 0;const t=gf();function e(r){return r*t.ONE_THOUSAND}Or.toMiliseconds=e;function n(r){return Math.floor(r/t.ONE_THOUSAND)}return Or.fromMiliseconds=n,Or}var bf;function Bb(){return bf||(bf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ks;e.__exportStar(_b(),t),e.__exportStar(Ob(),t)}(Ua)),Ua}var ni={},wf;function Ab(){if(wf)return ni;wf=1,Object.defineProperty(ni,"__esModule",{value:!0}),ni.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 ni.Watch=t,ni.default=t,ni}var La={},qi={},mf;function Db(){if(mf)return qi;mf=1,Object.defineProperty(qi,"__esModule",{value:!0}),qi.IWatch=void 0;class t{}return qi.IWatch=t,qi}var vf;function $b(){return vf||(vf=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Ks.__exportStar(Db(),t)}(La)),La}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ks;e.__exportStar(Bb(),t),e.__exportStar(Ab(),t),e.__exportStar($b(),t),e.__exportStar(gf(),t)})(H);class Ar{}class Tb extends Ar{constructor(e){super()}}const Ef=H.FIVE_SECONDS,Dr={pulse:"heartbeat_pulse"};class qa extends Tb{constructor(e){super(e),this.events=new rt.exports.EventEmitter,this.interval=Ef,this.interval=e?.interval||Ef}static async init(e){const n=new qa(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(),H.toMiliseconds(this.interval))}pulse(){this.events.emit(Dr.pulse)}}const Pb=/"(?:_|\\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*:/,Rb=/"(?: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*:/,Nb=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Cb(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Ub(t);return}return e}function Ub(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function Hs(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(!Nb.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Pb.test(t)||Rb.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Cb)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function Fb(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Ne(t,...e){try{return Fb(t(...e))}catch(n){return Promise.reject(n)}}function kb(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function Lb(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function Gs(t){if(kb(t))return String(t);if(Lb(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return Gs(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Ma="base64:";function qb(t){return typeof t=="string"?t:Ma+zb(t)}function Mb(t){return typeof t!="string"||!t.startsWith(Ma)?t:jb(t.slice(Ma.length))}function jb(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function zb(t){return globalThis.Buffer?Buffer.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function ht(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Vb(...t){return ht(t.join(":"))}function Ws(t){return t=ht(t),t?t+":":""}function Kb(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 Hb(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}function i$(t){return t}const Gb="memory",Wb=()=>{const t=new Map;return{name:Gb,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 Zb(t={}){const e={mounts:{"":t.driver||Wb()},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=ht(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 xf(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 d=new Map,h=p=>{let g=d.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},d.set(p.base,g)),g};for(const p of u){const g=typeof p=="string",m=ht(g?p:p.key),B=g?void 0:p.value,$=g||!p.options?l:{...l,...p.options},x=n(m);h(x).items.push({key:m,value:B,relativeKey:x.relativeKey,options:$})}return Promise.all([...d.values()].map(p=>f(p))).then(p=>p.flat())},c={hasItem(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return Ne(d.hasItem,f,l)},getItem(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return Ne(d.getItem,f,l).then(h=>Hs(h))},getItems(u,l={}){return a(u,l,f=>f.driver.getItems?Ne(f.driver.getItems,f.items.map(d=>({key:d.relativeKey,options:d.options})),l).then(d=>d.map(h=>({key:Vb(f.base,h.key),value:Hs(h.value)}))):Promise.all(f.items.map(d=>Ne(f.driver.getItem,d.relativeKey,d.options).then(h=>({key:d.key,value:Hs(h)})))))},getItemRaw(u,l={}){u=ht(u);const{relativeKey:f,driver:d}=n(u);return d.getItemRaw?Ne(d.getItemRaw,f,l):Ne(d.getItem,f,l).then(h=>Mb(h))},async setItem(u,l,f={}){if(l===void 0)return c.removeItem(u);u=ht(u);const{relativeKey:d,driver:h}=n(u);h.setItem&&(await Ne(h.setItem,d,Gs(l),f),h.watch||i("update",u))},async setItems(u,l){await a(u,l,async f=>{if(f.driver.setItems)return Ne(f.driver.setItems,f.items.map(d=>({key:d.relativeKey,value:Gs(d.value),options:d.options})),l);f.driver.setItem&&await Promise.all(f.items.map(d=>Ne(f.driver.setItem,d.relativeKey,Gs(d.value),d.options)))})},async setItemRaw(u,l,f={}){if(l===void 0)return c.removeItem(u,f);u=ht(u);const{relativeKey:d,driver:h}=n(u);if(h.setItemRaw)await Ne(h.setItemRaw,d,l,f);else if(h.setItem)await Ne(h.setItem,d,qb(l),f);else return;h.watch||i("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=ht(u);const{relativeKey:f,driver:d}=n(u);d.removeItem&&(await Ne(d.removeItem,f,l),(l.removeMeta||l.removeMata)&&await Ne(d.removeItem,f+"$",l),d.watch||i("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=ht(u);const{relativeKey:f,driver:d}=n(u),h=Object.create(null);if(d.getMeta&&Object.assign(h,await Ne(d.getMeta,f,l)),!l.nativeOnly){const p=await Ne(d.getItem,f+"$",l).then(g=>Hs(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(h,p))}return h},setMeta(u,l,f={}){return this.setItem(u+"$",l,f)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=Ws(u);const f=r(u,!0);let d=[];const h=[];let p=!0;for(const m of f){m.driver.flags?.maxDepth||(p=!1);const B=await Ne(m.driver.getKeys,m.relativeBase,l);for(const $ of B){const x=m.mountpoint+ht($);d.some(_=>x.startsWith(_))||h.push(x)}d=[m.mountpoint,...d.filter($=>!$.startsWith(m.mountpoint))]}const g=l.maxDepth!==void 0&&!p;return h.filter(m=>(!g||Kb(m,l.maxDepth))&&Hb(m,u))},async clear(u,l={}){u=Ws(u),await Promise.all(r(u,!1).map(async f=>{if(f.driver.clear)return Ne(f.driver.clear,f.relativeBase,l);if(f.driver.removeItem){const d=await f.driver.getKeys(f.relativeBase||"",l);return Promise.all(d.map(h=>f.driver.removeItem(h,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>_f(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=Ws(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((f,d)=>d.length-f.length)),e.mounts[u]=l,e.watching&&Promise.resolve(xf(l,i,u)).then(f=>{e.unwatch[u]=f}).catch(console.error),c},async unmount(u,l=!0){u=Ws(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await _f(e.mounts[u]),e.mountpoints=e.mountpoints.filter(f=>f!==u),delete e.mounts[u])},getMount(u=""){u=ht(u)+":";const l=n(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=ht(u),r(u,l.parents).map(d=>({driver:d.driver,base:d.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,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 xf(t,e,n){return t.watch?t.watch((r,i)=>e(r,n+i)):()=>{}}async function _f(t){typeof t.dispose=="function"&&await Ne(t.dispose)}function $r(t){return new Promise((e,n)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>n(t.error)})}function If(t,e){const n=indexedDB.open(t);n.onupgradeneeded=()=>n.result.createObjectStore(e);const r=$r(n);return(i,s)=>r.then(o=>s(o.transaction(e,i).objectStore(e)))}let ja;function Mi(){return ja||(ja=If("keyval-store","keyval")),ja}function Sf(t,e=Mi()){return e("readonly",n=>$r(n.get(t)))}function Yb(t,e,n=Mi()){return n("readwrite",r=>(r.put(e,t),$r(r.transaction)))}function Xb(t,e=Mi()){return e("readwrite",n=>(n.delete(t),$r(n.transaction)))}function Jb(t=Mi()){return t("readwrite",e=>(e.clear(),$r(e.transaction)))}function Qb(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},$r(t.transaction)}function ew(t=Mi()){return t("readonly",e=>{if(e.getAllKeys)return $r(e.getAllKeys());const n=[];return Qb(e,r=>n.push(r.key)).then(()=>n)})}const tw=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n),nw=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 ri(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return nw(t)}catch{return t}}function ji(t){return typeof t=="string"?t:tw(t)||""}const rw="idb-keyval";var iw=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",n=i=>e+i;let r;return t.dbName&&t.storeName&&(r=If(t.dbName,t.storeName)),{name:rw,options:t,async hasItem(i){return!(typeof await Sf(n(i),r)>"u")},async getItem(i){return await Sf(n(i),r)??null},setItem(i,s){return Yb(n(i),s,r)},removeItem(i){return Xb(n(i),r)},getKeys(){return ew(r)},clear(){return Jb(r)}}};const sw="WALLET_CONNECT_V2_INDEXED_DB",ow="keyvaluestorage";class aw{constructor(){this.indexedDb=Zb({driver:iw({dbName:sw,storeName:ow})})}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,ji(n))}async removeItem(e){await this.indexedDb.removeItem(e)}}var za=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Zs={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 za<"u"&&za.localStorage?Zs.exports=za.localStorage:typeof window<"u"&&window.localStorage?Zs.exports=window.localStorage:Zs.exports=new e})();function cw(t){var e;return[t[0],ri((e=t[1])!=null?e:"")]}class uw{constructor(){this.localStorage=Zs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(cw)}async getItem(e){const n=this.localStorage.getItem(e);if(n!==null)return ri(n)}async setItem(e,n){this.localStorage.setItem(e,ji(n))}async removeItem(e){this.localStorage.removeItem(e)}}const lw="wc_storage_version",Of=1,fw=async(t,e,n)=>{const r=lw,i=await e.getItem(r);if(i&&i>=Of){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,Of),n(e),hw(t,o)},hw=async(t,e)=>{e.length&&e.forEach(async n=>{await t.removeItem(n)})};class dw{constructor(){this.initialized=!1,this.setInitialized=n=>{this.storage=n,this.initialized=!0};const e=new uw;this.storage=e;try{const n=new aw;fw(e,n,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,n){return await this.initialize(),this.storage.setItem(e,n)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const n=setInterval(()=>{this.initialized&&(clearInterval(n),e())},20)})}}var rn={exports:{}};function pw(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var gw=yw;function yw(t,e,n){var r=n&&n.stringify||pw,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,d=t&&t.length||0,h=0;h<d;){if(t.charCodeAt(h)===37&&h+1<d){switch(f=f>-1?f:0,t.charCodeAt(h+1)){case 100:case 102:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Number(e[l]),f=h+2,h++;break;case 105:if(l>=c||e[l]==null)break;f<h&&(u+=t.slice(f,h)),u+=Math.floor(Number(e[l])),f=h+2,h++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;f<h&&(u+=t.slice(f,h));var p=typeof e[l];if(p==="string"){u+="'"+e[l]+"'",f=h+2,h++;break}if(p==="function"){u+=e[l].name||"<anonymous>",f=h+2,h++;break}u+=r(e[l]),f=h+2,h++;break;case 115:if(l>=c)break;f<h&&(u+=t.slice(f,h)),u+=String(e[l]),f=h+2,h++;break;case 37:f<h&&(u+=t.slice(f,h)),u+="%",f=h+2,h++,l--;break}++l}++h}return f===-1?t:(f<d&&(u+=t.slice(f)),u)}const Bf=gw;rn.exports=gn;const zi=Tw().console||{},bw={mapHttpRequest:Ys,mapHttpResponse:Ys,wrapRequestSerializer:Wa,wrapResponseSerializer:Wa,wrapErrorSerializer:Wa,req:Ys,res:Ys,err:Df,errWithCause:Df};function Vn(t,e){return t==="silent"?1/0:e.levels.values[t]}const Va=Symbol("pino.logFuncs"),Ka=Symbol("pino.hierarchy"),ww={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Af(t,e){const n={logger:e,parent:t[Ka]};e[Ka]=n}function mw(t,e,n){const r={};e.forEach(i=>{r[i]=n[i]?n[i]:zi[i]||zi[ww[i]||"log"]||ii}),t[Va]=r}function vw(t,e){return Array.isArray(t)?t.filter(function(n){return n!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function gn(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||zi;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},i=vw(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=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof n=="function"&&a.forEach(function(g){n[g]=n}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",u=Object.create(n);u.log||(u.log=ii),mw(u,a,n),Af({},u),Object.defineProperty(u,"levelVal",{get:f}),Object.defineProperty(u,"level",{get:d,set:h});const l={transmit:e,serialize:i,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:Aw(t),messageKey:t.messageKey||"msg",onChild:t.onChild||ii};u.levels=Ew(t),u.level=c,u.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},u.setMaxListeners=u.getMaxListeners=u.emit=u.addListener=u.on=u.prependListener=u.once=u.prependOnceListener=u.removeListener=u.removeAllListeners=u.listeners=u.listenerCount=u.eventNames=u.write=u.flush=ii,u.serializers=r,u._serialize=i,u._stdErrSerialize=s,u.child=function(...g){return p.call(this,l,...g)},e&&(u._logEvent=Ga());function f(){return Vn(this.level,this)}function d(){return this._level}function h(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,Tr(this,l,u,"error"),Tr(this,l,u,"fatal"),Tr(this,l,u,"warn"),Tr(this,l,u,"info"),Tr(this,l,u,"debug"),Tr(this,l,u,"trace"),o.forEach(m=>{Tr(this,l,u,m)})}function p(g,m,B){if(!m)throw new Error("missing bindings for child Pino");B=B||{},i&&m.serializers&&(B.serializers=m.serializers);const $=B.serializers;if(i&&$){var x=Object.assign({},r,$),_=t.browser.serialize===!0?Object.keys(x):i;delete m.serializers,Ha([m],_,x,this._stdErrSerialize)}function T(C){this._childLevel=(C._childLevel|0)+1,this.bindings=m,x&&(this.serializers=x,this._serialize=_),e&&(this._logEvent=Ga([].concat(C._logEvent.bindings,m)))}T.prototype=this;const P=new T(this);return Af(this,P),P.child=function(...C){return p.call(this,g,...C)},P.level=B.level||this.level,g.onChild(P),P}return u}function Ew(t){const e=t.customLevels||{},n=Object.assign({},gn.levels.values,e),r=Object.assign({},gn.levels.labels,xw(e));return{values:n,labels:r}}function xw(t){const e={};return Object.keys(t).forEach(function(n){e[t[n]]=n}),e}gn.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"}},gn.stdSerializers=bw,gn.stdTimeFunctions=Object.assign({},{nullTime:$f,epochTime:Tf,unixTime:Dw,isoTime:$w});function _w(t){const e=[];t.bindings&&e.push(t.bindings);let n=t[Ka];for(;n.parent;)n=n.parent,n.logger.bindings&&e.push(n.logger.bindings);return e.reverse()}function Tr(t,e,n,r){if(Object.defineProperty(t,r,{value:Vn(t.level,n)>Vn(r,n)?ii:n[Va][r],writable:!0,enumerable:!0,configurable:!0}),t[r]===ii){if(!e.transmit)return;const s=e.transmit.level||t.level,o=Vn(s,n);if(Vn(r,n)<o)return}t[r]=Sw(t,e,n,r);const i=_w(t);i.length!==0&&(t[r]=Iw(i,t[r]))}function Iw(t,e){return function(){return e.apply(this,[...t,...arguments])}}function Sw(t,e,n,r){return function(i){return function(){const s=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===zi?zi:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var u=!1;if(e.serialize&&(Ha(o,this._serialize,this.serializers,this._stdErrSerialize),u=!0),e.asObject||e.formatters?i.call(a,...Ow(this,r,o,s,e)):i.apply(a,o),e.transmit){const l=e.transmit.level||t._level,f=Vn(l,n),d=Vn(r,n);if(d<f)return;Bw(this,{ts:s,methodLevel:r,methodValue:d,transmitLevel:l,transmitValue:n.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Vn(t._level,n)},o,u)}}}(t[Va][r])}function Ow(t,e,n,r,i){const{level:s,log:o=f=>f}=i.formatters||{},a=n.slice();let c=a[0];const u={};let l=(t._childLevel|0)+1;if(l<1&&(l=1),r&&(u.time=r),s){const f=s(e,t.levels.values[e]);Object.assign(u,f)}else u.level=t.levels.values[e];if(i.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());return[o(u),...a]}else{if(c!==null&&typeof c=="object"){for(;l--&&typeof a[0]=="object";)Object.assign(u,a.shift());c=a.length?Bf(a.shift(),a):void 0}else typeof c=="string"&&(c=Bf(a.shift(),a));return c!==void 0&&(u[i.messageKey]=c),[o(u)]}}function Ha(t,e,n,r){for(const i in t)if(r&&t[i]instanceof Error)t[i]=gn.stdSerializers.err(t[i]);else if(typeof t[i]=="object"&&!Array.isArray(t[i])&&e)for(const s in t[i])e.indexOf(s)>-1&&s in n&&(t[i][s]=n[s](t[i][s]))}function Bw(t,e,n,r=!1){const i=e.send,s=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,u=t._logEvent.bindings;r||Ha(n,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=n.filter(function(l){return u.indexOf(l)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,i(o,t._logEvent,c),t._logEvent=Ga(u)}function Ga(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Df(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const n in t)e[n]===void 0&&(e[n]=t[n]);return e}function Aw(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?$f:Tf}function Ys(){return{}}function Wa(t){return t}function ii(){}function $f(){return!1}function Tf(){return Date.now()}function Dw(){return Math.round(Date.now()/1e3)}function $w(){return new Date(Date.now()).toISOString()}function Tw(){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)||{}}}rn.exports.default=gn;var Pw=rn.exports.pino=gn;const Rw={level:"info"},Xs="custom_context",Za=1e3*1024;var Nw=Object.defineProperty,Cw=(t,e,n)=>e in t?Nw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Kn=(t,e,n)=>Cw(t,typeof e!="symbol"?e+"":e,n);class Uw{constructor(e){Kn(this,"nodeValue"),Kn(this,"sizeInBytes"),Kn(this,"next"),this.nodeValue=e,this.sizeInBytes=new TextEncoder().encode(this.nodeValue).length,this.next=null}get value(){return this.nodeValue}get size(){return this.sizeInBytes}}class Pf{constructor(e){Kn(this,"lengthInNodes"),Kn(this,"sizeInBytes"),Kn(this,"head"),Kn(this,"tail"),Kn(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const n=new Uw(e);if(n.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${n.size}`);for(;this.size+n.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=n),this.tail=n):(this.head=n,this.tail=n),this.lengthInNodes++,this.sizeInBytes+=n.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let n=this.head;for(;n!==null;)e.push(n.value),n=n.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const n=e.value;return e=e.next,{done:!1,value:n}}}}}const Fw=t=>JSON.stringify(t,(e,n)=>typeof n=="bigint"?n.toString()+"n":n);function Rf(t){return typeof t=="string"?t:Fw(t)||""}var kw=Object.defineProperty,Lw=(t,e,n)=>e in t?kw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Js=(t,e,n)=>Lw(t,typeof e!="symbol"?e+"":e,n);class Nf{constructor(e,n=Za){Js(this,"logs"),Js(this,"level"),Js(this,"levelValue"),Js(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=rn.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=n,this.logs=new Pf(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,n){n===rn.exports.levels.values.error?console.error(e):n===rn.exports.levels.values.warn?console.warn(e):n===rn.exports.levels.values.debug?console.debug(e):n===rn.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Rf({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 Pf(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const n=this.getLogArray();return n.push(Rf({extraMetadata:e})),new Blob(n,{type:"application/json"})}}var qw=Object.defineProperty,Mw=(t,e,n)=>e in t?qw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,jw=(t,e,n)=>Mw(t,typeof e!="symbol"?e+"":e,n);class zw{constructor(e,n=Za){jw(this,"baseChunkLogger"),this.baseChunkLogger=new Nf(e,n)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const n=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=n,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(n)}}var Vw=Object.defineProperty,Kw=(t,e,n)=>e in t?Vw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hw=(t,e,n)=>Kw(t,typeof e!="symbol"?e+"":e,n);class Gw{constructor(e,n=Za){Hw(this,"baseChunkLogger"),this.baseChunkLogger=new Nf(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 Ww=Object.defineProperty,Zw=Object.defineProperties,Yw=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,Xw=Object.prototype.hasOwnProperty,Jw=Object.prototype.propertyIsEnumerable,Uf=(t,e,n)=>e in t?Ww(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Hn=(t,e)=>{for(var n in e||(e={}))Xw.call(e,n)&&Uf(t,n,e[n]);if(Cf)for(var n of Cf(e))Jw.call(e,n)&&Uf(t,n,e[n]);return t},Gn=(t,e)=>Zw(t,Yw(e));function Qw(t){return Gn(Hn({},t),{level:t?.level||Rw.level})}function em(t,e,n=Xs){return t[n]=e,t}function dt(t,e=Xs){return t[e]||""}function tm(t,e,n=Xs){const r=dt(t,n);return r.trim()?`${r}/${e}`:e}function Ot(t,e,n=Xs){const r=tm(t,e,n),i=t.child({context:r});return em(i,r,n)}function nm(t){var e,n;const r=new zw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:rn.exports(Gn(Hn({},t.opts),{level:"trace",browser:Gn(Hn({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})})),chunkLoggerController:r}}function rm(t){var e,n;const r=new Gw((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:rn.exports(Gn(Hn({},t.opts),{level:"trace",browser:Gn(Hn({},(n=t.opts)==null?void 0:n.browser),{write:i=>r.write(i)})}),r),chunkLoggerController:r}}function Ff(t){var e;if(typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string")return{logger:t.loggerOverride,chunkLoggerController:null};const n=Gn(Hn({},t.opts),{level:typeof t.loggerOverride=="string"?t.loggerOverride:(e=t.opts)==null?void 0:e.level});return typeof window<"u"?nm(Gn(Hn({},t),{opts:n})):rm(Gn(Hn({},t),{opts:n}))}var im=Object.defineProperty,sm=(t,e,n)=>e in t?im(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,kf=(t,e,n)=>sm(t,typeof e!="symbol"?e+"":e,n);class om extends Ar{constructor(e){super(),this.opts=e,kf(this,"protocol","wc"),kf(this,"version",2)}}var am=Object.defineProperty,cm=(t,e,n)=>e in t?am(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,um=(t,e,n)=>cm(t,typeof e!="symbol"?e+"":e,n);class lm extends Ar{constructor(e,n){super(),this.core=e,this.logger=n,um(this,"records",new Map)}}class fm{constructor(e,n){this.logger=e,this.core=n}}class hm extends Ar{constructor(e,n){super(),this.relayer=e,this.logger=n}}class dm extends Ar{constructor(e){super()}}class pm{constructor(e,n,r,i){this.core=e,this.logger=n,this.name=r}}class gm extends Ar{constructor(e,n){super(),this.relayer=e,this.logger=n}}class ym extends Ar{constructor(e,n){super(),this.core=e,this.logger=n}}class bm{constructor(e,n,r){this.core=e,this.logger=n,this.store=r}}class wm{constructor(e,n){this.projectId=e,this.logger=n}}class mm{constructor(e,n,r){this.core=e,this.logger=n,this.telemetryEnabled=r}}var vm=Object.defineProperty,Em=(t,e,n)=>e in t?vm(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Lf=(t,e,n)=>Em(t,typeof e!="symbol"?e+"":e,n);class xm{constructor(e){this.opts=e,Lf(this,"protocol","wc"),Lf(this,"version",2)}}class _m{constructor(e){this.client=e}}function Im(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function qf(t,...e){if(!Im(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 Mf(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 Sm(t,e){qf(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}const si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ya=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Om(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function jf(t){return typeof t=="string"&&(t=Om(t)),qf(t),t}class Bm{clone(){return this._cloneInto()}}function Am(t){const e=r=>t().update(jf(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function zf(t=32){if(si&&typeof si.getRandomValues=="function")return si.getRandomValues(new Uint8Array(t));if(si&&typeof si.randomBytes=="function")return si.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function Dm(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 $m extends Bm{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=Ya(this.buffer)}update(e){Mf(this);const{view:n,buffer:r,blockLen:i}=this;e=jf(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=Ya(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){Mf(this),Sm(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;Dm(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Ya(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 Qs=BigInt(2**32-1),Xa=BigInt(32);function Vf(t,e=!1){return e?{h:Number(t&Qs),l:Number(t>>Xa&Qs)}:{h:Number(t>>Xa&Qs)|0,l:Number(t&Qs)|0}}function Tm(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}=Vf(t[i],e);[n[i],r[i]]=[s,o]}return[n,r]}const Pm=(t,e)=>BigInt(t>>>0)<<Xa|BigInt(e>>>0),Rm=(t,e,n)=>t>>>n,Nm=(t,e,n)=>t<<32-n|e>>>n,Cm=(t,e,n)=>t>>>n|e<<32-n,Um=(t,e,n)=>t<<32-n|e>>>n,Fm=(t,e,n)=>t<<64-n|e>>>n-32,km=(t,e,n)=>t>>>n-32|e<<64-n,Lm=(t,e)=>e,qm=(t,e)=>t,Mm=(t,e,n)=>t<<n|e>>>32-n,jm=(t,e,n)=>e<<n|t>>>32-n,zm=(t,e,n)=>e<<n-32|t>>>64-n,Vm=(t,e,n)=>t<<n-32|e>>>64-n;function Km(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const Hm=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Gm=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Wm=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Zm=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,Ym=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),Xm=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,ne={fromBig:Vf,split:Tm,toBig:Pm,shrSH:Rm,shrSL:Nm,rotrSH:Cm,rotrSL:Um,rotrBH:Fm,rotrBL:km,rotr32H:Lm,rotr32L:qm,rotlSH:Mm,rotlSL:jm,rotlBH:zm,rotlBL:Vm,add:Km,add3L:Hm,add3H:Gm,add4L:Wm,add4H:Zm,add5H:Xm,add5L:Ym},[Jm,Qm]=ne.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))),Wn=new Uint32Array(80),Zn=new Uint32Array(80);class e2 extends $m{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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)Wn[x]=e.getUint32(n),Zn[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=Wn[x-15]|0,T=Zn[x-15]|0,P=ne.rotrSH(_,T,1)^ne.rotrSH(_,T,8)^ne.shrSH(_,T,7),C=ne.rotrSL(_,T,1)^ne.rotrSL(_,T,8)^ne.shrSL(_,T,7),U=Wn[x-2]|0,D=Zn[x-2]|0,j=ne.rotrSH(U,D,19)^ne.rotrBH(U,D,61)^ne.shrSH(U,D,6),M=ne.rotrSL(U,D,19)^ne.rotrBL(U,D,61)^ne.shrSL(U,D,6),E=ne.add4L(C,M,Zn[x-7],Zn[x-16]),b=ne.add4H(E,P,j,Wn[x-7],Wn[x-16]);Wn[x]=b|0,Zn[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=ne.rotrSH(f,d,14)^ne.rotrSH(f,d,18)^ne.rotrBH(f,d,41),T=ne.rotrSL(f,d,14)^ne.rotrSL(f,d,18)^ne.rotrBL(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=ne.add5L($,T,C,Qm[x],Zn[x]),D=ne.add5H(U,B,_,P,Jm[x],Wn[x]),j=U|0,M=ne.rotrSH(r,i,28)^ne.rotrBH(r,i,34)^ne.rotrBH(r,i,39),E=ne.rotrSL(r,i,28)^ne.rotrBL(r,i,34)^ne.rotrBL(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=ne.add(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=ne.add3L(j,E,v);r=ne.add3H(y,D,M,b),i=y|0}({h:r,l:i}=ne.add(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=ne.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=ne.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=ne.add(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=ne.add(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=ne.add(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=ne.add(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=ne.add(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){Wn.fill(0),Zn.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 t2=Am(()=>new e2);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Ja=BigInt(0),Kf=BigInt(1),n2=BigInt(2);function Qa(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ec(t){if(!Qa(t))throw new Error("Uint8Array expected")}function tc(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const r2=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function nc(t){ec(t);let e="";for(let n=0;n<t.length;n++)e+=r2[t[n]];return e}function Hf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ja:BigInt("0x"+t)}const yn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Gf(t){if(t>=yn._0&&t<=yn._9)return t-yn._0;if(t>=yn.A&&t<=yn.F)return t-(yn.A-10);if(t>=yn.a&&t<=yn.f)return t-(yn.a-10)}function Wf(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=Gf(t.charCodeAt(s)),a=Gf(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 i2(t){return Hf(nc(t))}function eo(t){return ec(t),Hf(nc(Uint8Array.from(t).reverse()))}function Zf(t,e){return Wf(t.toString(16).padStart(e*2,"0"))}function rc(t,e){return Zf(t,e).reverse()}function bn(t,e,n){let r;if(typeof e=="string")try{r=Wf(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Qa(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 Yf(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];ec(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 ic=t=>typeof t=="bigint"&&Ja<=t;function s2(t,e,n){return ic(t)&&ic(e)&&ic(n)&&e<=t&&t<n}function Vi(t,e,n,r){if(!s2(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function o2(t){let e;for(e=0;t>Ja;t>>=Kf,e+=1);return e}const a2=t=>(n2<<BigInt(t-1))-Kf,c2={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"||Qa(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 sc(t,e,n={}){const r=(i,s,o)=>{const a=c2[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 Xf(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 Ce=BigInt(0),_e=BigInt(1),Pr=BigInt(2),u2=BigInt(3),oc=BigInt(4),Jf=BigInt(5),Qf=BigInt(8);function De(t,e){const n=t%e;return n>=Ce?n:e+n}function l2(t,e,n){if(e<Ce)throw new Error("invalid exponent, negatives unsupported");if(n<=Ce)throw new Error("invalid modulus");if(n===_e)return Ce;let r=_e;for(;e>Ce;)e&_e&&(r=r*t%n),t=t*t%n,e>>=_e;return r}function sn(t,e,n){let r=t;for(;e-- >Ce;)r*=r,r%=n;return r}function eh(t,e){if(t===Ce)throw new Error("invert: expected non-zero number");if(e<=Ce)throw new Error("invert: expected positive modulus, got "+e);let n=De(t,e),r=e,i=Ce,s=_e;for(;n!==Ce;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==_e)throw new Error("invert: does not exist");return De(i,e)}function f2(t){const e=(t-_e)/Pr;let n,r,i;for(n=t-_e,r=0;n%Pr===Ce;n/=Pr,r++);for(i=Pr;i<t&&l2(i,e,t)!==t-_e;i++)if(i>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+_e)/oc;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+_e)/Pr;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 d=1;for(let p=o.sqr(f);d<c&&!o.eql(p,o.ONE);d++)p=o.sqr(p);const h=o.pow(u,_e<<BigInt(c-d-1));u=o.sqr(h),l=o.mul(l,h),f=o.mul(f,u),c=d}return l}}function h2(t){if(t%oc===u2){const e=(t+_e)/oc;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%Qf===Jf){const e=(t-Jf)/Qf;return function(n,r){const i=n.mul(r,Pr),s=n.pow(i,e),o=n.mul(r,s),a=n.mul(n.mul(o,Pr),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 f2(t)}const d2=(t,e)=>(De(t,e)&_e)===_e,p2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function g2(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=p2.reduce((r,i)=>(r[i]="function",r),e);return sc(t,n)}function y2(t,e,n){if(n<Ce)throw new Error("invalid exponent, negatives unsupported");if(n===Ce)return t.ONE;if(n===_e)return e;let r=t.ONE,i=e;for(;n>Ce;)n&_e&&(r=t.mul(r,i)),i=t.sqr(i),n>>=_e;return r}function b2(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 th(t,e){const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function nh(t,e,n=!1,r={}){if(t<=Ce)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=th(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:a2(i),ZERO:Ce,ONE:_e,create:c=>De(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ce<=c&&c<t},is0:c=>c===Ce,isOdd:c=>(c&_e)===_e,neg:c=>De(-c,t),eql:(c,u)=>c===u,sqr:c=>De(c*c,t),add:(c,u)=>De(c+u,t),sub:(c,u)=>De(c-u,t),mul:(c,u)=>De(c*u,t),pow:(c,u)=>y2(a,c,u),div:(c,u)=>De(c*eh(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>eh(c,t),sqrt:r.sqrt||(c=>(o||(o=h2(t)),o(a,c))),invertBatch:c=>b2(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>n?rc(c,s):Zf(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?eo(c):i2(c)}});return Object.freeze(a)}const rh=BigInt(0),to=BigInt(1);function ac(t,e){const n=e.negate();return t?n:e}function ih(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function cc(t,e){ih(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1);return{windows:n,windowSize:r}}function w2(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 m2(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 uc=new WeakMap,sh=new WeakMap;function lc(t){return sh.get(t)||1}function v2(t,e){return{constTimeNegate:ac,hasPrecomputes(n){return lc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>rh;)r&to&&(i=i.add(s)),s=s.double(),r>>=to;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=cc(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}=cc(n,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**n-1),l=2**n,f=BigInt(n);for(let d=0;d<s;d++){const h=d*o;let p=Number(i&u);i>>=f,p>o&&(p-=l,i+=to);const g=h,m=h+Math.abs(p)-1,B=d%2!==0,$=p<0;p===0?c=c.add(ac(B,r[g])):a=a.add(ac($,r[m]))}return{p:a,f:c}},wNAFUnsafe(n,r,i,s=t.ZERO){const{windows:o,windowSize:a}=cc(n,e),c=BigInt(2**n-1),u=2**n,l=BigInt(n);for(let f=0;f<o;f++){const d=f*a;if(i===rh)break;let h=Number(i&c);if(i>>=l,h>a&&(h-=u,i+=to),h===0)continue;let p=r[d+Math.abs(h)-1];h<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(n,r,i){let s=uc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&uc.set(r,i(s))),s},wNAFCached(n,r,i){const s=lc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=lc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){ih(r,e),sh.set(n,r),uc.delete(n)}}}function E2(t,e,n,r){if(w2(n,t),m2(r,e),n.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const i=t.ZERO,s=o2(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 h=0;h<r.length;h++){const p=r[h],g=Number(p>>BigInt(f)&BigInt(a));c[g]=c[g].add(n[h])}let d=i;for(let h=c.length-1,p=i;h>0;h--)p=p.add(c[h]),d=d.add(p);if(l=l.add(d),f!==0)for(let h=0;h<o;h++)l=l.double()}return l}function x2(t){return g2(t.Fp),sc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...th(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const Ht=BigInt(0),pt=BigInt(1),no=BigInt(2),_2=BigInt(8),I2={zip215:!0};function S2(t){const e=x2(t);return sc(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function O2(t){const e=S2(t),{Fp:n,n:r,prehash:i,hash:s,randomBytes:o,nByteLength:a,h:c}=e,u=no<<BigInt(a*8)-pt,l=n.create,f=nh(e.n,e.nBitLength),d=e.uvRatio||((y,w)=>{try{return{isValid:!0,value:n.sqrt(y*n.inv(w))}}catch{return{isValid:!1,value:Ht}}}),h=e.adjustScalarBytes||(y=>y),p=e.domain||((y,w,I)=>{if(tc("phflag",I),w.length||I)throw new Error("Contexts/pre-hash are not supported");return y});function g(y,w){Vi("coordinate "+y,w,Ht,u)}function m(y){if(!(y instanceof x))throw new Error("ExtendedPoint expected")}const B=Xf((y,w)=>{const{ex:I,ey:O,ez:S}=y,A=y.is0();w==null&&(w=A?_2:n.inv(S));const R=l(I*w),k=l(O*w),F=l(S*w);if(A)return{x:Ht,y:pt};if(F!==pt)throw new Error("invZ was invalid");return{x:R,y:k}}),$=Xf(y=>{const{a:w,d:I}=e;if(y.is0())throw new Error("bad point: ZERO");const{ex:O,ey:S,ez:A,et:R}=y,k=l(O*O),F=l(S*S),L=l(A*A),N=l(L*L),q=l(k*w),z=l(L*l(q+F)),W=l(N+l(I*l(k*F)));if(z!==W)throw new Error("bad point: equation left != right (1)");const K=l(O*S),Z=l(A*R);if(K!==Z)throw new Error("bad point: equation left != right (2)");return!0});class x{constructor(w,I,O,S){this.ex=w,this.ey=I,this.ez=O,this.et=S,g("x",w),g("y",I),g("z",O),g("t",S),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(w){if(w instanceof x)throw new Error("extended point not allowed");const{x:I,y:O}=w||{};return g("x",I),g("y",O),new x(I,O,pt,l(I*O))}static normalizeZ(w){const I=n.invertBatch(w.map(O=>O.ez));return w.map((O,S)=>O.toAffine(I[S])).map(x.fromAffine)}static msm(w,I){return E2(x,f,w,I)}_setWindowSize(w){P.setWindowSize(this,w)}assertValidity(){$(this)}equals(w){m(w);const{ex:I,ey:O,ez:S}=this,{ex:A,ey:R,ez:k}=w,F=l(I*k),L=l(A*S),N=l(O*k),q=l(R*S);return F===L&&N===q}is0(){return this.equals(x.ZERO)}negate(){return new x(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:w}=e,{ex:I,ey:O,ez:S}=this,A=l(I*I),R=l(O*O),k=l(no*l(S*S)),F=l(w*A),L=I+O,N=l(l(L*L)-A-R),q=F+R,z=q-k,W=F-R,K=l(N*z),Z=l(q*W),Q=l(N*W),ee=l(z*q);return new x(K,Z,ee,Q)}add(w){m(w);const{a:I,d:O}=e,{ex:S,ey:A,ez:R,et:k}=this,{ex:F,ey:L,ez:N,et:q}=w;if(I===BigInt(-1)){const jy=l((A-S)*(L+F)),zy=l((A+S)*(L-F)),Hl=l(zy-jy);if(Hl===Ht)return this.double();const Vy=l(R*no*q),Ky=l(k*no*N),Hy=Ky+Vy,Gy=zy+jy,Wy=Ky-Vy,e$=l(Hy*Hl),t$=l(Gy*Wy),n$=l(Hy*Wy),r$=l(Hl*Gy);return new x(e$,t$,r$,n$)}const z=l(S*F),W=l(A*L),K=l(k*O*q),Z=l(R*N),Q=l((S+A)*(F+L)-z-W),ee=Z-K,ie=Z+K,he=l(W-I*z),Ee=l(Q*ee),zn=l(ie*he),Aa=l(Q*he),QD=l(ee*ie);return new x(Ee,zn,QD,Aa)}subtract(w){return this.add(w.negate())}wNAF(w){return P.wNAFCached(this,w,x.normalizeZ)}multiply(w){const I=w;Vi("scalar",I,pt,r);const{p:O,f:S}=this.wNAF(I);return x.normalizeZ([O,S])[0]}multiplyUnsafe(w,I=x.ZERO){const O=w;return Vi("scalar",O,Ht,r),O===Ht?T:this.is0()||O===pt?this:P.wNAFCachedUnsafe(this,O,x.normalizeZ,I)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,r).is0()}toAffine(w){return B(this,w)}clearCofactor(){const{h:w}=e;return w===pt?this:this.multiplyUnsafe(w)}static fromHex(w,I=!1){const{d:O,a:S}=e,A=n.BYTES;w=bn("pointHex",w,A),tc("zip215",I);const R=w.slice(),k=w[A-1];R[A-1]=k&-129;const F=eo(R),L=I?u:n.ORDER;Vi("pointHex.y",F,Ht,L);const N=l(F*F),q=l(N-pt),z=l(O*N-S);let{isValid:W,value:K}=d(q,z);if(!W)throw new Error("Point.fromHex: invalid y coordinate");const Z=(K&pt)===pt,Q=(k&128)!==0;if(!I&&K===Ht&&Q)throw new Error("Point.fromHex: x=0 and x_0=1");return Q!==Z&&(K=l(-K)),x.fromAffine({x:K,y:F})}static fromPrivateKey(w){return D(w).point}toRawBytes(){const{x:w,y:I}=this.toAffine(),O=rc(I,n.BYTES);return O[O.length-1]|=w&pt?128:0,O}toHex(){return nc(this.toRawBytes())}}x.BASE=new x(e.Gx,e.Gy,pt,l(e.Gx*e.Gy)),x.ZERO=new x(Ht,pt,pt,Ht);const{BASE:_,ZERO:T}=x,P=v2(x,a*8);function C(y){return De(y,r)}function U(y){return C(eo(y))}function D(y){const w=n.BYTES;y=bn("private key",y,w);const I=bn("hashed private key",s(y),2*w),O=h(I.slice(0,w)),S=I.slice(w,2*w),A=U(O),R=_.multiply(A),k=R.toRawBytes();return{head:O,prefix:S,scalar:A,point:R,pointBytes:k}}function j(y){return D(y).pointBytes}function M(y=new Uint8Array,...w){const I=Yf(...w);return U(s(p(I,bn("context",y),!!i)))}function E(y,w,I={}){y=bn("message",y),i&&(y=i(y));const{prefix:O,scalar:S,pointBytes:A}=D(w),R=M(I.context,O,y),k=_.multiply(R).toRawBytes(),F=M(I.context,k,A,y),L=C(R+F*S);Vi("signature.s",L,Ht,r);const N=Yf(k,rc(L,n.BYTES));return bn("result",N,n.BYTES*2)}const b=I2;function v(y,w,I,O=b){const{context:S,zip215:A}=O,R=n.BYTES;y=bn("signature",y,2*R),w=bn("message",w),I=bn("publicKey",I,R),A!==void 0&&tc("zip215",A),i&&(w=i(w));const k=eo(y.slice(R,2*R));let F,L,N;try{F=x.fromHex(I,A),L=x.fromHex(y.slice(0,R),A),N=_.multiplyUnsafe(k)}catch{return!1}if(!A&&F.isSmallOrder())return!1;const q=M(S,L.toRawBytes(),F.toRawBytes(),w);return L.add(F.multiplyUnsafe(q)).subtract(N).clearCofactor().equals(x.ZERO)}return _._setWindowSize(8),{CURVE:e,getPublicKey:j,sign:E,verify:v,ExtendedPoint:x,utils:{getExtendedPublicKey:D,randomPrivateKey:()=>o(n.BYTES),precompute(y=8,w=x.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}}}}BigInt(0),BigInt(1);const fc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),oh=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const B2=BigInt(1),ah=BigInt(2);BigInt(3);const A2=BigInt(5),D2=BigInt(8);function $2(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=fc,o=t*t%s*t%s,a=sn(o,ah,s)*o%s,c=sn(a,B2,s)*t%s,u=sn(c,A2,s)*c%s,l=sn(u,e,s)*u%s,f=sn(l,n,s)*l%s,d=sn(f,r,s)*f%s,h=sn(d,i,s)*d%s,p=sn(h,i,s)*d%s,g=sn(p,e,s)*u%s;return{pow_p_5_8:sn(g,ah,s)*t%s,b2:o}}function T2(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function P2(t,e){const n=fc,r=De(e*e*e,n),i=De(r*r*e,n),s=$2(t*i).pow_p_5_8;let o=De(t*r*s,n);const a=De(e*o*o,n),c=o,u=De(o*oh,n),l=a===t,f=a===De(-t,n),d=a===De(-t*oh,n);return l&&(o=c),(f||d)&&(o=u),d2(o,n)&&(o=De(-o,n)),{isValid:l||f,value:o}}const R2=nh(fc,void 0,!0),N2={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:R2,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:D2,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:t2,randomBytes:zf,adjustScalarBytes:T2,uvRatio:P2},ch=O2(N2),C2="EdDSA",U2="JWT",ro=".",io="base64url",uh="utf8",lh="utf8",F2=":",k2="did",L2="key",fh="base58btc",q2="z",M2="K36",j2=32;function hc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function hh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?hc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function dh(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=hh(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return hc(n)}function z2(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var V2=z2,K2=V2;const ph=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")},H2=t=>new TextEncoder().encode(t),G2=t=>new TextDecoder().decode(t);class W2{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 Z2{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 gh(this,e)}}class Y2{constructor(e){this.decoders=e}or(e){return gh(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 gh=(t,e)=>new Y2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class X2{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new W2(e,n,r),this.decoder=new Z2(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const so=({name:t,prefix:e,encode:n,decode:r})=>new X2(t,e,n,r),Ki=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=K2(n,e);return so({prefix:t,name:e,encode:r,decode:s=>ph(i(s))})},J2=(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},Q2=(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},Le=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>so({prefix:e,name:t,encode(i){return Q2(i,r,n)},decode(i){return J2(i,r,n,t)}}),ev=so({prefix:"\0",name:"identity",encode:t=>G2(t),decode:t=>H2(t)});var tv=Object.freeze({__proto__:null,identity:ev});const nv=Le({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var rv=Object.freeze({__proto__:null,base2:nv});const iv=Le({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sv=Object.freeze({__proto__:null,base8:iv});const ov=Ki({prefix:"9",name:"base10",alphabet:"0123456789"});var av=Object.freeze({__proto__:null,base10:ov});const cv=Le({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),uv=Le({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var lv=Object.freeze({__proto__:null,base16:cv,base16upper:uv});const fv=Le({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),hv=Le({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dv=Le({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pv=Le({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gv=Le({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yv=Le({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),bv=Le({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),wv=Le({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),mv=Le({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vv=Object.freeze({__proto__:null,base32:fv,base32upper:hv,base32pad:dv,base32padupper:pv,base32hex:gv,base32hexupper:yv,base32hexpad:bv,base32hexpadupper:wv,base32z:mv});const Ev=Ki({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xv=Ki({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _v=Object.freeze({__proto__:null,base36:Ev,base36upper:xv});const Iv=Ki({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sv=Ki({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ov=Object.freeze({__proto__:null,base58btc:Iv,base58flickr:Sv});const Bv=Le({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Av=Le({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Dv=Le({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),$v=Le({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Tv=Object.freeze({__proto__:null,base64:Bv,base64pad:Av,base64url:Dv,base64urlpad:$v});const yh=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}"),Pv=yh.reduce((t,e,n)=>(t[n]=e,t),[]),Rv=yh.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function Nv(t){return t.reduce((e,n)=>(e+=Pv[n],e),"")}function Cv(t){const e=[];for(const n of t){const r=Rv[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const Uv=so({prefix:"\u{1F680}",name:"base256emoji",encode:Nv,decode:Cv});var Fv=Object.freeze({__proto__:null,base256emoji:Uv}),kv=wh,bh=128,Lv=127,qv=~Lv,Mv=Math.pow(2,31);function wh(t,e,n){e=e||[],n=n||0;for(var r=n;t>=Mv;)e[n++]=t&255|bh,t/=128;for(;t&qv;)e[n++]=t&255|bh,t>>>=7;return e[n]=t|0,wh.bytes=n-r+1,e}var jv=dc,zv=128,mh=127;function dc(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw dc.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&mh)<<i:(o&mh)*Math.pow(2,i),i+=7}while(o>=zv);return dc.bytes=s-r,n}var Vv=Math.pow(2,7),Kv=Math.pow(2,14),Hv=Math.pow(2,21),Gv=Math.pow(2,28),Wv=Math.pow(2,35),Zv=Math.pow(2,42),Yv=Math.pow(2,49),Xv=Math.pow(2,56),Jv=Math.pow(2,63),Qv=function(t){return t<Vv?1:t<Kv?2:t<Hv?3:t<Gv?4:t<Wv?5:t<Zv?6:t<Yv?7:t<Xv?8:t<Jv?9:10},eE={encode:kv,decode:jv,encodingLength:Qv},vh=eE;const Eh=(t,e,n=0)=>(vh.encode(t,e,n),e),xh=t=>vh.encodingLength(t),pc=(t,e)=>{const n=e.byteLength,r=xh(t),i=r+xh(n),s=new Uint8Array(i+n);return Eh(t,s,0),Eh(n,s,r),s.set(e,i),new tE(t,n,e,s)};class tE{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const _h=({name:t,code:e,encode:n})=>new nE(t,e,n);class nE{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?pc(this.code,n):n.then(r=>pc(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Ih=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),rE=_h({name:"sha2-256",code:18,encode:Ih("SHA-256")}),iE=_h({name:"sha2-512",code:19,encode:Ih("SHA-512")});var sE=Object.freeze({__proto__:null,sha256:rE,sha512:iE});const Sh=0,oE="identity",Oh=ph;var aE=Object.freeze({__proto__:null,identity:{code:Sh,name:oE,encode:Oh,digest:t=>pc(Sh,Oh(t))}});new TextEncoder,new TextDecoder;const Bh={...tv,...rv,...sv,...av,...lv,...vv,..._v,...Ov,...Tv,...Fv};({...sE,...aE});function Ah(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const Dh=Ah("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),gc=Ah("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=hh(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),$h={utf8:Dh,"utf-8":Dh,hex:Bh.base16,latin1:gc,ascii:gc,binary:gc,...Bh};function oo(t,e="utf8"){const n=$h[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 oi(t,e="utf8"){const n=$h[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?hc(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function Th(t){return ri(oo(oi(t,io),uh))}function ao(t){return oo(oi(ji(t),uh),io)}function Ph(t){const e=oi(M2,fh),n=q2+oo(dh([e,t]),fh);return[k2,L2,n].join(F2)}function cE(t){return oo(t,io)}function uE(t){return oi(t,io)}function lE(t){return oi([ao(t.header),ao(t.payload)].join(ro),lh)}function fE(t){return[ao(t.header),ao(t.payload),cE(t.signature)].join(ro)}function yc(t){const e=t.split(ro),n=Th(e[0]),r=Th(e[1]),i=uE(e[2]),s=oi(e.slice(0,2).join(ro),lh);return{header:n,payload:r,signature:i,data:s}}function Rh(t=zf(j2)){const e=ch.getPublicKey(t);return{secretKey:dh([t,e]),publicKey:e}}async function hE(t,e,n,r,i=H.fromMiliseconds(Date.now())){const s={alg:C2,typ:U2},o=Ph(r.publicKey),a=i+n,c={iss:o,sub:t,aud:e,iat:i,exp:a},u=lE({header:s,payload:c}),l=ch.sign(u,r.secretKey.slice(0,32));return fE({header:s,payload:c,signature:l})}var Nh=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))},dE=function(){function t(e,n,r){this.name=e,this.version=n,this.os=r,this.type="browser"}return t}(),pE=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=process.platform}return t}(),gE=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}(),yE=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),bE=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),wE=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,mE=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,Ch=3,vE=[["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",wE]],Uh=[["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 EE(t){return t?Fh(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new bE:typeof navigator<"u"?Fh(navigator.userAgent):IE()}function xE(t){return t!==""&&vE.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 Fh(t){var e=xE(t);if(!e)return null;var n=e[0],r=e[1];if(n==="searchbot")return new yE;var i=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);i?i.length<Ch&&(i=Nh(Nh([],i,!0),SE(Ch-i.length),!0)):i=[];var s=i.join("."),o=_E(t),a=mE.exec(t);return a&&a[1]?new gE(n,s,o,a[1]):new dE(n,s,o)}function _E(t){for(var e=0,n=Uh.length;e<n;e++){var r=Uh[e],i=r[0],s=r[1],o=s.exec(t);if(o)return i}return null}function IE(){var t=typeof process<"u"&&process.version;return t?new pE(process.version.slice(1)):null}function SE(t){for(var e=[],n=0;n<t;n++)e.push("0");return e}var we={};Object.defineProperty(we,"__esModule",{value:!0}),we.getLocalStorage=we.getLocalStorageOrThrow=we.getCrypto=we.getCryptoOrThrow=kh=we.getLocation=we.getLocationOrThrow=bc=we.getNavigator=we.getNavigatorOrThrow=Nr=we.getDocument=we.getDocumentOrThrow=we.getFromWindowOrThrow=we.getFromWindow=void 0;function Rr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}we.getFromWindow=Rr;function ai(t){const e=Rr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}we.getFromWindowOrThrow=ai;function OE(){return ai("document")}we.getDocumentOrThrow=OE;function BE(){return Rr("document")}var Nr=we.getDocument=BE;function AE(){return ai("navigator")}we.getNavigatorOrThrow=AE;function DE(){return Rr("navigator")}var bc=we.getNavigator=DE;function $E(){return ai("location")}we.getLocationOrThrow=$E;function TE(){return Rr("location")}var kh=we.getLocation=TE;function PE(){return ai("crypto")}we.getCryptoOrThrow=PE;function RE(){return Rr("crypto")}we.getCrypto=RE;function NE(){return ai("localStorage")}we.getLocalStorageOrThrow=NE;function CE(){return Rr("localStorage")}we.getLocalStorage=CE;var wc={};Object.defineProperty(wc,"__esModule",{value:!0});var Lh=wc.getWindowMetadata=void 0;const qh=we;function UE(){let t,e;try{t=qh.getDocumentOrThrow(),e=qh.getLocationOrThrow()}catch{return null}function n(){const f=t.getElementsByTagName("link"),d=[];for(let h=0;h<f.length;h++){const p=f[h],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const m=p.getAttribute("href");if(m)if(m.toLowerCase().indexOf("https:")===-1&&m.toLowerCase().indexOf("http:")===-1&&m.indexOf("//")!==0){let B=e.protocol+"//"+e.host;if(m.indexOf("/")===0)B+=m;else{const $=e.pathname.split("/");$.pop();const x=$.join("/");B+=x+"/"+m}d.push(B)}else if(m.indexOf("//")===0){const B=e.protocol+m;d.push(B)}else d.push(m)}}return d}function r(...f){const d=t.getElementsByTagName("meta");for(let h=0;h<d.length;h++){const p=d[h],g=["itemprop","property","name"].map(m=>p.getAttribute(m)).filter(m=>m?f.includes(m):!1);if(g.length&&g){const m=p.getAttribute("content");if(m)return m}}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}}Lh=wc.getWindowMetadata=UE;const FE="0.1.1";function kE(){return FE}class ye extends Error{constructor(e,n={}){const r=(()=>{if(n.cause instanceof ye){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 ye&&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(`
|
|
15
|
+
`);super(a,n.cause?{cause:n.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${kE()}`}),this.cause=n.cause,this.details=r,this.docs=o,this.docsPath=i,this.shortMessage=e}walk(e){return Mh(this,e)}}function Mh(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Mh(t.cause,e):e?null:t}const ci=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function co(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ui(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function wn(t,...e){if(!co(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 jh(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");ui(t.outputLen),ui(t.blockLen)}function li(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 zh(t,e){wn(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function LE(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Yn(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function mc(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function on(t,e){return t<<32-e|t>>>e}const qE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function ME(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function jE(t){for(let e=0;e<t.length;e++)t[e]=ME(t[e]);return t}const Vh=qE?t=>t:jE,Kh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",zE=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function fi(t){if(wn(t),Kh)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=zE[t[n]];return e}const mn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hh(t){if(t>=mn._0&&t<=mn._9)return t-mn._0;if(t>=mn.A&&t<=mn.F)return t-(mn.A-10);if(t>=mn.a&&t<=mn.f)return t-(mn.a-10)}function uo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Kh)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=Hh(t.charCodeAt(s)),a=Hh(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 vc(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function lo(t){return typeof t=="string"&&(t=vc(t)),wn(t),t}function vn(...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}class Ec{}function fo(t){const e=r=>t().update(lo(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function ho(t=32){if(ci&&typeof ci.getRandomValues=="function")return ci.getRandomValues(new Uint8Array(t));if(ci&&typeof ci.randomBytes=="function")return Uint8Array.from(ci.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function VE(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 KE(t,e,n){return t&e^~t&n}function HE(t,e,n){return t&e^t&n^e&n}class Gh extends Ec{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=mc(this.buffer)}update(e){li(this),e=lo(e),wn(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=mc(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){li(this),zh(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,Yn(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;VE(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=mc(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 En=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Ge=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),We=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),po=BigInt(2**32-1),Wh=BigInt(32);function GE(t,e=!1){return e?{h:Number(t&po),l:Number(t>>Wh&po)}:{h:Number(t>>Wh&po)|0,l:Number(t&po)|0}}function Zh(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}=GE(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const Yh=(t,e,n)=>t>>>n,Xh=(t,e,n)=>t<<32-n|e>>>n,hi=(t,e,n)=>t>>>n|e<<32-n,di=(t,e,n)=>t<<32-n|e>>>n,go=(t,e,n)=>t<<64-n|e>>>n-32,yo=(t,e,n)=>t>>>n-32|e<<64-n,WE=(t,e,n)=>t<<n|e>>>32-n,ZE=(t,e,n)=>e<<n|t>>>32-n,YE=(t,e,n)=>e<<n-32|t>>>64-n,XE=(t,e,n)=>t<<n-32|e>>>64-n;function xn(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const JE=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),QE=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,e3=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),t3=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,n3=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),r3=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,i3=BigInt(0),Hi=BigInt(1),s3=BigInt(2),o3=BigInt(7),a3=BigInt(256),c3=BigInt(113),Jh=[],Qh=[],ed=[];for(let t=0,e=Hi,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Jh.push(2*(5*r+n)),Qh.push((t+1)*(t+2)/2%64);let i=i3;for(let s=0;s<7;s++)e=(e<<Hi^(e>>o3)*c3)%a3,e&s3&&(i^=Hi<<(Hi<<BigInt(s))-Hi);ed.push(i)}const td=Zh(ed,!0),u3=td[0],l3=td[1],nd=(t,e,n)=>n>32?YE(t,e,n):WE(t,e,n),rd=(t,e,n)=>n>32?XE(t,e,n):ZE(t,e,n);function f3(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=nd(u,l,1)^n[a],d=rd(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Qh[o],c=nd(i,s,a),u=rd(i,s,a),l=Jh[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]^=u3[r],t[1]^=l3[r]}Yn(n)}class xc extends Ec{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,ui(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=LE(this.state)}clone(){return this._cloneInto()}keccak(){Vh(this.state32),f3(this.state32,this.rounds),Vh(this.state32),this.posOut=0,this.pos=0}update(e){li(this),e=lo(e),wn(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){li(this,!1),wn(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 ui(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(zh(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,Yn(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new xc(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 h3=(t,e,n)=>fo(()=>new xc(e,t,n)),d3=h3(1,136,256/8),p3=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]),Xn=new Uint32Array(64);class g3 extends Gh{constructor(e=32){super(64,e,8,!1),this.A=En[0]|0,this.B=En[1]|0,this.C=En[2]|0,this.D=En[3]|0,this.E=En[4]|0,this.F=En[5]|0,this.G=En[6]|0,this.H=En[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)Xn[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=Xn[f-15],h=Xn[f-2],p=on(d,7)^on(d,18)^d>>>3,g=on(h,17)^on(h,19)^h>>>10;Xn[f]=g+Xn[f-7]+p+Xn[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 d=on(a,6)^on(a,11)^on(a,25),h=l+d+KE(a,c,u)+p3[f]+Xn[f]|0,g=(on(r,2)^on(r,13)^on(r,22))+HE(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+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(){Yn(Xn)}destroy(){this.set(0,0,0,0,0,0,0,0),Yn(this.buffer)}}const id=Zh(["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))),y3=id[0],b3=id[1],Jn=new Uint32Array(80),Qn=new Uint32Array(80);class sd extends Gh{constructor(e=64){super(128,e,16,!1),this.Ah=We[0]|0,this.Al=We[1]|0,this.Bh=We[2]|0,this.Bl=We[3]|0,this.Ch=We[4]|0,this.Cl=We[5]|0,this.Dh=We[6]|0,this.Dl=We[7]|0,this.Eh=We[8]|0,this.El=We[9]|0,this.Fh=We[10]|0,this.Fl=We[11]|0,this.Gh=We[12]|0,this.Gl=We[13]|0,this.Hh=We[14]|0,this.Hl=We[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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)Jn[x]=e.getUint32(n),Qn[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=Jn[x-15]|0,T=Qn[x-15]|0,P=hi(_,T,1)^hi(_,T,8)^Yh(_,T,7),C=di(_,T,1)^di(_,T,8)^Xh(_,T,7),U=Jn[x-2]|0,D=Qn[x-2]|0,j=hi(U,D,19)^go(U,D,61)^Yh(U,D,6),M=di(U,D,19)^yo(U,D,61)^Xh(U,D,6),E=e3(C,M,Qn[x-7],Qn[x-16]),b=t3(E,P,j,Jn[x-7],Jn[x-16]);Jn[x]=b|0,Qn[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=hi(f,d,14)^hi(f,d,18)^go(f,d,41),T=di(f,d,14)^di(f,d,18)^yo(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=n3($,T,C,b3[x],Qn[x]),D=r3(U,B,_,P,y3[x],Jn[x]),j=U|0,M=hi(r,i,28)^go(r,i,34)^go(r,i,39),E=di(r,i,28)^yo(r,i,34)^yo(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=xn(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=JE(j,E,v);r=QE(y,D,M,b),i=y|0}({h:r,l:i}=xn(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=xn(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=xn(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=xn(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=xn(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=xn(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=xn(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=xn(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){Yn(Jn,Qn)}destroy(){Yn(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class w3 extends sd{constructor(){super(48),this.Ah=Ge[0]|0,this.Al=Ge[1]|0,this.Bh=Ge[2]|0,this.Bl=Ge[3]|0,this.Ch=Ge[4]|0,this.Cl=Ge[5]|0,this.Dh=Ge[6]|0,this.Dl=Ge[7]|0,this.Eh=Ge[8]|0,this.El=Ge[9]|0,this.Fh=Ge[10]|0,this.Fl=Ge[11]|0,this.Gh=Ge[12]|0,this.Gl=Ge[13]|0,this.Hh=Ge[14]|0,this.Hl=Ge[15]|0}}const pi=fo(()=>new g3),m3=fo(()=>new sd),v3=fo(()=>new w3);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _c=BigInt(0),bo=BigInt(1);function Gi(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function er(t){if(!Gi(t))throw new Error("Uint8Array expected")}function Wi(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function wo(t){const e=t.toString(16);return e.length&1?"0"+e:e}function od(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?_c:BigInt("0x"+t)}const ad=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",E3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cr(t){if(er(t),ad)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=E3[t[n]];return e}const _n={_0:48,_9:57,A:65,F:70,a:97,f:102};function cd(t){if(t>=_n._0&&t<=_n._9)return t-_n._0;if(t>=_n.A&&t<=_n.F)return t-(_n.A-10);if(t>=_n.a&&t<=_n.f)return t-(_n.a-10)}function mo(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(ad)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=cd(t.charCodeAt(s)),a=cd(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 it(t){return od(Cr(t))}function ud(t){return er(t),od(Cr(Uint8Array.from(t).reverse()))}function $e(t,e){return mo(t.toString(16).padStart(e*2,"0"))}function ld(t,e){return $e(t,e).reverse()}function Ze(t,e,n){let r;if(typeof e=="string")try{r=mo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Gi(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 Ie(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];er(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 Ic(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}const Sc=t=>typeof t=="bigint"&&_c<=t;function Oc(t,e,n){return Sc(t)&&Sc(e)&&Sc(n)&&e<=t&&t<n}function gi(t,e,n,r){if(!Oc(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function Zi(t){let e;for(e=0;t>_c;t>>=bo,e+=1);return e}function x3(t,e){return t>>BigInt(e)&bo}const Ur=t=>(bo<<BigInt(t))-bo,Bc=t=>new Uint8Array(t),fd=t=>Uint8Array.from(t);function _3(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=Bc(t),i=Bc(t),s=0;const o=()=>{r.fill(1),i.fill(0),s=0},a=(...f)=>n(i,r,...f),c=(f=Bc(0))=>{i=a(fd([0]),f),r=a(),f.length!==0&&(i=a(fd([1]),f),r=a())},u=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){r=a();const h=r.slice();d.push(h),f+=r.length}return Ie(...d)};return(f,d)=>{o(),c(f);let h;for(;!(h=d(u()));)c();return o(),h}}const I3={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"||Gi(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 Yi(t,e,n={}){const r=(i,s,o)=>{const a=I3[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}const hd=()=>{throw new Error("not implemented")};function Ac(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}}function S3(t,e){if(wd(t)>e)throw new G3({givenSize:wd(t),maxSize:e})}const In={zero:48,nine:57,A:65,F:70,a:97,f:102};function dd(t){if(t>=In.zero&&t<=In.nine)return t-In.zero;if(t>=In.A&&t<=In.F)return t-(In.A-10);if(t>=In.a&&t<=In.f)return t-(In.a-10)}function O3(t,e={}){const{dir:n,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new W3({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 Dc(t,e){if(On(t)>e)throw new F3({givenSize:On(t),maxSize:e})}function B3(t,e){if(typeof e=="number"&&e>0&&e>On(t)-1)throw new bd({offset:e,position:"start",size:On(t)})}function A3(t,e,n){if(typeof e=="number"&&typeof n=="number"&&On(t)!==n-e)throw new bd({offset:n,position:"end",size:On(t)})}function pd(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 k3({size:Math.ceil(i.length/2),targetSize:r,type:"Hex"});return`0x${i[n==="right"?"padEnd":"padStart"](r*2,"0")}`}const D3="#__bigint";function $c(t,e,n){return JSON.stringify(t,(r,i)=>typeof e=="function"?e(r,i):typeof i=="bigint"?i.toString()+D3:i,n)}const $3=new TextEncoder,T3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function P3(t,e={}){const{strict:n=!1}=e;if(!t)throw new gd(t);if(typeof t!="string")throw new gd(t);if(n&&!/^0x[0-9a-fA-F]*$/.test(t))throw new yd(t);if(!t.startsWith("0x"))throw new yd(t)}function Tc(...t){return`0x${t.reduce((e,n)=>e+n.replace("0x",""),"")}`}function Pc(t){return t instanceof Uint8Array?Xi(t):Array.isArray(t)?Xi(new Uint8Array(t)):t}function R3(t,e={}){const n=`0x${Number(t)}`;return typeof e.size=="number"?(Dc(n,e.size),Eo(n,e.size)):n}function Xi(t,e={}){let n="";for(let i=0;i<t.length;i++)n+=T3[t[i]];const r=`0x${n}`;return typeof e.size=="number"?(Dc(r,e.size),Rc(r,e.size)):r}function vo(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 U3({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?Eo(c,r):c}function N3(t,e={}){return Xi($3.encode(t),e)}function Eo(t,e){return pd(t,{dir:"left",size:e})}function Rc(t,e){return pd(t,{dir:"right",size:e})}function Sn(t,e,n,r={}){const{strict:i}=r;B3(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(n??t.length)*2)}`;return i&&A3(s,e,n),s}function On(t){return Math.ceil((t.length-2)/2)}function C3(t,e={}){const{strict:n=!1}=e;try{return P3(t,{strict:n}),!0}catch{return!1}}class U3 extends ye{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 gd extends ye{constructor(e){super(`Value \`${typeof e=="object"?$c(e):e}\` of type \`${typeof e}\` is an invalid hex type.`,{metaMessages:['Hex types must be represented as `"0x${string}"`.']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexTypeError"})}}class yd extends ye{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}class F3 extends ye{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 bd extends ye{constructor({offset:e,position:n,size:r}){super(`Slice ${n==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}class k3 extends ye{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}}const L3=new TextEncoder;function q3(t){if(!(t instanceof Uint8Array)){if(!t)throw new xo(t);if(typeof t!="object")throw new xo(t);if(!("BYTES_PER_ELEMENT"in t))throw new xo(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new xo(t)}}function M3(t){return t instanceof Uint8Array?t:typeof t=="string"?z3(t):j3(t)}function j3(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function z3(t,e={}){const{size:n}=e;let r=t;n&&(Dc(t,n),r=Rc(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=dd(i.charCodeAt(c++)),l=dd(i.charCodeAt(c++));if(u===void 0||l===void 0)throw new ye(`Invalid byte sequence ("${i[c-2]}${i[c-1]}" in "${i}").`);o[a]=u*16+l}return o}function V3(t,e={}){const{size:n}=e,r=L3.encode(t);return typeof n=="number"?(S3(r,n),K3(r,n)):r}function K3(t,e){return O3(t,{dir:"right",size:e})}function wd(t){return t.length}function H3(t){try{return q3(t),!0}catch{return!1}}class xo extends ye{constructor(e){super(`Value \`${typeof e=="object"?$c(e):e}\` of type \`${typeof e}\` is an invalid Bytes value.`,{metaMessages:["Bytes values must be of type `Bytes`."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.InvalidBytesTypeError"})}}class G3 extends ye{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 W3 extends ye{constructor({size:e,targetSize:n,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${n}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function md(t,e={}){const{as:n=typeof t=="string"?"Hex":"Bytes"}=e,r=d3(M3(t));return n==="Bytes"?r:Xi(r)}class Z3 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 Nc={checksum:new Z3(8192)}.checksum;function vd(t,e={}){const{compressed:n}=e,{prefix:r,x:i,y:s}=t;if(n===!1||typeof i=="bigint"&&typeof s=="bigint"){if(r!==4)throw new xd({prefix:r,cause:new t8});return}if(n===!0||typeof i=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new xd({prefix:r,cause:new e8});return}throw new Q3({publicKey:t})}function Y3(t){const e=(()=>{if(C3(t))return Ed(t);if(H3(t))return X3(t);const{prefix:n,x:r,y:i}=t;return typeof r=="bigint"&&typeof i=="bigint"?{prefix:n??4,x:r,y:i}:{prefix:n,x:r}})();return vd(e),e}function X3(t){return Ed(Xi(t))}function Ed(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new n8({publicKey:t});if(t.length===130){const r=BigInt(Sn(t,0,32)),i=BigInt(Sn(t,32,64));return{prefix:4,x:r,y:i}}if(t.length===132){const r=Number(Sn(t,0,1)),i=BigInt(Sn(t,1,33)),s=BigInt(Sn(t,33,65));return{prefix:r,x:i,y:s}}const e=Number(Sn(t,0,1)),n=BigInt(Sn(t,1,33));return{prefix:e,x:n}}function J3(t,e={}){vd(t);const{prefix:n,x:r,y:i}=t,{includePrefix:s=!0}=e;return Tc(s?vo(n,{size:1}):"0x",vo(r,{size:32}),typeof i=="bigint"?vo(i,{size:32}):"0x")}class Q3 extends ye{constructor({publicKey:e}){super(`Value \`${$c(e)}\` is not a valid public key.`,{metaMessages:["Public key must contain:","- an `x` and `prefix` value (compressed)","- an `x`, `y`, and `prefix` value (uncompressed)"]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidError"})}}class xd extends ye{constructor({prefix:e,cause:n}){super(`Prefix "${e}" is invalid.`,{cause:n}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class e8 extends ye{constructor(){super("Prefix must be 2 or 3 for compressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidCompressedPrefixError"})}}class t8 extends ye{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}class n8 extends ye{constructor({publicKey:e}){super(`Value \`${e}\` is an invalid public key size.`,{metaMessages:["Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).",`Received ${On(Pc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}}const r8=/^0x[a-fA-F0-9]{40}$/;function Cc(t,e={}){const{strict:n=!0}=e;if(!r8.test(t))throw new Id({address:t,cause:new o8});if(n){if(t.toLowerCase()===t)return;if(_d(t)!==t)throw new Id({address:t,cause:new a8})}}function _d(t){if(Nc.has(t))return Nc.get(t);Cc(t,{strict:!1});const e=t.substring(2).toLowerCase(),n=md(V3(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 Nc.set(t,i),i}function i8(t,e={}){const{checksum:n=!1}=e;return Cc(t),n?_d(t):t}function s8(t,e={}){const n=md(`0x${J3(t).slice(4)}`).substring(26);return i8(`0x${n}`,e)}class Id extends ye{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 o8 extends ye{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 a8 extends ye{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}const c8=/^(.*)\[([0-9]*)\]$/,u8=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/,l8=/^(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 Uc(t,e){if(t.length!==e.length)throw new h8({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(Uc.encode(i,s))}return Tc(...n)}(function(t){function e(n,r,i=!1){if(n==="address"){const c=r;return Cc(c),Eo(c.toLowerCase(),i?32:0)}if(n==="string")return N3(r);if(n==="bytes")return r;if(n==="bool")return Eo(R3(r),i?32:1);const s=n.match(l8);if(s){const[c,u,l="256"]=s,f=Number.parseInt(l,10)/8;return vo(r,{size:i?32:f,signed:u==="int"})}const o=n.match(u8);if(o){const[c,u]=o;if(Number.parseInt(u,10)!==(r.length-2)/2)throw new f8({expectedSize:Number.parseInt(u,10),value:r});return Rc(r,i?32:0)}const a=n.match(c8);if(a&&Array.isArray(r)){const[c,u]=a,l=[];for(let f=0;f<r.length;f++)l.push(e(u,r[f],!0));return l.length===0?"0x":Tc(...l)}throw new d8(n)}t.encode=e})(Uc||(Uc={}));class f8 extends ye{constructor({expectedSize:e,value:n}){super(`Size of bytes "${n}" (bytes${On(n)}) does not match expected size (bytes${e}).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.BytesSizeMismatchError"})}}class h8 extends ye{constructor({expectedLength:e,givenLength:n}){super(["ABI encoding parameters/values length mismatch.",`Expected length (parameters): ${e}`,`Given length (values): ${n}`].join(`
|
|
16
|
+
`)),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiParameters.LengthMismatchError"})}}class d8 extends ye{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 Sd extends Ec{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,jh(e);const r=lo(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),Yn(s)}update(e){return li(this),this.iHash.update(e),this}digestInto(e){li(this),wn(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 Fc=(t,e,n)=>new Sd(t,e).update(n).digest();Fc.create=(t,e)=>new Sd(t,e);const gt=BigInt(0),st=BigInt(1),Fr=BigInt(2),p8=BigInt(3),Od=BigInt(4),Bd=BigInt(5),Ad=BigInt(8);function ot(t,e){const n=t%e;return n>=gt?n:e+n}function Ct(t,e,n){let r=t;for(;e-- >gt;)r*=r,r%=n;return r}function kc(t,e){if(t===gt)throw new Error("invert: expected non-zero number");if(e<=gt)throw new Error("invert: expected positive modulus, got "+e);let n=ot(t,e),r=e,i=gt,s=st;for(;n!==gt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==st)throw new Error("invert: does not exist");return ot(i,e)}function Dd(t,e){const n=(t.ORDER+st)/Od,r=t.pow(e,n);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function g8(t,e){const n=(t.ORDER-Bd)/Ad,r=t.mul(e,Fr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Fr),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 y8(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-st,n=0;for(;e%Fr===gt;)e/=Fr,n++;let r=Fr;const i=tr(t);for(;Io(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Dd;let s=i.pow(r,e);const o=(e+st)/Fr;return function(c,u){if(c.is0(u))return u;if(Io(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const m=st<<BigInt(l-p-1),B=c.pow(f,m);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function b8(t){return t%Od===p8?Dd:t%Ad===Bd?g8:y8(t)}const w8=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function $d(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},n=w8.reduce((r,i)=>(r[i]="function",r),e);return Yi(t,n)}function _o(t,e,n){if(n<gt)throw new Error("invalid exponent, negatives unsupported");if(n===gt)return t.ONE;if(n===st)return e;let r=t.ONE,i=e;for(;n>gt;)n&st&&(r=t.mul(r,i)),i=t.sqr(i),n>>=st;return r}function kr(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 Io(t,e){const n=(t.ORDER-st)/Fr,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 Td(t,e){e!==void 0&&ui(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function tr(t,e,n=!1,r={}){if(t<=gt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:i,nByteLength:s}=Td(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:Ur(i),ZERO:gt,ONE:st,create:c=>ot(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return gt<=c&&c<t},is0:c=>c===gt,isOdd:c=>(c&st)===st,neg:c=>ot(-c,t),eql:(c,u)=>c===u,sqr:c=>ot(c*c,t),add:(c,u)=>ot(c+u,t),sub:(c,u)=>ot(c-u,t),mul:(c,u)=>ot(c*u,t),pow:(c,u)=>_o(a,c,u),div:(c,u)=>ot(c*kc(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>kc(c,t),sqrt:r.sqrt||(c=>(o||(o=b8(t)),o(a,c))),toBytes:c=>n?ld(c,s):$e(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return n?ud(c):it(c)},invertBatch:c=>kr(a,c),cmov:(c,u,l)=>l?u:c});return Object.freeze(a)}function Pd(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 Lc(t){const e=Pd(t);return e+Math.ceil(e/2)}function Rd(t,e,n=!1){const r=t.length,i=Pd(e),s=Lc(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ud(t):it(t),a=ot(o,e-st)+st;return n?ld(a,i):$e(a,i)}const Nd=BigInt(0),qc=BigInt(1);function Mc(t,e){const n=e.negate();return t?n:e}function Cd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function jc(t,e){Cd(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Ur(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Ud(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+=qc);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function m8(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 v8(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 zc=new WeakMap,Fd=new WeakMap;function Vc(t){return Fd.get(t)||1}function E8(t,e){return{constTimeNegate:Mc,hasPrecomputes(n){return Vc(n)!==1},unsafeLadder(n,r,i=t.ZERO){let s=n;for(;r>Nd;)r&qc&&(i=i.add(s)),s=s.double(),r>>=qc;return i},precomputeWindow(n,r){const{windows:i,windowSize:s}=jc(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=jc(n,e);for(let c=0;c<a.windows;c++){const{nextN:u,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:p}=Ud(i,c,a);i=u,f?o=o.add(Mc(h,r[p])):s=s.add(Mc(d,r[l]))}return{p:s,f:o}},wNAFUnsafe(n,r,i,s=t.ZERO){const o=jc(n,e);for(let a=0;a<o.windows&&i!==Nd;a++){const{nextN:c,offset:u,isZero:l,isNeg:f}=Ud(i,a,o);if(i=c,!l){const d=r[u];s=s.add(f?d.negate():d)}}return s},getPrecomputes(n,r,i){let s=zc.get(r);return s||(s=this.precomputeWindow(r,n),n!==1&&zc.set(r,i(s))),s},wNAFCached(n,r,i){const s=Vc(n);return this.wNAF(s,this.getPrecomputes(s,n,i),r)},wNAFCachedUnsafe(n,r,i,s){const o=Vc(n);return o===1?this.unsafeLadder(n,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,n,i),r,s)},setWindowSize(n,r){Cd(r,e),Fd.set(n,r),zc.delete(n)}}}function x8(t,e,n,r){m8(n,t),v8(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=Zi(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Ur(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function kd(t){return $d(t.Fp),Yi(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Td(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}function Ld(t){t.lowS!==void 0&&Wi("lowS",t.lowS),t.prehash!==void 0&&Wi("prehash",t.prehash)}function _8(t){const e=kd(t);Yi(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 I8 extends Error{constructor(e=""){super(e)}}const Bn={Err:I8,_tlv:{encode:(t,e)=>{const{Err:n}=Bn;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=wo(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?wo(i.length/2|128):"";return wo(t)+s+i+e},decode(t,e){const{Err:n}=Bn;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}=Bn;if(t<Gt)throw new e("integer: negative integers are not allowed");let n=wo(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}=Bn;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 it(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Bn,i=Ze("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}=Bn,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 Kc(t,e){return Cr($e(t,e))}const Gt=BigInt(0),ge=BigInt(1),nr=BigInt(2),Ji=BigInt(3),Hc=BigInt(4);function Gc(t){const e=_8(t),{Fp:n}=e,r=tr(e.n,e.nBitLength),i=e.toBytes||((x,_,T)=>{const P=_.toAffine();return Ie(Uint8Array.from([4]),n.toBytes(P.x),n.toBytes(P.y))}),s=e.fromBytes||(x=>{const _=x.subarray(1),T=n.fromBytes(_.subarray(0,n.BYTES)),P=n.fromBytes(_.subarray(n.BYTES,2*n.BYTES));return{x:T,y:P}});function o(x){const{a:_,b:T}=e,P=n.sqr(x),C=n.mul(P,x);return n.add(n.add(C,n.mul(x,_)),T)}function a(x,_){const T=n.sqr(_),P=o(x);return n.eql(T,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=n.mul(n.pow(e.a,Ji),Hc),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(x){return Oc(x,ge,e.n)}function f(x){const{allowedPrivateKeyLengths:_,nByteLength:T,wrapPrivateKey:P,n:C}=e;if(_&&typeof x!="bigint"){if(Gi(x)&&(x=Cr(x)),typeof x!="string"||!_.includes(x.length))throw new Error("invalid private key");x=x.padStart(T*2,"0")}let U;try{U=typeof x=="bigint"?x:it(Ze("private key",x,T))}catch{throw new Error("invalid private key, expected hex or "+T+" bytes, got "+typeof x)}return P&&(U=ot(U,C)),gi("private key",U,ge,C),U}function d(x){if(!(x instanceof g))throw new Error("ProjectivePoint expected")}const h=Ac((x,_)=>{const{px:T,py:P,pz:C}=x;if(n.eql(C,n.ONE))return{x:T,y:P};const U=x.is0();_==null&&(_=U?n.ONE:n.inv(C));const D=n.mul(T,_),j=n.mul(P,_),M=n.mul(C,_);if(U)return{x:n.ZERO,y:n.ZERO};if(!n.eql(M,n.ONE))throw new Error("invZ was invalid");return{x:D,y:j}}),p=Ac(x=>{if(x.is0()){if(e.allowInfinityPoint&&!n.is0(x.py))return;throw new Error("bad point: ZERO")}const{x:_,y:T}=x.toAffine();if(!n.isValid(_)||!n.isValid(T))throw new Error("bad point: x or y not FE");if(!a(_,T))throw new Error("bad point: equation left != right");if(!x.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(_,T,P){if(_==null||!n.isValid(_))throw new Error("x required");if(T==null||!n.isValid(T)||n.is0(T))throw new Error("y required");if(P==null||!n.isValid(P))throw new Error("z required");this.px=_,this.py=T,this.pz=P,Object.freeze(this)}static fromAffine(_){const{x:T,y:P}=_||{};if(!_||!n.isValid(T)||!n.isValid(P))throw new Error("invalid affine point");if(_ instanceof g)throw new Error("projective point not allowed");const C=U=>n.eql(U,n.ZERO);return C(T)&&C(P)?g.ZERO:new g(T,P,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(_){const T=kr(n,_.map(P=>P.pz));return _.map((P,C)=>P.toAffine(T[C])).map(g.fromAffine)}static fromHex(_){const T=g.fromAffine(s(Ze("pointHex",_)));return T.assertValidity(),T}static fromPrivateKey(_){return g.BASE.multiply(f(_))}static msm(_,T){return x8(g,r,_,T)}_setWindowSize(_){$.setWindowSize(this,_)}assertValidity(){p(this)}hasEvenY(){const{y:_}=this.toAffine();if(n.isOdd)return!n.isOdd(_);throw new Error("Field doesn't support isOdd")}equals(_){d(_);const{px:T,py:P,pz:C}=this,{px:U,py:D,pz:j}=_,M=n.eql(n.mul(T,j),n.mul(U,C)),E=n.eql(n.mul(P,j),n.mul(D,C));return M&&E}negate(){return new g(this.px,n.neg(this.py),this.pz)}double(){const{a:_,b:T}=e,P=n.mul(T,Ji),{px:C,py:U,pz:D}=this;let j=n.ZERO,M=n.ZERO,E=n.ZERO,b=n.mul(C,C),v=n.mul(U,U),y=n.mul(D,D),w=n.mul(C,U);return w=n.add(w,w),E=n.mul(C,D),E=n.add(E,E),j=n.mul(_,E),M=n.mul(P,y),M=n.add(j,M),j=n.sub(v,M),M=n.add(v,M),M=n.mul(j,M),j=n.mul(w,j),E=n.mul(P,E),y=n.mul(_,y),w=n.sub(b,y),w=n.mul(_,w),w=n.add(w,E),E=n.add(b,b),b=n.add(E,b),b=n.add(b,y),b=n.mul(b,w),M=n.add(M,b),y=n.mul(U,D),y=n.add(y,y),b=n.mul(y,w),j=n.sub(j,b),E=n.mul(y,v),E=n.add(E,E),E=n.add(E,E),new g(j,M,E)}add(_){d(_);const{px:T,py:P,pz:C}=this,{px:U,py:D,pz:j}=_;let M=n.ZERO,E=n.ZERO,b=n.ZERO;const v=e.a,y=n.mul(e.b,Ji);let w=n.mul(T,U),I=n.mul(P,D),O=n.mul(C,j),S=n.add(T,P),A=n.add(U,D);S=n.mul(S,A),A=n.add(w,I),S=n.sub(S,A),A=n.add(T,C);let R=n.add(U,j);return A=n.mul(A,R),R=n.add(w,O),A=n.sub(A,R),R=n.add(P,C),M=n.add(D,j),R=n.mul(R,M),M=n.add(I,O),R=n.sub(R,M),b=n.mul(v,A),M=n.mul(y,O),b=n.add(M,b),M=n.sub(I,b),b=n.add(I,b),E=n.mul(M,b),I=n.add(w,w),I=n.add(I,w),O=n.mul(v,O),A=n.mul(y,A),I=n.add(I,O),O=n.sub(w,O),O=n.mul(v,O),A=n.add(A,O),w=n.mul(I,A),E=n.add(E,w),w=n.mul(R,A),M=n.mul(S,M),M=n.sub(M,w),w=n.mul(S,I),b=n.mul(R,b),b=n.add(b,w),new g(M,E,b)}subtract(_){return this.add(_.negate())}is0(){return this.equals(g.ZERO)}wNAF(_){return $.wNAFCached(this,_,g.normalizeZ)}multiplyUnsafe(_){const{endo:T,n:P}=e;gi("scalar",_,Gt,P);const C=g.ZERO;if(_===Gt)return C;if(this.is0()||_===ge)return this;if(!T||$.hasPrecomputes(this))return $.wNAFCachedUnsafe(this,_,g.normalizeZ);let{k1neg:U,k1:D,k2neg:j,k2:M}=T.splitScalar(_),E=C,b=C,v=this;for(;D>Gt||M>Gt;)D&ge&&(E=E.add(v)),M&ge&&(b=b.add(v)),v=v.double(),D>>=ge,M>>=ge;return U&&(E=E.negate()),j&&(b=b.negate()),b=new g(n.mul(b.px,T.beta),b.py,b.pz),E.add(b)}multiply(_){const{endo:T,n:P}=e;gi("scalar",_,ge,P);let C,U;if(T){const{k1neg:D,k1:j,k2neg:M,k2:E}=T.splitScalar(_);let{p:b,f:v}=this.wNAF(j),{p:y,f:w}=this.wNAF(E);b=$.constTimeNegate(D,b),y=$.constTimeNegate(M,y),y=new g(n.mul(y.px,T.beta),y.py,y.pz),C=b.add(y),U=v.add(w)}else{const{p:D,f:j}=this.wNAF(_);C=D,U=j}return g.normalizeZ([C,U])[0]}multiplyAndAddUnsafe(_,T,P){const C=g.BASE,U=(j,M)=>M===Gt||M===ge||!j.equals(C)?j.multiplyUnsafe(M):j.multiply(M),D=U(this,T).add(U(_,P));return D.is0()?void 0:D}toAffine(_){return h(this,_)}isTorsionFree(){const{h:_,isTorsionFree:T}=e;if(_===ge)return!0;if(T)return T(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:_,clearCofactor:T}=e;return _===ge?this:T?T(g,this):this.multiplyUnsafe(e.h)}toRawBytes(_=!0){return Wi("isCompressed",_),this.assertValidity(),i(g,this,_)}toHex(_=!0){return Wi("isCompressed",_),Cr(this.toRawBytes(_))}}g.BASE=new g(e.Gx,e.Gy,n.ONE),g.ZERO=new g(n.ZERO,n.ONE,n.ZERO);const{endo:m,nBitLength:B}=e,$=E8(g,m?Math.ceil(B/2):B);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:f,weierstrassEquation:o,isWithinCurveOrder:l}}function S8(t){const e=kd(t);return Yi(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function O8(t){const e=S8(t),{Fp:n,n:r,nByteLength:i,nBitLength:s}=e,o=n.BYTES+1,a=2*n.BYTES+1;function c(y){return ot(y,r)}function u(y){return kc(y,r)}const{ProjectivePoint:l,normPrivateKeyToScalar:f,weierstrassEquation:d,isWithinCurveOrder:h}=Gc({...e,toBytes(y,w,I){const O=w.toAffine(),S=n.toBytes(O.x),A=Ie;return Wi("isCompressed",I),I?A(Uint8Array.from([w.hasEvenY()?2:3]),S):A(Uint8Array.from([4]),S,n.toBytes(O.y))},fromBytes(y){const w=y.length,I=y[0],O=y.subarray(1);if(w===o&&(I===2||I===3)){const S=it(O);if(!Oc(S,ge,n.ORDER))throw new Error("Point is not on curve");const A=d(S);let R;try{R=n.sqrt(A)}catch(L){const N=L instanceof Error?": "+L.message:"";throw new Error("Point is not on curve"+N)}const k=(R&ge)===ge;return(I&1)===1!==k&&(R=n.neg(R)),{x:S,y:R}}else if(w===a&&I===4){const S=n.fromBytes(O.subarray(0,n.BYTES)),A=n.fromBytes(O.subarray(n.BYTES,2*n.BYTES));return{x:S,y:A}}else{const S=o,A=a;throw new Error("invalid Point, expected length of "+S+", or uncompressed "+A+", got "+w)}}});function p(y){const w=r>>ge;return y>w}function g(y){return p(y)?c(-y):y}const m=(y,w,I)=>it(y.slice(w,I));class B{constructor(w,I,O){gi("r",w,ge,r),gi("s",I,ge,r),this.r=w,this.s=I,O!=null&&(this.recovery=O),Object.freeze(this)}static fromCompact(w){const I=i;return w=Ze("compactSignature",w,I*2),new B(m(w,0,I),m(w,I,2*I))}static fromDER(w){const{r:I,s:O}=Bn.toSig(Ze("DER",w));return new B(I,O)}assertValidity(){}addRecoveryBit(w){return new B(this.r,this.s,w)}recoverPublicKey(w){const{r:I,s:O,recovery:S}=this,A=C(Ze("msgHash",w));if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");const R=S===2||S===3?I+e.n:I;if(R>=n.ORDER)throw new Error("recovery id 2 or 3 invalid");const k=(S&1)===0?"02":"03",F=l.fromHex(k+Kc(R,n.BYTES)),L=u(R),N=c(-A*L),q=c(O*L),z=l.BASE.multiplyAndAddUnsafe(F,N,q);if(!z)throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new B(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return mo(this.toDERHex())}toDERHex(){return Bn.hexFromSig(this)}toCompactRawBytes(){return mo(this.toCompactHex())}toCompactHex(){const w=i;return Kc(this.r,w)+Kc(this.s,w)}}const $={isValidPrivateKey(y){try{return f(y),!0}catch{return!1}},normPrivateKeyToScalar:f,randomPrivateKey:()=>{const y=Lc(e.n);return Rd(e.randomBytes(y),e.n)},precompute(y=8,w=l.BASE){return w._setWindowSize(y),w.multiply(BigInt(3)),w}};function x(y,w=!0){return l.fromPrivateKey(y).toRawBytes(w)}function _(y){if(typeof y=="bigint")return!1;if(y instanceof l)return!0;const I=Ze("key",y).length,O=n.BYTES,S=O+1,A=2*O+1;if(!(e.allowedPrivateKeyLengths||i===S))return I===S||I===A}function T(y,w,I=!0){if(_(y)===!0)throw new Error("first arg must be private key");if(_(w)===!1)throw new Error("second arg must be public key");return l.fromHex(w).multiply(f(y)).toRawBytes(I)}const P=e.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const w=it(y),I=y.length*8-s;return I>0?w>>BigInt(I):w},C=e.bits2int_modN||function(y){return c(P(y))},U=Ur(s);function D(y){return gi("num < 2^"+s,y,Gt,U),$e(y,i)}function j(y,w,I=M){if(["recovered","canonical"].some(K=>K in I))throw new Error("sign() legacy options not supported");const{hash:O,randomBytes:S}=e;let{lowS:A,prehash:R,extraEntropy:k}=I;A==null&&(A=!0),y=Ze("msgHash",y),Ld(I),R&&(y=Ze("prehashed msgHash",O(y)));const F=C(y),L=f(w),N=[D(L),D(F)];if(k!=null&&k!==!1){const K=k===!0?S(n.BYTES):k;N.push(Ze("extraEntropy",K))}const q=Ie(...N),z=F;function W(K){const Z=P(K);if(!h(Z))return;const Q=u(Z),ee=l.BASE.multiply(Z).toAffine(),ie=c(ee.x);if(ie===Gt)return;const he=c(Q*c(z+ie*L));if(he===Gt)return;let Ee=(ee.x===ie?0:2)|Number(ee.y&ge),zn=he;return A&&p(he)&&(zn=g(he),Ee^=1),new B(ie,zn,Ee)}return{seed:q,k2sig:W}}const M={lowS:e.lowS,prehash:!1},E={lowS:e.lowS,prehash:!1};function b(y,w,I=M){const{seed:O,k2sig:S}=j(y,w,I),A=e;return _3(A.hash.outputLen,A.nByteLength,A.hmac)(O,S)}l.BASE._setWindowSize(8);function v(y,w,I,O=E){const S=y;w=Ze("msgHash",w),I=Ze("publicKey",I);const{lowS:A,prehash:R,format:k}=O;if(Ld(O),"strict"in O)throw new Error("options.strict was renamed to lowS");if(k!==void 0&&k!=="compact"&&k!=="der")throw new Error("format must be compact or der");const F=typeof S=="string"||Gi(S),L=!F&&!k&&typeof S=="object"&&S!==null&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!F&&!L)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let N,q;try{if(L&&(N=new B(S.r,S.s)),F){try{k!=="compact"&&(N=B.fromDER(S))}catch(Ee){if(!(Ee instanceof Bn.Err))throw Ee}!N&&k!=="der"&&(N=B.fromCompact(S))}q=l.fromHex(I)}catch{return!1}if(!N||A&&N.hasHighS())return!1;R&&(w=e.hash(w));const{r:z,s:W}=N,K=C(w),Z=u(W),Q=c(K*Z),ee=c(z*Z),ie=l.BASE.multiplyAndAddUnsafe(q,Q,ee)?.toAffine();return ie?c(ie.x)===z:!1}return{CURVE:e,getPublicKey:x,getSharedSecret:T,sign:b,verify:v,ProjectivePoint:l,Signature:B,utils:$}}function B8(t,e){const n=t.ORDER;let r=Gt;for(let p=n-ge;p%nr===Gt;p/=nr)r+=ge;const i=r,s=nr<<i-ge-ge,o=s*nr,a=(n-ge)/o,c=(a-ge)/nr,u=o-ge,l=s,f=t.pow(e,a),d=t.pow(e,(a+ge)/nr);let h=(p,g)=>{let m=f,B=t.pow(g,u),$=t.sqr(B);$=t.mul($,g);let x=t.mul(p,$);x=t.pow(x,c),x=t.mul(x,B),B=t.mul(x,g),$=t.mul(x,p);let _=t.mul($,B);x=t.pow(_,l);let T=t.eql(x,t.ONE);B=t.mul($,d),x=t.mul(_,m),$=t.cmov(B,$,T),_=t.cmov(x,_,T);for(let P=i;P>ge;P--){let C=P-nr;C=nr<<C-ge;let U=t.pow(_,C);const D=t.eql(U,t.ONE);B=t.mul($,m),m=t.mul(m,m),U=t.mul(_,m),$=t.cmov(B,$,D),_=t.cmov(U,_,D)}return{isValid:T,value:$}};if(t.ORDER%Hc===Ji){const p=(t.ORDER-Ji)/Hc,g=t.sqrt(t.neg(e));h=(m,B)=>{let $=t.sqr(B);const x=t.mul(m,B);$=t.mul($,x);let _=t.pow($,p);_=t.mul(_,x);const T=t.mul(_,g),P=t.mul(t.sqr(_),B),C=t.eql(P,m);let U=t.cmov(T,_,C);return{isValid:C,value:U}}}return h}function qd(t,e){if($d(t),!t.isValid(e.A)||!t.isValid(e.B)||!t.isValid(e.Z))throw new Error("mapToCurveSimpleSWU: invalid opts");const n=B8(t,e.Z);if(!t.isOdd)throw new Error("Fp.isOdd is not implemented!");return r=>{let i,s,o,a,c,u,l,f;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:d,value:h}=n(s,u);f=t.mul(i,r),f=t.mul(f,h),l=t.cmov(l,o,d),f=t.cmov(f,h,d);const p=t.isOdd(r)===t.isOdd(f);f=t.cmov(t.neg(f),f,p);const g=kr(t,[a],!0)[0];return l=t.mul(l,g),{x:l,y:f}}}function A8(t){return{hash:t,hmac:(e,...n)=>Fc(t,e,vn(...n)),randomBytes:ho}}function So(t,e){const n=r=>O8({...t,...A8(r)});return{...n(e),create:n}}const D8=it;function rr(t,e){if(Qi(t),Qi(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 $8(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 Qi(t){if(!Number.isSafeInteger(t))throw new Error("number expected")}function T8(t,e,n,r){er(t),er(e),Qi(n),e.length>255&&(e=r(Ie(Ic("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=Ie(e,rr(e.length,1)),c=rr(0,s),u=rr(n,2),l=new Array(o),f=r(Ie(c,t,u,rr(0,1),a));l[0]=r(Ie(f,rr(1,1),a));for(let h=1;h<=o;h++){const p=[$8(f,l[h-1]),rr(h+1,1),a];l[h]=r(Ie(...p))}return Ie(...l).slice(0,n)}function P8(t,e,n,r,i){if(er(t),er(e),Qi(n),e.length>255){const s=Math.ceil(2*r/8);e=i.create({dkLen:s}).update(Ic("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(rr(n,2)).update(e).update(rr(e.length,1)).digest()}function Md(t,e,n){Yi(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;er(t),Qi(e);const u=typeof c=="string"?Ic(c):c,l=r.toString(2).length,f=Math.ceil((l+i)/8),d=e*s*f;let h;if(a==="xmd")h=T8(t,u,d,o);else if(a==="xof")h=P8(t,u,d,i,o);else if(a==="_internal_pass")h=t;else throw new Error('expand must be "xmd" or "xof"');const p=new Array(e);for(let g=0;g<e;g++){const m=new Array(s);for(let B=0;B<s;B++){const $=f*(B+g*s),x=h.subarray($,$+f);m[B]=ot(D8(x),r)}p[g]=m}return p}function jd(t,e){const n=e.map(r=>Array.from(r).reverse());return(r,i)=>{const[s,o,a,c]=n.map(f=>f.reduce((d,h)=>t.add(t.mul(d,r),h))),[u,l]=kr(t,[o,c],!0);return r=t.mul(s,u),i=t.mul(i,t.mul(a,l)),{x:r,y:i}}}function zd(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=Md(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=Md(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 Vd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Kd=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),R8=BigInt(0),N8=BigInt(1),Wc=BigInt(2),Hd=(t,e)=>(t+e/Wc)/e;function C8(t){const e=Vd,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=Ct(l,n,e)*l%e,d=Ct(f,n,e)*l%e,h=Ct(d,Wc,e)*u%e,p=Ct(h,i,e)*h%e,g=Ct(p,s,e)*p%e,m=Ct(g,a,e)*g%e,B=Ct(m,c,e)*m%e,$=Ct(B,a,e)*g%e,x=Ct($,n,e)*l%e,_=Ct(x,o,e)*p%e,T=Ct(_,r,e)*u%e,P=Ct(T,Wc,e);if(!Zc.eql(Zc.sqr(P),t))throw new Error("Cannot find square root");return P}const Zc=tr(Vd,void 0,void 0,{sqrt:C8}),U8=So({a:R8,b:BigInt(7),Fp:Zc,n:Kd,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Kd,n=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-N8*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=n,o=BigInt("0x100000000000000000000000000000000"),a=Hd(s*t,e),c=Hd(-r*t,e);let u=ot(t-a*n-c*i,e),l=ot(-a*r-c*s,e);const f=u>o,d=l>o;if(f&&(u=e-u),d&&(l=e-l),u>o||l>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}}},pi);function F8(t){if(t.length!==130&&t.length!==132)throw new L8({signature:t});const e=BigInt(Sn(t,0,32)),n=BigInt(Sn(t,32,64)),r=(()=>{const i=+`0x${t.slice(130)}`;if(!Number.isNaN(i))try{return k8(i)}catch{throw new q8({value:i})}})();return typeof r>"u"?{r:e,s:n}:{r:e,s:n,yParity:r}}function k8(t){if(t===0||t===27)return 0;if(t===1||t===28)return 1;if(t>=35)return t%2===0?1:0;throw new M8({value:t})}class L8 extends ye{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${On(Pc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class q8 extends ye{constructor({value:e}){super(`Value \`${e}\` is an invalid y-parity value. Y-parity must be 0 or 1.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidYParityError"})}}class M8 extends ye{constructor({value:e}){super(`Value \`${e}\` is an invalid v value. v must be 27, 28 or >=35.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidVError"})}}Object.freeze({1:0n,2:1n,3:2n,4:3n,5:4n,6:5n,7:6n,8:7n,9:8n,A:9n,B:10n,C:11n,D:12n,E:13n,F:14n,G:15n,H:16n,J:17n,K:18n,L:19n,M:20n,N:21n,P:22n,Q:23n,R:24n,S:25n,T:26n,U:27n,V:28n,W:29n,X:30n,Y:31n,Z:32n,a:33n,b:34n,c:35n,d:36n,e:37n,f:38n,g:39n,h:40n,i:41n,j:42n,k:43n,m:44n,n:45n,o:46n,p:47n,q:48n,r:49n,s:50n,t:51n,u:52n,v:53n,w:54n,x:55n,y:56n,z:57n}),Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[e,t.charCodeAt(0)]),{...Object.fromEntries(Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/").map((t,e)=>[t.charCodeAt(0),e]))},En.slice();const j8=BigInt(0),Oo=BigInt(1),Gd=BigInt(2),yi=BigInt(3);function z8(t){const e=[];for(;t>Oo;t>>=Oo)(t&Oo)===j8?e.unshift(0):(t&yi)===yi?(e.unshift(-1),t+=Oo):e.unshift(1);return e}function V8(t){const{Fp:e,Fr:n,Fp2:r,Fp6:i,Fp12:s}=t.fields,o=t.params.xNegative,a=t.params.twistType,c=Gc({n:n.ORDER,...t.G1}),u=Object.assign(c,zd(c.ProjectivePoint,t.G1.mapToCurve,{...t.htfDefaults,...t.G1.htfDefaults})),l=Gc({n:n.ORDER,...t.G2}),f=Object.assign(l,zd(l.ProjectivePoint,t.G2.mapToCurve,{...t.htfDefaults,...t.G2.htfDefaults}));let d;if(a==="multiplicative")d=(F,L,N,q,z,W)=>s.mul014(q,F,r.mul(L,z),r.mul(N,W));else if(a==="divisive")d=(F,L,N,q,z,W)=>s.mul034(q,r.mul(N,W),r.mul(L,z),F);else throw new Error("bls: unknown twist type");const h=r.div(r.ONE,r.mul(r.ONE,Gd));function p(F,L,N,q){const z=r.sqr(N),W=r.sqr(q),K=r.mulByB(r.mul(W,yi)),Z=r.mul(K,yi),Q=r.sub(r.sub(r.sqr(r.add(N,q)),W),z),ee=r.sub(K,z),ie=r.mul(r.sqr(L),yi),he=r.neg(Q);return F.push([ee,ie,he]),L=r.mul(r.mul(r.mul(r.sub(z,Z),L),N),h),N=r.sub(r.sqr(r.mul(r.add(z,Z),h)),r.mul(r.sqr(K),yi)),q=r.mul(z,Q),{Rx:L,Ry:N,Rz:q}}function g(F,L,N,q,z,W){const K=r.sub(N,r.mul(W,q)),Z=r.sub(L,r.mul(z,q)),Q=r.sub(r.mul(K,z),r.mul(Z,W)),ee=r.neg(K),ie=Z;F.push([Q,ee,ie]);const he=r.sqr(Z),Ee=r.mul(he,Z),zn=r.mul(he,L),Aa=r.add(r.sub(Ee,r.mul(zn,Gd)),r.mul(r.sqr(K),q));return L=r.mul(Z,Aa),N=r.sub(r.mul(r.sub(zn,Aa),K),r.mul(Ee,N)),q=r.mul(q,Ee),{Rx:L,Ry:N,Rz:q}}const m=z8(t.params.ateLoopSize),B=Ac(F=>{const L=F,{x:N,y:q}=L.toAffine(),z=N,W=q,K=r.neg(q);let Z=z,Q=W,ee=r.ONE;const ie=[];for(const he of m){const Ee=[];({Rx:Z,Ry:Q,Rz:ee}=p(Ee,Z,Q,ee)),he&&({Rx:Z,Ry:Q,Rz:ee}=g(Ee,Z,Q,ee,z,he===-1?K:W)),ie.push(Ee)}if(t.postPrecompute){const he=ie[ie.length-1];t.postPrecompute(Z,Q,ee,z,W,g.bind(null,he))}return ie});function $(F,L=!1){let N=s.ONE;if(F.length){const q=F[0][0].length;for(let z=0;z<q;z++){N=s.sqr(N);for(const[W,K,Z]of F)for(const[Q,ee,ie]of W[z])N=d(Q,ee,ie,N,K,Z)}}return o&&(N=s.conjugate(N)),L?s.finalExponentiate(N):N}function x(F,L=!0){const N=[];u.ProjectivePoint.normalizeZ(F.map(({g1:q})=>q)),f.ProjectivePoint.normalizeZ(F.map(({g2:q})=>q));for(const{g1:q,g2:z}of F){if(q.equals(u.ProjectivePoint.ZERO)||z.equals(f.ProjectivePoint.ZERO))throw new Error("pairing is not available for ZERO point");q.assertValidity(),z.assertValidity();const W=q.toAffine();N.push([B(z),W.x,W.y])}return $(N,L)}function _(F,L,N=!0){return x([{g1:F,g2:L}],N)}const T={randomPrivateKey:()=>{const F=Lc(n.ORDER);return Rd(t.randomBytes(F),n.ORDER)},calcPairingPrecomputes:B},{ShortSignature:P}=t.G1,{Signature:C}=t.G2;function U(F){return F instanceof u.ProjectivePoint?F:u.ProjectivePoint.fromHex(F)}function D(F,L){return F instanceof u.ProjectivePoint?F:u.hashToCurve(Ze("point",F),L)}function j(F){return F instanceof f.ProjectivePoint?F:C.fromHex(F)}function M(F,L){return F instanceof f.ProjectivePoint?F:f.hashToCurve(Ze("point",F),L)}function E(F){return u.ProjectivePoint.fromPrivateKey(F).toRawBytes(!0)}function b(F){return f.ProjectivePoint.fromPrivateKey(F).toRawBytes(!0)}function v(F,L,N){const q=M(F,N);q.assertValidity();const z=q.multiply(u.normPrivateKeyToScalar(L));return F instanceof f.ProjectivePoint?z:C.toRawBytes(z)}function y(F,L,N){const q=D(F,N);q.assertValidity();const z=q.multiply(u.normPrivateKeyToScalar(L));return F instanceof u.ProjectivePoint?z:P.toRawBytes(z)}function w(F,L,N,q){const z=U(N),W=M(L,q),K=u.ProjectivePoint.BASE,Z=j(F),Q=x([{g1:z.negate(),g2:W},{g1:K,g2:Z}]);return s.eql(Q,s.ONE)}function I(F,L,N,q){const z=j(N),W=D(L,q),K=f.ProjectivePoint.BASE,Z=U(F),Q=x([{g1:W,g2:z},{g1:Z,g2:K.negate()}]);return s.eql(Q,s.ONE)}function O(F){if(!Array.isArray(F)||F.length===0)throw new Error("expected non-empty array")}function S(F){O(F);const N=F.map(U).reduce((q,z)=>q.add(z),u.ProjectivePoint.ZERO);return F[0]instanceof u.ProjectivePoint?(N.assertValidity(),N):N.toRawBytes(!0)}function A(F){O(F);const N=F.map(j).reduce((q,z)=>q.add(z),f.ProjectivePoint.ZERO);return F[0]instanceof f.ProjectivePoint?(N.assertValidity(),N):C.toRawBytes(N)}function R(F){O(F);const N=F.map(U).reduce((q,z)=>q.add(z),u.ProjectivePoint.ZERO);return F[0]instanceof u.ProjectivePoint?(N.assertValidity(),N):P.toRawBytes(N)}function k(F,L,N,q){if(O(L),N.length!==L.length)throw new Error("amount of public keys and messages should be equal");const z=j(F),W=L.map(ee=>M(ee,q)),K=N.map(U),Z=new Map;for(let ee=0;ee<K.length;ee++){const ie=K[ee],he=W[ee];let Ee=Z.get(he);Ee===void 0&&(Ee=[],Z.set(he,Ee)),Ee.push(ie)}const Q=[];try{for(const[ee,ie]of Z){const he=ie.reduce((Ee,zn)=>Ee.add(zn));Q.push({g1:he,g2:ee})}return Q.push({g1:u.ProjectivePoint.BASE.negate(),g2:z}),s.eql(x(Q),s.ONE)}catch{return!1}}return u.ProjectivePoint.BASE._setWindowSize(4),{getPublicKey:E,getPublicKeyForShortSignatures:b,sign:v,signShortSignature:y,verify:w,verifyBatch:k,verifyShortSignature:I,aggregatePublicKeys:S,aggregateSignatures:A,aggregateShortSignatures:R,millerLoopBatch:$,pairing:_,pairingBatch:x,G1:u,G2:f,Signature:C,ShortSignature:P,fields:{Fr:n,Fp:e,Fp2:r,Fp6:i,Fp12:s},params:{ateLoopSize:t.params.ateLoopSize,r:t.params.r,G1b:t.G1.b,G2b:t.G2.b},utils:T}}const K8=BigInt(0),bi=BigInt(1),An=BigInt(2),Wd=BigInt(3);function Yc(t,e,n,r,i=1,s){const o=BigInt(s===void 0?r:s),a=n**BigInt(r),c=[];for(let u=0;u<i;u++){const l=BigInt(u+1),f=[];for(let d=0,h=bi;d<r;d++){const p=(l*h-l)/o%a;f.push(t.pow(e,p)),h*=n}c.push(f)}return c}function H8(t,e,n){const r=e.pow(n,(t.ORDER-bi)/Wd),i=e.pow(n,(t.ORDER-bi)/An);function s(d,h){const p=e.mul(e.frobeniusMap(d,1),r),g=e.mul(e.frobeniusMap(h,1),i);return[p,g]}const o=e.pow(n,(t.ORDER**An-bi)/Wd),a=e.pow(n,(t.ORDER**An-bi)/An);if(!e.eql(a,e.neg(e.ONE)))throw new Error("psiFrobenius: PSI2_Y!==-1");function c(d,h){return[e.mul(d,o),e.neg(h)]}const u=d=>(h,p)=>{const g=p.toAffine(),m=d(g.x,g.y);return h.fromAffine({x:m[0],y:m[1]})},l=u(s),f=u(c);return{psi:s,psi2:c,G2psi:l,G2psi2:f,PSI_X:r,PSI_Y:i,PSI2_X:o,PSI2_Y:a}}function G8(t){const{ORDER:e}=t,n=tr(e),r=n.create(t.NONRESIDUE||BigInt(-1)),i=n.div(n.ONE,An),s=Yc(n,r,n.ORDER,2)[0],o=({c0:E,c1:b},{c0:v,c1:y})=>({c0:n.add(E,v),c1:n.add(b,y)}),a=({c0:E,c1:b},{c0:v,c1:y})=>({c0:n.sub(E,v),c1:n.sub(b,y)}),c=({c0:E,c1:b},v)=>{if(typeof v=="bigint")return{c0:n.mul(E,v),c1:n.mul(b,v)};const{c0:y,c1:w}=v;let I=n.mul(E,y),O=n.mul(b,w);const S=n.sub(I,O),A=n.sub(n.mul(n.add(E,b),n.add(y,w)),n.add(I,O));return{c0:S,c1:A}},u=({c0:E,c1:b})=>{const v=n.add(E,b),y=n.sub(E,b),w=n.add(E,E);return{c0:n.mul(v,y),c1:n.mul(w,b)}},l=E=>{if(E.length!==2)throw new Error("invalid tuple");const b=E.map(v=>n.create(v));return{c0:b[0],c1:b[1]}},f=e*e,d=l(t.FP2_NONRESIDUE),h={ORDER:f,isLE:n.isLE,NONRESIDUE:d,BITS:Zi(f),BYTES:Math.ceil(Zi(f)/8),MASK:Ur(Zi(f)),ZERO:{c0:n.ZERO,c1:n.ZERO},ONE:{c0:n.ONE,c1:n.ZERO},create:E=>E,isValid:({c0:E,c1:b})=>typeof E=="bigint"&&typeof b=="bigint",is0:({c0:E,c1:b})=>n.is0(E)&&n.is0(b),eql:({c0:E,c1:b},{c0:v,c1:y})=>n.eql(E,v)&&n.eql(b,y),neg:({c0:E,c1:b})=>({c0:n.neg(E),c1:n.neg(b)}),pow:(E,b)=>_o(h,E,b),invertBatch:E=>kr(h,E),add:o,sub:a,mul:c,sqr:u,addN:o,subN:a,mulN:c,sqrN:u,div:(E,b)=>h.mul(E,typeof b=="bigint"?n.inv(n.create(b)):h.inv(b)),inv:({c0:E,c1:b})=>{const v=n.inv(n.create(E*E+b*b));return{c0:n.mul(v,n.create(E)),c1:n.mul(v,n.create(-b))}},sqrt:E=>{if(t.Fp2sqrt)return t.Fp2sqrt(E);const{c0:b,c1:v}=E;if(n.is0(v))return Io(n,b)===1?h.create({c0:n.sqrt(b),c1:n.ZERO}):h.create({c0:n.ZERO,c1:n.sqrt(n.div(b,r))});const y=n.sqrt(n.sub(n.sqr(b),n.mul(n.sqr(v),r)));let w=n.mul(n.add(y,b),i);Io(n,w)===-1&&(w=n.sub(w,y));const O=n.sqrt(w),S=h.create({c0:O,c1:n.div(n.mul(v,i),O)});if(!h.eql(h.sqr(S),E))throw new Error("Cannot find square root");const A=S,R=h.neg(A),{re:k,im:F}=h.reim(A),{re:L,im:N}=h.reim(R);return F>N||F===N&&k>L?A:R},isOdd:E=>{const{re:b,im:v}=h.reim(E),y=b%An,w=b===K8,I=v%An;return BigInt(y||w&&I)==bi},fromBytes(E){if(E.length!==h.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:n.fromBytes(E.subarray(0,n.BYTES)),c1:n.fromBytes(E.subarray(n.BYTES))}},toBytes:({c0:E,c1:b})=>Ie(n.toBytes(E),n.toBytes(b)),cmov:({c0:E,c1:b},{c0:v,c1:y},w)=>({c0:n.cmov(E,v,w),c1:n.cmov(b,y,w)}),reim:({c0:E,c1:b})=>({re:E,im:b}),mulByNonresidue:({c0:E,c1:b})=>h.mul({c0:E,c1:b},d),mulByB:t.Fp2mulByB,fromBigTuple:l,frobeniusMap:({c0:E,c1:b},v)=>({c0:E,c1:n.mul(b,s[v%2])})},p=({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>({c0:h.add(E,y),c1:h.add(b,w),c2:h.add(v,I)}),g=({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>({c0:h.sub(E,y),c1:h.sub(b,w),c2:h.sub(v,I)}),m=({c0:E,c1:b,c2:v},y)=>{if(typeof y=="bigint")return{c0:h.mul(E,y),c1:h.mul(b,y),c2:h.mul(v,y)};const{c0:w,c1:I,c2:O}=y,S=h.mul(E,w),A=h.mul(b,I),R=h.mul(v,O);return{c0:h.add(S,h.mulByNonresidue(h.sub(h.mul(h.add(b,v),h.add(I,O)),h.add(A,R)))),c1:h.add(h.sub(h.mul(h.add(E,b),h.add(w,I)),h.add(S,A)),h.mulByNonresidue(R)),c2:h.sub(h.add(A,h.mul(h.add(E,v),h.add(w,O))),h.add(S,R))}},B=({c0:E,c1:b,c2:v})=>{let y=h.sqr(E),w=h.mul(h.mul(E,b),An),I=h.mul(h.mul(b,v),An),O=h.sqr(v);return{c0:h.add(h.mulByNonresidue(I),y),c1:h.add(h.mulByNonresidue(O),w),c2:h.sub(h.sub(h.add(h.add(w,h.sqr(h.add(h.sub(E,b),v))),I),y),O)}},[$,x]=Yc(h,d,n.ORDER,6,2,3),_={ORDER:h.ORDER,isLE:h.isLE,BITS:3*h.BITS,BYTES:3*h.BYTES,MASK:Ur(3*h.BITS),ZERO:{c0:h.ZERO,c1:h.ZERO,c2:h.ZERO},ONE:{c0:h.ONE,c1:h.ZERO,c2:h.ZERO},create:E=>E,isValid:({c0:E,c1:b,c2:v})=>h.isValid(E)&&h.isValid(b)&&h.isValid(v),is0:({c0:E,c1:b,c2:v})=>h.is0(E)&&h.is0(b)&&h.is0(v),neg:({c0:E,c1:b,c2:v})=>({c0:h.neg(E),c1:h.neg(b),c2:h.neg(v)}),eql:({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I})=>h.eql(E,y)&&h.eql(b,w)&&h.eql(v,I),sqrt:hd,div:(E,b)=>_.mul(E,typeof b=="bigint"?n.inv(n.create(b)):_.inv(b)),pow:(E,b)=>_o(_,E,b),invertBatch:E=>kr(_,E),add:p,sub:g,mul:m,sqr:B,addN:p,subN:g,mulN:m,sqrN:B,inv:({c0:E,c1:b,c2:v})=>{let y=h.sub(h.sqr(E),h.mulByNonresidue(h.mul(v,b))),w=h.sub(h.mulByNonresidue(h.sqr(v)),h.mul(E,b)),I=h.sub(h.sqr(b),h.mul(E,v)),O=h.inv(h.add(h.mulByNonresidue(h.add(h.mul(v,w),h.mul(b,I))),h.mul(E,y)));return{c0:h.mul(O,y),c1:h.mul(O,w),c2:h.mul(O,I)}},fromBytes:E=>{if(E.length!==_.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:h.fromBytes(E.subarray(0,h.BYTES)),c1:h.fromBytes(E.subarray(h.BYTES,2*h.BYTES)),c2:h.fromBytes(E.subarray(2*h.BYTES))}},toBytes:({c0:E,c1:b,c2:v})=>Ie(h.toBytes(E),h.toBytes(b),h.toBytes(v)),cmov:({c0:E,c1:b,c2:v},{c0:y,c1:w,c2:I},O)=>({c0:h.cmov(E,y,O),c1:h.cmov(b,w,O),c2:h.cmov(v,I,O)}),fromBigSix:E=>{if(!Array.isArray(E)||E.length!==6)throw new Error("invalid Fp6 usage");return{c0:h.fromBigTuple(E.slice(0,2)),c1:h.fromBigTuple(E.slice(2,4)),c2:h.fromBigTuple(E.slice(4,6))}},frobeniusMap:({c0:E,c1:b,c2:v},y)=>({c0:h.frobeniusMap(E,y),c1:h.mul(h.frobeniusMap(b,y),$[y%6]),c2:h.mul(h.frobeniusMap(v,y),x[y%6])}),mulByFp2:({c0:E,c1:b,c2:v},y)=>({c0:h.mul(E,y),c1:h.mul(b,y),c2:h.mul(v,y)}),mulByNonresidue:({c0:E,c1:b,c2:v})=>({c0:h.mulByNonresidue(v),c1:E,c2:b}),mul1:({c0:E,c1:b,c2:v},y)=>({c0:h.mulByNonresidue(h.mul(v,y)),c1:h.mul(E,y),c2:h.mul(b,y)}),mul01({c0:E,c1:b,c2:v},y,w){let I=h.mul(E,y),O=h.mul(b,w);return{c0:h.add(h.mulByNonresidue(h.sub(h.mul(h.add(b,v),w),O)),I),c1:h.sub(h.sub(h.mul(h.add(y,w),h.add(E,b)),I),O),c2:h.add(h.sub(h.mul(h.add(E,v),y),I),O)}}},T=Yc(h,d,n.ORDER,12,1,6)[0],P=({c0:E,c1:b},{c0:v,c1:y})=>({c0:_.add(E,v),c1:_.add(b,y)}),C=({c0:E,c1:b},{c0:v,c1:y})=>({c0:_.sub(E,v),c1:_.sub(b,y)}),U=({c0:E,c1:b},v)=>{if(typeof v=="bigint")return{c0:_.mul(E,v),c1:_.mul(b,v)};let{c0:y,c1:w}=v,I=_.mul(E,y),O=_.mul(b,w);return{c0:_.add(I,_.mulByNonresidue(O)),c1:_.sub(_.mul(_.add(E,b),_.add(y,w)),_.add(I,O))}},D=({c0:E,c1:b})=>{let v=_.mul(E,b);return{c0:_.sub(_.sub(_.mul(_.add(_.mulByNonresidue(b),E),_.add(E,b)),v),_.mulByNonresidue(v)),c1:_.add(v,v)}};function j(E,b){const v=h.sqr(E),y=h.sqr(b);return{first:h.add(h.mulByNonresidue(y),v),second:h.sub(h.sub(h.sqr(h.add(E,b)),v),y)}}const M={ORDER:h.ORDER,isLE:_.isLE,BITS:2*_.BITS,BYTES:2*_.BYTES,MASK:Ur(2*_.BITS),ZERO:{c0:_.ZERO,c1:_.ZERO},ONE:{c0:_.ONE,c1:_.ZERO},create:E=>E,isValid:({c0:E,c1:b})=>_.isValid(E)&&_.isValid(b),is0:({c0:E,c1:b})=>_.is0(E)&&_.is0(b),neg:({c0:E,c1:b})=>({c0:_.neg(E),c1:_.neg(b)}),eql:({c0:E,c1:b},{c0:v,c1:y})=>_.eql(E,v)&&_.eql(b,y),sqrt:hd,inv:({c0:E,c1:b})=>{let v=_.inv(_.sub(_.sqr(E),_.mulByNonresidue(_.sqr(b))));return{c0:_.mul(E,v),c1:_.neg(_.mul(b,v))}},div:(E,b)=>M.mul(E,typeof b=="bigint"?n.inv(n.create(b)):M.inv(b)),pow:(E,b)=>_o(M,E,b),invertBatch:E=>kr(M,E),add:P,sub:C,mul:U,sqr:D,addN:P,subN:C,mulN:U,sqrN:D,fromBytes:E=>{if(E.length!==M.BYTES)throw new Error("fromBytes invalid length="+E.length);return{c0:_.fromBytes(E.subarray(0,_.BYTES)),c1:_.fromBytes(E.subarray(_.BYTES))}},toBytes:({c0:E,c1:b})=>Ie(_.toBytes(E),_.toBytes(b)),cmov:({c0:E,c1:b},{c0:v,c1:y},w)=>({c0:_.cmov(E,v,w),c1:_.cmov(b,y,w)}),fromBigTwelve:E=>({c0:_.fromBigSix(E.slice(0,6)),c1:_.fromBigSix(E.slice(6,12))}),frobeniusMap(E,b){const{c0:v,c1:y,c2:w}=_.frobeniusMap(E.c1,b),I=T[b%12];return{c0:_.frobeniusMap(E.c0,b),c1:_.create({c0:h.mul(v,I),c1:h.mul(y,I),c2:h.mul(w,I)})}},mulByFp2:({c0:E,c1:b},v)=>({c0:_.mulByFp2(E,v),c1:_.mulByFp2(b,v)}),conjugate:({c0:E,c1:b})=>({c0:E,c1:_.neg(b)}),mul014:({c0:E,c1:b},v,y,w)=>{let I=_.mul01(E,v,y),O=_.mul1(b,w);return{c0:_.add(_.mulByNonresidue(O),I),c1:_.sub(_.sub(_.mul01(_.add(b,E),v,h.add(y,w)),I),O)}},mul034:({c0:E,c1:b},v,y,w)=>{const I=_.create({c0:h.mul(E.c0,v),c1:h.mul(E.c1,v),c2:h.mul(E.c2,v)}),O=_.mul01(b,y,w),S=_.mul01(_.add(E,b),h.add(v,y),w);return{c0:_.add(_.mulByNonresidue(O),I),c1:_.sub(S,_.add(I,O))}},_cyclotomicSquare:t.Fp12cyclotomicSquare,_cyclotomicExp:t.Fp12cyclotomicExp,finalExponentiate:t.Fp12finalExponentiate};return{Fp:n,Fp2:h,Fp6:_,Fp4Square:j,Fp12:M}}const at=BigInt(0),Bo=BigInt(1),Ue=BigInt(2),Ao=BigInt(3),es=BigInt(4),ir=BigInt("0xd201000000010000"),W8=Zi(ir),{Fp:X,Fp2:J,Fp6:Xc,Fp4Square:Jc,Fp12:re}=G8({ORDER:BigInt("0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab"),FP2_NONRESIDUE:[Bo,Bo],Fp2mulByB:({c0:t,c1:e})=>{const n=X.mul(t,es),r=X.mul(e,es);return{c0:X.sub(n,r),c1:X.add(n,r)}},Fp12cyclotomicSquare:({c0:t,c1:e})=>{const{c0:n,c1:r,c2:i}=t,{c0:s,c1:o,c2:a}=e,{first:c,second:u}=Jc(n,o),{first:l,second:f}=Jc(s,i),{first:d,second:h}=Jc(r,a),p=J.mulByNonresidue(h);return{c0:Xc.create({c0:J.add(J.mul(J.sub(c,n),Ue),c),c1:J.add(J.mul(J.sub(l,r),Ue),l),c2:J.add(J.mul(J.sub(d,i),Ue),d)}),c1:Xc.create({c0:J.add(J.mul(J.add(p,s),Ue),p),c1:J.add(J.mul(J.add(u,o),Ue),u),c2:J.add(J.mul(J.add(f,a),Ue),f)})}},Fp12cyclotomicExp(t,e){let n=re.ONE;for(let r=W8-1;r>=0;r--)n=re._cyclotomicSquare(n),x3(e,r)&&(n=re.mul(n,t));return n},Fp12finalExponentiate:t=>{const e=ir,n=re.div(re.frobeniusMap(t,6),t),r=re.mul(re.frobeniusMap(n,2),n),i=re.conjugate(re._cyclotomicExp(r,e)),s=re.mul(re.conjugate(re._cyclotomicSquare(r)),i),o=re.conjugate(re._cyclotomicExp(s,e)),a=re.conjugate(re._cyclotomicExp(o,e)),c=re.mul(re.conjugate(re._cyclotomicExp(a,e)),re._cyclotomicSquare(i)),u=re.conjugate(re._cyclotomicExp(c,e)),l=re.frobeniusMap(re.mul(i,a),2),f=re.frobeniusMap(re.mul(o,r),3),d=re.frobeniusMap(re.mul(c,re.conjugate(r)),1),h=re.mul(re.mul(u,re.conjugate(s)),r);return re.mul(re.mul(re.mul(l,f),d),h)}}),Zd=tr(BigInt("0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")),Z8=jd(J,[[["0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97d6"],["0x0","0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71a"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71e","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38d"],["0x171d6541fa38ccfaed6dea691f5fb614cb14b4e7f4e810aa22d6108f142b85757098e38d0f671c7188e2aaaaaaaa5ed1","0x0"]],[["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa63"],["0xc","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa9f"],["0x1","0x0"]],[["0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706","0x1530477c7ab4113b59a4c18b076d11930f7da5d4a07f649bf54439d87d27e500fc8c25ebf8c92f6812cfc71c71c6d706"],["0x0","0x5c759507e8e333ebb5b7a9a47d7ed8532c52d39fd3a042a88b58423c50ae15d5c2638e343d9c71c6238aaaaaaaa97be"],["0x11560bf17baa99bc32126fced787c88f984f87adf7ae0c7f9a208c6b4f20a4181472aaa9cb8d555526a9ffffffffc71c","0x8ab05f8bdd54cde190937e76bc3e447cc27c3d6fbd7063fcd104635a790520c0a395554e5c6aaaa9354ffffffffe38f"],["0x124c9ad43b6cf79bfbf7043de3811ad0761b0f37a1e26286b0e977c69aa274524e79097a56dc4bd9e1b371c71c718b10","0x0"]],[["0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa8fb"],["0x0","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffa9d3"],["0x12","0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaa99"],["0x1","0x0"]]].map(t=>t.map(e=>J.fromBigTuple(e.map(BigInt))))),Y8=jd(X,[["0x11a05f2b1e833340b809101dd99815856b303e88a2d7005ff2627b56cdb4e2c85610c2d5f2e62d6eaeac1662734649b7","0x17294ed3e943ab2f0588bab22147a81c7c17e75b2f6a8417f565e33c70d1e86b4838f2a6f318c356e834eef1b3cb83bb","0xd54005db97678ec1d1048c5d10a9a1bce032473295983e56878e501ec68e25c958c3e3d2a09729fe0179f9dac9edcb0","0x1778e7166fcc6db74e0609d307e55412d7f5e4656a8dbf25f1b33289f1b330835336e25ce3107193c5b388641d9b6861","0xe99726a3199f4436642b4b3e4118e5499db995a1257fb3f086eeb65982fac18985a286f301e77c451154ce9ac8895d9","0x1630c3250d7313ff01d1201bf7a74ab5db3cb17dd952799b9ed3ab9097e68f90a0870d2dcae73d19cd13c1c66f652983","0xd6ed6553fe44d296a3726c38ae652bfb11586264f0f8ce19008e218f9c86b2a8da25128c1052ecaddd7f225a139ed84","0x17b81e7701abdbe2e8743884d1117e53356de5ab275b4db1a682c62ef0f2753339b7c8f8c8f475af9ccb5618e3f0c88e","0x80d3cf1f9a78fc47b90b33563be990dc43b756ce79f5574a2c596c928c5d1de4fa295f296b74e956d71986a8497e317","0x169b1f8e1bcfa7c42e0c37515d138f22dd2ecb803a0c5c99676314baf4bb1b7fa3190b2edc0327797f241067be390c9e","0x10321da079ce07e272d8ec09d2565b0dfa7dccdde6787f96d50af36003b14866f69b771f8c285decca67df3f1605fb7b","0x6e08c248e260e70bd1e962381edee3d31d79d7e22c837bc23c0bf1bc24c6b68c24b1b80b64d391fa9c8ba2e8ba2d229"],["0x8ca8d548cff19ae18b2e62f4bd3fa6f01d5ef4ba35b48ba9c9588617fc8ac62b558d681be343df8993cf9fa40d21b1c","0x12561a5deb559c4348b4711298e536367041e8ca0cf0800c0126c2588c48bf5713daa8846cb026e9e5c8276ec82b3bff","0xb2962fe57a3225e8137e629bff2991f6f89416f5a718cd1fca64e00b11aceacd6a3d0967c94fedcfcc239ba5cb83e19","0x3425581a58ae2fec83aafef7c40eb545b08243f16b1655154cca8abc28d6fd04976d5243eecf5c4130de8938dc62cd8","0x13a8e162022914a80a6f1d5f43e7a07dffdfc759a12062bb8d6b44e833b306da9bd29ba81f35781d539d395b3532a21e","0xe7355f8e4e667b955390f7f0506c6e9395735e9ce9cad4d0a43bcef24b8982f7400d24bc4228f11c02df9a29f6304a5","0x772caacf16936190f3e0c63e0596721570f5799af53a1894e2e073062aede9cea73b3538f0de06cec2574496ee84a3a","0x14a7ac2a9d64a8b230b3f5b074cf01996e7f63c21bca68a81996e1cdf9822c580fa5b9489d11e2d311f7d99bbdcc5a5e","0xa10ecf6ada54f825e920b3dafc7a3cce07f8d1d7161366b74100da67f39883503826692abba43704776ec3a79a1d641","0x95fc13ab9e92ad4476d6e3eb3a56680f682b4ee96f7d03776df533978f31c1593174e4b4b7865002d6384d168ecdd0a","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"],["0x90d97c81ba24ee0259d1f094980dcfa11ad138e48a869522b52af6c956543d3cd0c7aee9b3ba3c2be9845719707bb33","0x134996a104ee5811d51036d776fb46831223e96c254f383d0f906343eb67ad34d6c56711962fa8bfe097e75a2e41c696","0xcc786baa966e66f4a384c86a3b49942552e2d658a31ce2c344be4b91400da7d26d521628b00523b8dfe240c72de1f6","0x1f86376e8981c217898751ad8746757d42aa7b90eeb791c09e4a3ec03251cf9de405aba9ec61deca6355c77b0e5f4cb","0x8cc03fdefe0ff135caf4fe2a21529c4195536fbe3ce50b879833fd221351adc2ee7f8dc099040a841b6daecf2e8fedb","0x16603fca40634b6a2211e11db8f0a6a074a7d0d4afadb7bd76505c3d3ad5544e203f6326c95a807299b23ab13633a5f0","0x4ab0b9bcfac1bbcb2c977d027796b3ce75bb8ca2be184cb5231413c4d634f3747a87ac2460f415ec961f8855fe9d6f2","0x987c8d5333ab86fde9926bd2ca6c674170a05bfe3bdd81ffd038da6c26c842642f64550fedfe935a15e4ca31870fb29","0x9fc4018bd96684be88c9e221e4da1bb8f3abd16679dc26c1e8b6e6a1f20cabe69d65201c78607a360370e577bdba587","0xe1bba7a1186bdb5223abde7ada14a23c42a0ca7915af6fe06985e7ed1e4d43b9b3f7055dd4eba6f2bafaaebca731c30","0x19713e47937cd1be0dfd0b8f1d43fb93cd2fcbcb6caf493fd1183e416389e61031bf3a5cce3fbafce813711ad011c132","0x18b46a908f36f6deb918c143fed2edcc523559b8aaf0c2462e6bfe7f911f643249d9cdf41b44d606ce07c8a4d0074d8e","0xb182cac101b9399d155096004f53f447aa7b12a3426b08ec02710e807b4633f06c851c1919211f20d4c04f00b971ef8","0x245a394ad1eca9b72fc00ae7be315dc757b3b080d4c158013e6632d3c40659cc6cf90ad1c232a6442d9d3f5db980133","0x5c129645e44cf1102a159f748c4a3fc5e673d81d7e86568d9ab0f5d396a7ce46ba1049b6579afb7866b1e715475224b","0x15e6be4e990f03ce4ea50b3b42df2eb5cb181d8f84965a3957add4fa95af01b2b665027efec01c7704b456be69c8b604"],["0x16112c4c3a9c98b252181140fad0eae9601a6de578980be6eec3232b5be72e7a07f3688ef60c206d01479253b03663c1","0x1962d75c2381201e1a0cbd6c43c348b885c84ff731c4d59ca4a10356f453e01f78a4260763529e3532f6102c2e49a03d","0x58df3306640da276faaae7d6e8eb15778c4855551ae7f310c35a5dd279cd2eca6757cd636f96f891e2538b53dbf67f2","0x16b7d288798e5395f20d23bf89edb4d1d115c5dbddbcd30e123da489e726af41727364f2c28297ada8d26d98445f5416","0xbe0e079545f43e4b00cc912f8228ddcc6d19c9f0f69bbb0542eda0fc9dec916a20b15dc0fd2ededda39142311a5001d","0x8d9e5297186db2d9fb266eaac783182b70152c65550d881c5ecd87b6f0f5a6449f38db9dfa9cce202c6477faaf9b7ac","0x166007c08a99db2fc3ba8734ace9824b5eecfdfa8d0cf8ef5dd365bc400a0051d5fa9c01a58b1fb93d1a1399126a775c","0x16a3ef08be3ea7ea03bcddfabba6ff6ee5a4375efa1f4fd7feb34fd206357132b920f5b00801dee460ee415a15812ed9","0x1866c8ed336c61231a1be54fd1d74cc4f9fb0ce4c6af5920abc5750c4bf39b4852cfe2f7bb9248836b233d9d55535d4a","0x167a55cda70a6e1cea820597d94a84903216f763e13d87bb5308592e7ea7d4fbc7385ea3d529b35e346ef48bb8913f55","0x4d2f259eea405bd48f010a01ad2911d9c6dd039bb61a6290e591b36e636a5c871a5c29f4f83060400f8b49cba8f6aa8","0xaccbb67481d033ff5852c1e48c50c477f94ff8aefce42d28c0f9a88cea7913516f968986f7ebbea9684b529e2561092","0xad6b9514c767fe3c3613144b45f1496543346d98adf02267d5ceef9a00d9b8693000763e3b90ac11e99b138573345cc","0x2660400eb2e4f3b628bdd0d53cd76f2bf565b94e72927c1cb748df27942480e420517bd8714cc80d1fadc1326ed06f7","0xe0fa1d816ddc03e6b24255e0d7819c171c40f65e273b853324efcd6356caa205ca2f570f13497804415473a1d634b8f","0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001"]].map(t=>t.map(e=>BigInt(e)))),X8=qd(J,{A:J.create({c0:X.create(at),c1:X.create(BigInt(240))}),B:J.create({c0:X.create(BigInt(1012)),c1:X.create(BigInt(1012))}),Z:J.create({c0:X.create(BigInt(-2)),c1:X.create(BigInt(-1))})}),J8=qd(X,{A:X.create(BigInt("0x144698a3b8e9433d693a02c96d4982b0ea985383ee66a8d8e8981aefd881ac98936f8da0e0f97f5cf428082d584c1d")),B:X.create(BigInt("0x12e2908d11688030018b12e8753eee3b2016c1f0f24f4070a0b9c14fcef35ef55a23215a316ceaa5d1cc48e98e172be0")),Z:X.create(BigInt(11))}),{G2psi:Yd,G2psi2:Q8}=H8(X,J,J.div(J.ONE,J.NONRESIDUE)),Qc=Object.freeze({DST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",encodeDST:"BLS_SIG_BLS12381G2_XMD:SHA-256_SSWU_RO_NUL_",p:X.ORDER,m:2,k:128,expand:"xmd",hash:pi}),Do=ts(X.toBytes(at),{infinity:!0,compressed:!0});function $o(t){t=t.slice();const e=t[0]&224,n=!!(e>>7&1),r=!!(e>>6&1),i=!!(e>>5&1);return t[0]&=31,{compressed:n,infinity:r,sort:i,value:t}}function ts(t,e){if(t[0]&224)throw new Error("setMask: non-empty mask");return e.compressed&&(t[0]|=128),e.infinity&&(t[0]|=64),e.sort&&(t[0]|=32),t}function Xd(t){t.assertValidity();const e=t.equals(Wt.G1.ProjectivePoint.ZERO),{x:n,y:r}=t.toAffine();if(e)return Do.slice();const i=X.ORDER,s=!!(r*Ue/i);return ts($e(n,X.BYTES),{compressed:!0,sort:s})}function Jd(t){t.assertValidity();const e=X.BYTES;if(t.equals(Wt.G2.ProjectivePoint.ZERO))return Ie(Do,$e(at,e));const{x:n,y:r}=t.toAffine(),{re:i,im:s}=J.reim(n),{re:o,im:a}=J.reim(r),u=!!((a>at?a*Ue:o*Ue)/X.ORDER&Bo),l=i;return Ie(ts($e(s,e),{sort:u,compressed:!0}),$e(l,e))}const Wt=V8({fields:{Fp:X,Fp2:J,Fp6:Xc,Fp12:re,Fr:Zd},G1:{Fp:X,h:BigInt("0x396c8c005555e1568c00aaab0000aaab"),Gx:BigInt("0x17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"),Gy:BigInt("0x08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"),a:X.ZERO,b:es,htfDefaults:{...Qc,m:1,DST:"BLS_SIG_BLS12381G1_XMD:SHA-256_SSWU_RO_NUL_"},wrapPrivateKey:!0,allowInfinityPoint:!0,isTorsionFree:(t,e)=>{const n=BigInt("0x5f19672fdf76ce51ba69c6076a0f77eaddb3a93be6f89688de17d813620a00022e01fffffffefffe"),r=new t(X.mul(e.px,n),e.py,e.pz);return e.multiplyUnsafe(ir).negate().multiplyUnsafe(ir).equals(r)},clearCofactor:(t,e)=>e.multiplyUnsafe(ir).add(e),mapToCurve:t=>{const{x:e,y:n}=J8(X.create(t[0]));return Y8(e,n)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=$o(t);if(i.length===48&&e){const s=X.ORDER,o=it(i),a=X.create(o&X.MASK);if(n){if(a!==at)throw new Error("G1: non-empty compressed point at infinity");return{x:at,y:at}}const c=X.add(X.pow(a,Ao),X.create(Wt.params.G1b));let u=X.sqrt(c);if(!u)throw new Error("invalid compressed G1 point");return u*Ue/s!==BigInt(r)&&(u=X.neg(u)),{x:X.create(a),y:X.create(u)}}else if(i.length===96&&!e){const s=it(i.subarray(0,X.BYTES)),o=it(i.subarray(X.BYTES));if(n){if(s!==at||o!==at)throw new Error("G1: non-empty point at infinity");return Wt.G1.ProjectivePoint.ZERO.toAffine()}return{x:X.create(s),y:X.create(o)}}else throw new Error("invalid point G1, expected 48/96 bytes")},toBytes:(t,e,n)=>{const r=e.equals(t.ZERO),{x:i,y:s}=e.toAffine();if(n){if(r)return Do.slice();const o=X.ORDER,a=!!(s*Ue/o);return ts($e(i,X.BYTES),{compressed:!0,sort:a})}else return r?Ie(new Uint8Array([64]),new Uint8Array(2*X.BYTES-1)):Ie($e(i,X.BYTES),$e(s,X.BYTES))},ShortSignature:{fromHex(t){const{infinity:e,sort:n,value:r}=$o(Ze("signatureHex",t,48)),i=X.ORDER,s=it(r);if(e)return Wt.G1.ProjectivePoint.ZERO;const o=X.create(s&X.MASK),a=X.add(X.pow(o,Ao),X.create(Wt.params.G1b));let c=X.sqrt(a);if(!c)throw new Error("invalid compressed G1 point");const u=BigInt(n);c*Ue/i!==u&&(c=X.neg(c));const l=Wt.G1.ProjectivePoint.fromAffine({x:o,y:c});return l.assertValidity(),l},toRawBytes(t){return Xd(t)},toHex(t){return Cr(Xd(t))}}},G2:{Fp:J,h:BigInt("0x5d543a95414e7f1091d50792876a202cd91de4547085abaa68a205b2e5a7ddfa628f1cb4d9e82ef21537e293a6691ae1616ec6e786f0c70cf1c38e31c7238e5"),Gx:J.fromBigTuple([BigInt("0x024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"),BigInt("0x13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e")]),Gy:J.fromBigTuple([BigInt("0x0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"),BigInt("0x0606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be")]),a:J.ZERO,b:J.fromBigTuple([es,es]),hEff:BigInt("0xbc69f08f2ee75b3584c6a0ea91b352888e2a8e9145ad7689986ff031508ffe1329c2f178731db956d82bf015d1212b02ec0ec69d7477c1ae954cbc06689f6a359894c0adebbf6b4e8020005aaa95551"),htfDefaults:{...Qc},wrapPrivateKey:!0,allowInfinityPoint:!0,mapToCurve:t=>{const{x:e,y:n}=X8(J.fromBigTuple(t));return Z8(e,n)},isTorsionFree:(t,e)=>e.multiplyUnsafe(ir).negate().equals(Yd(t,e)),clearCofactor:(t,e)=>{const n=ir;let r=e.multiplyUnsafe(n).negate(),i=Yd(t,e),s=e.double();return s=Q8(t,s),s=s.subtract(i),i=r.add(i),i=i.multiplyUnsafe(n).negate(),s=s.add(i),s=s.subtract(r),s.subtract(e)},fromBytes:t=>{const{compressed:e,infinity:n,sort:r,value:i}=$o(t);if(!e&&!n&&r||!e&&n&&r||r&&n&&e)throw new Error("invalid encoding flag: "+(t[0]&224));const s=X.BYTES,o=(a,c,u)=>it(a.slice(c,u));if(i.length===96&&e){const a=Wt.params.G2b,c=X.ORDER;if(n){if(i.reduce((g,m)=>g!==0?m+1:m,0)>0)throw new Error("invalid compressed G2 point");return{x:J.ZERO,y:J.ZERO}}const u=o(i,0,s),l=o(i,s,2*s),f=J.create({c0:X.create(l),c1:X.create(u)}),d=J.add(J.pow(f,Ao),a);let h=J.sqrt(d);const p=h.c1===at?h.c0*Ue/c:h.c1*Ue/c?Bo:at;return h=r&&p>0?h:J.neg(h),{x:f,y:h}}else if(i.length===192&&!e){if(n){if(i.reduce((f,d)=>f!==0?d+1:d,0)>0)throw new Error("invalid uncompressed G2 point");return{x:J.ZERO,y:J.ZERO}}const a=o(i,0,s),c=o(i,s,2*s),u=o(i,2*s,3*s),l=o(i,3*s,4*s);return{x:J.fromBigTuple([c,a]),y:J.fromBigTuple([l,u])}}else throw new Error("invalid point G2, expected 96/192 bytes")},toBytes:(t,e,n)=>{const{BYTES:r,ORDER:i}=X,s=e.equals(t.ZERO),{x:o,y:a}=e.toAffine();if(n){if(s)return Ie(Do,$e(at,r));const c=!!(a.c1===at?a.c0*Ue/i:a.c1*Ue/i);return Ie(ts($e(o.c1,r),{compressed:!0,sort:c}),$e(o.c0,r))}else{if(s)return Ie(new Uint8Array([64]),new Uint8Array(4*r-1));const{re:c,im:u}=J.reim(o),{re:l,im:f}=J.reim(a);return Ie($e(u,r),$e(c,r),$e(f,r),$e(l,r))}},Signature:{fromHex(t){const{infinity:e,sort:n,value:r}=$o(Ze("signatureHex",t)),i=X.ORDER,s=r.length/2;if(s!==48&&s!==96)throw new Error("invalid compressed signature length, must be 96 or 192");const o=it(r.slice(0,s)),a=it(r.slice(s));if(e)return Wt.G2.ProjectivePoint.ZERO;const c=X.create(o&X.MASK),u=X.create(a),l=J.create({c0:u,c1:c}),f=J.add(J.pow(l,Ao),Wt.params.G2b);let d=J.sqrt(f);if(!d)throw new Error("Failed to find a square root");const{re:h,im:p}=J.reim(d),g=BigInt(n),m=p>at&&p*Ue/i!==g,B=p===at&&h*Ue/i!==g;(m||B)&&(d=J.neg(d));const $=Wt.G2.ProjectivePoint.fromAffine({x:l,y:d});return $.assertValidity(),$},toRawBytes(t){return Jd(t)},toHex(t){return Cr(Jd(t))}}},params:{ateLoopSize:ir,r:Zd.ORDER,xNegative:!0,twistType:"multiplicative"},htfDefaults:Qc,hash:pi,randomBytes:ho});BigInt(0),BigInt(1),BigInt(2),BigInt(8),BigInt(0),BigInt(1),BigInt(2),BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),BigInt(0),BigInt(1),BigInt(2),BigInt(3),BigInt(5),BigInt(8);const eu=BigInt(0),tu=BigInt(1);function To(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=co(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 Po(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Qd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?eu:BigInt("0x"+t)}function Ro(t){return Qd(fi(t))}function ep(t){return wn(t),Qd(fi(Uint8Array.from(t).reverse()))}function nu(t,e){return uo(t.toString(16).padStart(e*2,"0"))}function tp(t,e){return nu(t,e).reverse()}function yt(t,e,n){let r;if(typeof e=="string")try{r=uo(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(co(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 ru=t=>typeof t=="bigint"&&eu<=t;function ex(t,e,n){return ru(t)&&ru(e)&&ru(n)&&e<=t&&t<n}function tx(t,e,n,r){if(!ex(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function np(t){let e;for(e=0;t>eu;t>>=tu,e+=1);return e}const ns=t=>(tu<<BigInt(t))-tu;function nx(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 p=[];for(;h<e;){s=u();const g=s.slice();p.push(g),h+=s.length}return vn(...p)};return(h,p)=>{c(),l(h);let g;for(;!(g=p(f()));)l();return c(),g}}function iu(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 rp(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 bt=BigInt(0),ct=BigInt(1),qr=BigInt(2),ip=BigInt(3),sp=BigInt(4),op=BigInt(5),rx=BigInt(7),ap=BigInt(8),ix=BigInt(9),cp=BigInt(16);function Zt(t,e){const n=t%e;return n>=bt?n:e+n}function Ut(t,e,n){let r=t;for(;e-- >bt;)r*=r,r%=n;return r}function up(t,e){if(t===bt)throw new Error("invert: expected non-zero number");if(e<=bt)throw new Error("invert: expected positive modulus, got "+e);let n=Zt(t,e),r=e,i=bt,s=ct;for(;n!==bt;){const a=r/n,c=r%n,u=i-s*a;r=n,n=c,i=s,s=u}if(r!==ct)throw new Error("invert: does not exist");return Zt(i,e)}function su(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function lp(t,e){const n=(t.ORDER+ct)/sp,r=t.pow(e,n);return su(t,r,e),r}function sx(t,e){const n=(t.ORDER-op)/ap,r=t.mul(e,qr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,qr),i),a=t.mul(s,t.sub(o,t.ONE));return su(t,a,e),a}function ox(t){const e=rs(t),n=fp(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+rx)/cp;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const g=a.eql(a.sqr(l),c),m=a.cmov(u,l,g);return su(a,m,c),m}}function fp(t){if(t<ip)throw new Error("sqrt is not defined for small field");let e=t-ct,n=0;for(;e%qr===bt;)e/=qr,n++;let r=qr;const i=rs(t);for(;dp(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return lp;let s=i.pow(r,e);const o=(e+ct)/qr;return function(c,u){if(c.is0(u))return u;if(dp(c,u)!==1)throw new Error("Cannot find square root");let l=n,f=c.mul(c.ONE,s),d=c.pow(u,e),h=c.pow(u,o);for(;!c.eql(d,c.ONE);){if(c.is0(d))return c.ZERO;let p=1,g=c.sqr(d);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===l)throw new Error("Cannot find square root");const m=ct<<BigInt(l-p-1),B=c.pow(f,m);l=p,f=c.sqr(B),d=c.mul(d,f),h=c.mul(h,B)}return h}}function ax(t){return t%sp===ip?lp:t%ap===op?sx:t%cp===ix?ox(t):fp(t)}const cx=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ux(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=cx.reduce((r,i)=>(r[i]="function",r),e);return iu(t,n),t}function lx(t,e,n){if(n<bt)throw new Error("invalid exponent, negatives unsupported");if(n===bt)return t.ONE;if(n===ct)return e;let r=t.ONE,i=e;for(;n>bt;)n&ct&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ct;return r}function hp(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 dp(t,e){const n=(t.ORDER-ct)/qr,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 pp(t,e){e!==void 0&&ui(e);const n=e!==void 0?e:t.toString(2).length,r=Math.ceil(n/8);return{nBitLength:n,nByteLength:r}}function rs(t,e,n=!1,r={}){if(t<=bt)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 d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=pp(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:ns(c),ZERO:bt,ONE:ct,allowedLengths:a,create:d=>Zt(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return bt<=d&&d<t},is0:d=>d===bt,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ct)===ct,neg:d=>Zt(-d,t),eql:(d,h)=>d===h,sqr:d=>Zt(d*d,t),add:(d,h)=>Zt(d+h,t),sub:(d,h)=>Zt(d-h,t),mul:(d,h)=>Zt(d*h,t),pow:(d,h)=>lx(f,d,h),div:(d,h)=>Zt(d*up(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>up(d,t),sqrt:s||(d=>(l||(l=ax(t)),l(f,d))),toBytes:d=>n?tp(d,u):nu(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const g=new Uint8Array(u);g.set(d,n?0:g.length-d.length),d=g}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?ep(d):Ro(d);if(o&&(p=Zt(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>hp(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function gp(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 yp(t){const e=gp(t);return e+Math.ceil(e/2)}function fx(t,e,n=!1){const r=t.length,i=gp(e),s=yp(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ep(t):Ro(t),a=Zt(o,e-ct)+ct;return n?tp(a,i):nu(a,i)}const wi=BigInt(0),Mr=BigInt(1);function No(t,e){const n=e.negate();return t?n:e}function ou(t,e){const n=hp(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function bp(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function au(t,e){bp(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=ns(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function wp(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+=Mr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function hx(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 dx(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 cu=new WeakMap,mp=new WeakMap;function uu(t){return mp.get(t)||1}function vp(t){if(t!==wi)throw new Error("invalid wNAF")}class px{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>wi;)n&Mr&&(r=r.add(i)),i=i.double(),n>>=Mr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=au(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=au(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=wp(r,a,o);r=c,l?s=s.add(No(d,n[h])):i=i.add(No(f,n[u]))}return vp(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=au(e,this.bits);for(let o=0;o<s.windows&&r!==wi;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=wp(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return vp(r),i}getPrecomputes(e,n,r){let i=cu.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),cu.set(n,i))),i}cached(e,n,r){const i=uu(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=uu(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){bp(n,this.bits),mp.set(e,n),cu.delete(e)}hasCache(e){return uu(e)!==1}}function gx(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>wi||r>wi;)n&Mr&&(s=s.add(i)),r&Mr&&(o=o.add(i)),i=i.double(),n>>=Mr,r>>=Mr;return{p1:s,p2:o}}function yx(t,e,n,r){hx(n,t),dx(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=np(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=ns(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Ep(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return ux(e),e}else return rs(t,{isLE:n})}function bx(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>wi))throw new Error(`CURVE.${c} must be positive bigint`)}const i=Ep(e.p,n.Fp,r),s=Ep(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 xp=(t,e)=>(t+(t>=0?e:-e)/_p)/e;function wx(t,e,n){const[[r,i],[s,o]]=e,a=xp(o*t,n),c=xp(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<$n,d=l<$n;f&&(u=-u),d&&(l=-l);const h=ns(Math.ceil(np(n)/2))+mi;if(u<$n||u>=h||l<$n||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function lu(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function fu(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return To(n.lowS,"lowS"),To(n.prehash,"prehash"),n.format!==void 0&&lu(n.format),n}class mx extends Error{constructor(e=""){super(e)}}const Dn={Err:mx,_tlv:{encode:(t,e)=>{const{Err:n}=Dn;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=Po(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?Po(i.length/2|128):"";return Po(t)+s+i+e},decode(t,e){const{Err:n}=Dn;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}=Dn;if(t<$n)throw new e("integer: negative integers are not allowed");let n=Po(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}=Dn;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 Ro(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Dn,i=yt("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}=Dn,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},$n=BigInt(0),mi=BigInt(1),_p=BigInt(2),Co=BigInt(3),vx=BigInt(4);function vi(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=yt("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 Ex(t,e={}){const n=bx("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;iu(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=Sp(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,b,v){const{x:y,y:w}=b.toAffine(),I=r.toBytes(y);if(To(v,"isCompressed"),v){l();const O=!r.isOdd(w);return vn(Ip(O),I)}else return vn(Uint8Array.of(4),I,r.toBytes(w))}function d(E){Lr(E,void 0,"Point");const{publicKey:b,publicKeyUncompressed:v}=u,y=E.length,w=E[0],I=E.subarray(1);if(y===b&&(w===2||w===3)){const O=r.fromBytes(I);if(!r.isValid(O))throw new Error("bad point: is not on curve, wrong x");const S=g(O);let A;try{A=r.sqrt(S)}catch(F){const L=F instanceof Error?": "+F.message:"";throw new Error("bad point: is not on curve, sqrt error"+L)}l();const R=r.isOdd(A);return(w&1)===1!==R&&(A=r.neg(A)),{x:O,y:A}}else if(y===v&&w===4){const O=r.BYTES,S=r.fromBytes(I.subarray(0,O)),A=r.fromBytes(I.subarray(O,O*2));if(!m(S,A))throw new Error("bad point: is not on curve");return{x:S,y:A}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${v}`)}const h=e.toBytes||f,p=e.fromBytes||d;function g(E){const b=r.sqr(E),v=r.mul(b,E);return r.add(r.add(v,r.mul(E,s.a)),s.b)}function m(E,b){const v=r.sqr(b),y=g(E);return r.eql(v,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,Co),vx),$=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,$)))throw new Error("bad curve params: a or b");function x(E,b,v=!1){if(!r.isValid(b)||v&&r.is0(b))throw new Error(`bad point coordinate ${E}`);return b}function _(E){if(!(E instanceof D))throw new Error("ProjectivePoint expected")}function T(E){if(!c||!c.basises)throw new Error("no endo");return wx(E,c.basises,i.ORDER)}const P=rp((E,b)=>{const{X:v,Y:y,Z:w}=E;if(r.eql(w,r.ONE))return{x:v,y};const I=E.is0();b==null&&(b=I?r.ONE:r.inv(w));const O=r.mul(v,b),S=r.mul(y,b),A=r.mul(w,b);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:O,y:S}}),C=rp(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:v}=E.toAffine();if(!r.isValid(b)||!r.isValid(v))throw new Error("bad point: x or y not field elements");if(!m(b,v))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(E,b,v,y,w){return v=new D(r.mul(v.X,E),v.Y,v.Z),b=No(y,b),v=No(w,v),b.add(v)}class D{constructor(b,v,y){this.X=x("x",b),this.Y=x("y",v,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:v,y}=b||{};if(!b||!r.isValid(v)||!r.isValid(y))throw new Error("invalid affine point");if(b instanceof D)throw new Error("projective point not allowed");return r.is0(v)&&r.is0(y)?D.ZERO:new D(v,y,r.ONE)}static fromBytes(b){const v=D.fromAffine(p(Lr(b,void 0,"point")));return v.assertValidity(),v}static fromHex(b){return D.fromBytes(yt("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return M.createCache(this,b),v||this.multiply(Co),this}assertValidity(){C(this)}hasEvenY(){const{y:b}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(b)}equals(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b,A=r.eql(r.mul(v,S),r.mul(I,w)),R=r.eql(r.mul(y,S),r.mul(O,w));return A&&R}negate(){return new D(this.X,r.neg(this.Y),this.Z)}double(){const{a:b,b:v}=s,y=r.mul(v,Co),{X:w,Y:I,Z:O}=this;let S=r.ZERO,A=r.ZERO,R=r.ZERO,k=r.mul(w,w),F=r.mul(I,I),L=r.mul(O,O),N=r.mul(w,I);return N=r.add(N,N),R=r.mul(w,O),R=r.add(R,R),S=r.mul(b,R),A=r.mul(y,L),A=r.add(S,A),S=r.sub(F,A),A=r.add(F,A),A=r.mul(S,A),S=r.mul(N,S),R=r.mul(y,R),L=r.mul(b,L),N=r.sub(k,L),N=r.mul(b,N),N=r.add(N,R),R=r.add(k,k),k=r.add(R,k),k=r.add(k,L),k=r.mul(k,N),A=r.add(A,k),L=r.mul(I,O),L=r.add(L,L),k=r.mul(L,N),S=r.sub(S,k),R=r.mul(L,F),R=r.add(R,R),R=r.add(R,R),new D(S,A,R)}add(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b;let A=r.ZERO,R=r.ZERO,k=r.ZERO;const F=s.a,L=r.mul(s.b,Co);let N=r.mul(v,I),q=r.mul(y,O),z=r.mul(w,S),W=r.add(v,y),K=r.add(I,O);W=r.mul(W,K),K=r.add(N,q),W=r.sub(W,K),K=r.add(v,w);let Z=r.add(I,S);return K=r.mul(K,Z),Z=r.add(N,z),K=r.sub(K,Z),Z=r.add(y,w),A=r.add(O,S),Z=r.mul(Z,A),A=r.add(q,z),Z=r.sub(Z,A),k=r.mul(F,K),A=r.mul(L,z),k=r.add(A,k),A=r.sub(q,k),k=r.add(q,k),R=r.mul(A,k),q=r.add(N,N),q=r.add(q,N),z=r.mul(F,z),K=r.mul(L,K),q=r.add(q,z),z=r.sub(N,z),z=r.mul(F,z),K=r.add(K,z),N=r.mul(q,K),R=r.add(R,N),N=r.mul(Z,K),A=r.mul(W,A),A=r.sub(A,N),N=r.mul(W,q),k=r.mul(Z,k),k=r.add(k,N),new D(A,R,k)}subtract(b){return this.add(b.negate())}is0(){return this.equals(D.ZERO)}multiply(b){const{endo:v}=e;if(!i.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,w;const I=O=>M.cached(this,O,S=>ou(D,S));if(v){const{k1neg:O,k1:S,k2neg:A,k2:R}=T(b),{p:k,f:F}=I(S),{p:L,f:N}=I(R);w=F.add(N),y=U(v.beta,k,L,O,A)}else{const{p:O,f:S}=I(b);y=O,w=S}return ou(D,[y,w])[0]}multiplyUnsafe(b){const{endo:v}=e,y=this;if(!i.isValid(b))throw new Error("invalid scalar: out of range");if(b===$n||y.is0())return D.ZERO;if(b===mi)return y;if(M.hasCache(this))return this.multiply(b);if(v){const{k1neg:w,k1:I,k2neg:O,k2:S}=T(b),{p1:A,p2:R}=gx(D,y,I,S);return U(v.beta,A,R,w,O)}else return M.unsafe(y,b)}multiplyAndAddUnsafe(b,v,y){const w=this.multiplyUnsafe(v).add(b.multiplyUnsafe(y));return w.is0()?void 0:w}toAffine(b){return P(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return o===mi?!0:b?b(D,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return o===mi?this:b?b(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(b=!0){return To(b,"isCompressed"),this.assertValidity(),h(D,this,b)}toHex(b=!0){return fi(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return ou(D,b)}static msm(b,v){return yx(D,i,b,v)}static fromPrivateKey(b){return D.BASE.multiply(vi(i,b))}}D.BASE=new D(s.Gx,s.Gy,r.ONE),D.ZERO=new D(r.ZERO,r.ONE,r.ZERO),D.Fp=r,D.Fn=i;const j=i.BITS,M=new px(D,e.endo?Math.ceil(j/2):j);return D.BASE.precompute(8),D}function Ip(t){return Uint8Array.of(t?2:3)}function Sp(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function xx(t,e={}){const{Fn:n}=t,r=e.randomBytes||ho,i=Object.assign(Sp(t.Fp,n),{seed:yp(n.ORDER)});function s(h){try{return!!vi(n,h)}catch{return!1}}function o(h,p){const{publicKey:g,publicKeyUncompressed:m}=i;try{const B=h.length;return p===!0&&B!==g||p===!1&&B!==m?!1:!!t.fromBytes(h)}catch{return!1}}function a(h=r(i.seed)){return fx(Lr(h,i.seed,"seed"),n.ORDER)}function c(h,p=!0){return t.BASE.multiply(vi(n,h)).toBytes(p)}function u(h){const p=a(h);return{secretKey:p,publicKey:c(p)}}function l(h){if(typeof h=="bigint")return!1;if(h instanceof t)return!0;const{secretKey:p,publicKey:g,publicKeyUncompressed:m}=i;if(n.allowedLengths||p===g)return;const B=yt("key",h).length;return B===g||B===m}function f(h,p,g=!0){if(l(h)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const m=vi(n,h);return t.fromHex(p).multiply(m).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:h=>vi(n,h),precompute(h=8,p=t.BASE){return p.precompute(h,!1)}},lengths:i})}function _x(t,e,n={}){jh(e),iu(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||ho,i=n.hmac||((v,...y)=>Fc(e,v,vn(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=xx(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function m(v){const y=a>>mi;return v>y}function B(v,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return y}function $(v,y){lu(y);const w=h.signature,I=y==="compact"?w:y==="recovered"?w+1:void 0;return Lr(v,I,`${y} signature`)}class x{constructor(y,w,I){this.r=B("r",y),this.s=B("s",w),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(y,w=g){$(y,w);let I;if(w==="der"){const{r:R,s:k}=Dn.toSig(Lr(y));return new x(R,k)}w==="recovered"&&(I=y[0],w="compact",y=y.subarray(1));const O=o.BYTES,S=y.subarray(0,O),A=y.subarray(O,O*2);return new x(o.fromBytes(S),o.fromBytes(A),I)}static fromHex(y,w){return this.fromBytes(uo(y),w)}addRecoveryBit(y){return new x(this.r,this.s,y)}recoverPublicKey(y){const w=s.ORDER,{r:I,s:O,recovery:S}=this;if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");if(a*_p<w&&S>1)throw new Error("recovery id is ambiguous for h>1 curve");const R=S===2||S===3?I+a:I;if(!s.isValid(R))throw new Error("recovery id 2 or 3 invalid");const k=s.toBytes(R),F=t.fromBytes(vn(Ip((S&1)===0),k)),L=o.inv(R),N=T(yt("msgHash",y)),q=o.create(-N*L),z=o.create(O*L),W=t.BASE.multiplyUnsafe(q).add(F.multiplyUnsafe(z));if(W.is0())throw new Error("point at infinify");return W.assertValidity(),W}hasHighS(){return m(this.s)}toBytes(y=g){if(lu(y),y==="der")return uo(Dn.hexFromSig(this));const w=o.toBytes(this.r),I=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return vn(Uint8Array.of(this.recovery),w,I)}return vn(w,I)}toHex(y){return fi(this.toBytes(y))}assertValidity(){}static fromCompact(y){return x.fromBytes(yt("sig",y),"compact")}static fromDER(y){return x.fromBytes(yt("sig",y),"der")}normalizeS(){return this.hasHighS()?new x(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return fi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return fi(this.toBytes("compact"))}}const _=n.bits2int||function(y){if(y.length>8192)throw new Error("input is too large");const w=Ro(y),I=y.length*8-c;return I>0?w>>BigInt(I):w},T=n.bits2int_modN||function(y){return o.create(_(y))},P=ns(c);function C(v){return tx("num < 2^"+c,v,$n,P),o.toBytes(v)}function U(v,y){return Lr(v,void 0,"message"),y?Lr(e(v),void 0,"prehashed message"):v}function D(v,y,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:I,prehash:O,extraEntropy:S}=fu(w,p);v=U(v,O);const A=T(v),R=vi(o,y),k=[C(R),C(A)];if(S!=null&&S!==!1){const q=S===!0?r(h.secretKey):S;k.push(yt("extraEntropy",q))}const F=vn(...k),L=A;function N(q){const z=_(q);if(!o.isValidNot0(z))return;const W=o.inv(z),K=t.BASE.multiply(z).toAffine(),Z=o.create(K.x);if(Z===$n)return;const Q=o.create(W*o.create(L+Z*R));if(Q===$n)return;let ee=(K.x===Z?0:2)|Number(K.y&mi),ie=Q;return I&&m(Q)&&(ie=o.neg(Q),ee^=1),new x(Z,ie,ee)}return{seed:F,k2sig:N}}function j(v,y,w={}){v=yt("message",v);const{seed:I,k2sig:O}=D(v,y,w);return nx(e.outputLen,o.BYTES,i)(I,O)}function M(v){let y;const w=typeof v=="string"||co(v),I=!w&&v!==null&&typeof v=="object"&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!w&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)y=new x(v.r,v.s);else if(w){try{y=x.fromBytes(yt("sig",v),"der")}catch(O){if(!(O instanceof Dn.Err))throw O}if(!y)try{y=x.fromBytes(yt("sig",v),"compact")}catch{return!1}}return y||!1}function E(v,y,w,I={}){const{lowS:O,prehash:S,format:A}=fu(I,p);if(w=yt("publicKey",w),y=U(yt("message",y),S),"strict"in I)throw new Error("options.strict was renamed to lowS");const R=A===void 0?M(v):x.fromBytes(yt("sig",v),A);if(R===!1)return!1;try{const k=t.fromBytes(w);if(O&&R.hasHighS())return!1;const{r:F,s:L}=R,N=T(y),q=o.inv(L),z=o.create(N*q),W=o.create(F*q),K=t.BASE.multiplyUnsafe(z).add(k.multiplyUnsafe(W));return K.is0()?!1:o.create(K.x)===F}catch{return!1}}function b(v,y,w={}){const{prehash:I}=fu(w,p);return y=U(y,I),x.fromBytes(v,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:j,verify:E,recoverPublicKey:b,Signature:x,hash:e})}function Ix(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=rs(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 Sx(t){const{CURVE:e,curveOpts:n}=Ix(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 Ox(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,pp(n.Fn.ORDER,n.Fn.BITS))})}function Bx(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=Sx(t),s=Ex(e,n),o=_x(s,r,i);return Ox(t,o)}function Ax(t,e){const n=r=>Bx({...t,hash:r});return{...n(e),create:n}}vc("HashToScalar-");const hu={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Dx={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},Op=BigInt(2);function $x(t){const e=hu.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=Ut(l,n,e)*l%e,d=Ut(f,n,e)*l%e,h=Ut(d,Op,e)*u%e,p=Ut(h,i,e)*h%e,g=Ut(p,s,e)*p%e,m=Ut(g,a,e)*g%e,B=Ut(m,c,e)*m%e,$=Ut(B,a,e)*g%e,x=Ut($,n,e)*l%e,_=Ut(x,o,e)*p%e,T=Ut(_,r,e)*u%e,P=Ut(T,Op,e);if(!du.eql(du.sqr(P),t))throw new Error("Cannot find square root");return P}const du=rs(hu.p,{sqrt:$x});Ax({...hu,Fp:du,lowS:!0,endo:Dx},pi);/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ei(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function pu(t,...e){if(!Ei(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 Bp(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 gu(t){if(typeof t!="function")throw new Error("function expected");return!0}function sr(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function xi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Uo(t){if(!Array.isArray(t))throw new Error("array expected")}function Fo(t,e){if(!Bp(!0,e))throw new Error(`${t}: array of strings expected`)}function yu(t,e){if(!Bp(!1,e))throw new Error(`${t}: array of numbers expected`)}function wt(...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 Bt(t){const e=typeof t=="string"?t.split(""):t,n=e.length;Fo("alphabet",e);const r=new Map(e.map((i,s)=>[i,s]));return{encode:i=>(Uo(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=>(Uo(i),i.map(s=>{sr("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function At(t=""){return sr("join",t),{encode:e=>(Fo("join.decode",e),e.join(t)),decode:e=>(sr("join.decode",e),e.split(t))}}function ko(t,e="="){return xi(t),sr("padding",e),{encode(n){for(Fo("padding.encode",n);n.length*t%8;)n.push(e);return n},decode(n){Fo("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 Ap(t){return gu(t),{encode:e=>e,decode:e=>t(e)}}function Dp(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(Uo(t),!t.length)return[];let r=0;const i=[],s=Array.from(t,a=>{if(xi(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,d=f+l;if(!Number.isSafeInteger(d)||f/e!==a||d-l!==f)throw new Error("convertRadix: carry overflow");const h=d/n;a=d%n;const p=Math.floor(h);if(s[u]=p,!Number.isSafeInteger(p)||p*n+a!==d)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 $p=(t,e)=>e===0?t:$p(e,t%e),Lo=(t,e)=>t+(e-$p(t,e)),qo=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function bu(t,e,n,r){if(Uo(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(Lo(e,n)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${n} carryBits=${Lo(e,n)}`);let i=0,s=0;const o=qo[e],a=qo[n]-1,c=[];for(const u of t){if(xi(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=qo[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 Tx(t){xi(t);const e=2**8;return{encode:n=>{if(!Ei(n))throw new Error("radix.encode input should be Uint8Array");return Dp(Array.from(n),e,t)},decode:n=>(yu("radix.decode",n),Uint8Array.from(Dp(n,t,e)))}}function Ft(t,e=!1){if(xi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(Lo(8,t)>32||Lo(t,8)>32)throw new Error("radix2: carry overflow");return{encode:n=>{if(!Ei(n))throw new Error("radix2.encode input should be Uint8Array");return bu(Array.from(n),8,t,!e)},decode:n=>(yu("radix2.decode",n),Uint8Array.from(bu(n,t,8,e)))}}function Tp(t){return gu(t),function(...e){try{return t.apply(null,e)}catch{}}}function Px(t,e){return xi(t),gu(e),{encode(n){if(!Ei(n))throw new Error("checksum.encode: input should be Uint8Array");const r=e(n).slice(0,t),i=new Uint8Array(n.length+t);return i.set(n),i.set(r,n.length),i},decode(n){if(!Ei(n))throw new Error("checksum.decode: input should be Uint8Array");const r=n.slice(0,-t),i=n.slice(-t),s=e(r).slice(0,t);for(let o=0;o<t;o++)if(s[o]!==i[o])throw new Error("Invalid checksum");return r}}}const Rx=wt(Ft(5),Bt("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),ko(5),At("")),Pp=typeof Uint8Array.from([]).toBase64=="function"&&typeof Uint8Array.fromBase64=="function",Rp=(t,e)=>{sr("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"})},wu=t=>wt(Tx(58),Bt(t),At("")),Nx=wu("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"),Cx=t=>wt(Px(4,e=>t(t(e))),Nx),mu=wt(Bt("qpzry9x8gf2tvdw0s3jn54khce6mua7l"),At("")),Np=[996825010,642813549,513874426,1027748829,705979059];function is(t){const e=t>>25;let n=(t&33554431)<<5;for(let r=0;r<Np.length;r++)(e>>r&1)===1&&(n^=Np[r]);return n}function Cp(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=is(i)^o>>5}i=is(i);for(let s=0;s<r;s++)i=is(i)^t.charCodeAt(s)&31;for(let s of e)i=is(i)^s;for(let s=0;s<6;s++)i=is(i);return i^=n,mu.encode(bu([i%qo[30]],30,5,!1))}function Up(t){const e=t==="bech32"?1:734539939,n=Ft(5),r=n.decode,i=n.encode,s=Tp(r);function o(f,d,h=90){sr("bech32.encode prefix",f),Ei(d)&&(d=Array.from(d)),yu("bech32.encode",d);const p=f.length;if(p===0)throw new TypeError(`Invalid prefix length ${p}`);const g=p+7+d.length;if(h!==!1&&g>h)throw new TypeError(`Length ${g} exceeds limit ${h}`);const m=f.toLowerCase(),B=Cp(m,d,e);return`${m}1${mu.encode(d)}${B}`}function a(f,d=90){sr("bech32.decode input",f);const h=f.length;if(h<8||d!==!1&&h>d)throw new TypeError(`invalid string length: ${h} (${f}). Expected (8..${d})`);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 m=p.slice(0,g),B=p.slice(g+1);if(B.length<6)throw new Error("Data must be at least 6 characters long");const $=mu.decode(B).slice(0,-6),x=Cp(m,$,e);if(!B.endsWith(x))throw new Error(`Invalid checksum in ${f}: expected "${x}"`);return{prefix:m,words:$}}const c=Tp(a);function u(f){const{prefix:d,words:h}=a(f,!1);return{prefix:d,words:h,bytes:r(h)}}function l(f,d){return o(f,i(d))}return{encode:o,decode:a,encodeFromBytes:l,decodeToBytes:u,decodeUnsafe:c,fromWords:r,fromWordsUnsafe:s,toWords:i}}const Ux=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Fx={encode(t){return pu(t),t.toHex()},decode(t){return sr("hex",t),Uint8Array.fromHex(t)}};Cx(pi),vc("Bitcoin seed");function kx(t){return s8(Lx(t))}function Lx(t){const{payload:e,signature:n}=t,{r,s:i,yParity:s}=n,a=new U8.Signature(BigInt(r),BigInt(i)).addRecoveryBit(s).recoverPublicKey(Pc(e).substring(2));return Y3(a)}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Fp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Mo(t,...e){if(!Fp(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 jo(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 kp(t,e){Mo(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ss(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function vu(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function qx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Mx(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function os(t){if(typeof t=="string")t=Mx(t);else if(Fp(t))t=Lp(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function Lp(t){return Uint8Array.from(t)}const Tn=16,Eu=new Uint8Array(16),an=ss(Eu),jx=225,zx=(t,e,n,r)=>{const i=r&1;return{s3:n<<31|r>>>1,s2:e<<31|n>>>1,s1:t<<31|e>>>1,s0:t>>>1^jx<<24&-(i&1)}},kt=t=>(t>>>0&255)<<24|(t>>>8&255)<<16|(t>>>16&255)<<8|t>>>24&255|0;function Vx(t){t.reverse();const e=t[15]&1;let n=0;for(let r=0;r<t.length;r++){const i=t[r];t[r]=i>>>1|n,n=(i&1)<<7}return t[0]^=-e&225,t}const Kx=t=>t>64*1024?8:t>1024?4:2;class qp{constructor(e,n){this.blockLen=Tn,this.outputLen=Tn,this.s0=0,this.s1=0,this.s2=0,this.s3=0,this.finished=!1,e=os(e),Mo(e,16);const r=qx(e);let i=r.getUint32(0,!1),s=r.getUint32(4,!1),o=r.getUint32(8,!1),a=r.getUint32(12,!1);const c=[];for(let p=0;p<128;p++)c.push({s0:kt(i),s1:kt(s),s2:kt(o),s3:kt(a)}),{s0:i,s1:s,s2:o,s3:a}=zx(i,s,o,a);const u=Kx(n||1024);if(![1,2,4,8].includes(u))throw new Error("ghash: invalid window size, expected 2, 4 or 8");this.W=u;const f=128/u,d=this.windowSize=2**u,h=[];for(let p=0;p<f;p++)for(let g=0;g<d;g++){let m=0,B=0,$=0,x=0;for(let _=0;_<u;_++){if(!(g>>>u-_-1&1))continue;const{s0:P,s1:C,s2:U,s3:D}=c[u*p+_];m^=P,B^=C,$^=U,x^=D}h.push({s0:m,s1:B,s2:$,s3:x})}this.t=h}_updateBlock(e,n,r,i){e^=this.s0,n^=this.s1,r^=this.s2,i^=this.s3;const{W:s,t:o,windowSize:a}=this;let c=0,u=0,l=0,f=0;const d=(1<<s)-1;let h=0;for(const p of[e,n,r,i])for(let g=0;g<4;g++){const m=p>>>8*g&255;for(let B=8/s-1;B>=0;B--){const $=m>>>s*B&d,{s0:x,s1:_,s2:T,s3:P}=o[h*a+$];c^=x,u^=_,l^=T,f^=P,h+=1}}this.s0=c,this.s1=u,this.s2=l,this.s3=f}update(e){jo(this),e=os(e),Mo(e);const n=ss(e),r=Math.floor(e.length/Tn),i=e.length%Tn;for(let s=0;s<r;s++)this._updateBlock(n[s*4+0],n[s*4+1],n[s*4+2],n[s*4+3]);return i&&(Eu.set(e.subarray(r*Tn)),this._updateBlock(an[0],an[1],an[2],an[3]),vu(an)),this}destroy(){const{t:e}=this;for(const n of e)n.s0=0,n.s1=0,n.s2=0,n.s3=0}digestInto(e){jo(this),kp(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=ss(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e}digest(){const e=new Uint8Array(Tn);return this.digestInto(e),this.destroy(),e}}class Hx extends qp{constructor(e,n){e=os(e),Mo(e);const r=Vx(Lp(e));super(r,n),vu(r)}update(e){e=os(e),jo(this);const n=ss(e),r=e.length%Tn,i=Math.floor(e.length/Tn);for(let s=0;s<i;s++)this._updateBlock(kt(n[s*4+3]),kt(n[s*4+2]),kt(n[s*4+1]),kt(n[s*4+0]));return r&&(Eu.set(e.subarray(i*Tn)),this._updateBlock(kt(an[3]),kt(an[2]),kt(an[1]),kt(an[0])),vu(an)),this}digestInto(e){jo(this),kp(e,this),this.finished=!0;const{s0:n,s1:r,s2:i,s3:s}=this,o=ss(e);return o[0]=n,o[1]=r,o[2]=i,o[3]=s,e.reverse()}}function Mp(t){const e=(r,i)=>t(i,r.length).update(os(r)).digest(),n=t(new Uint8Array(16),0);return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=(r,i)=>t(r,i),e}Mp((t,e)=>new qp(t,e)),Mp((t,e)=>new Hx(t,e));const jp=tr(BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff")),Gx=jp.create(BigInt("-3")),Wx=BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");So({a:Gx,b:Wx,Fp:jp,n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"),h:BigInt(1),lowS:!1},pi);const zp=tr(BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff")),Zx=zp.create(BigInt("-3")),Yx=BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef");So({a:Zx,b:Yx,Fp:zp,n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f"),h:BigInt(1),lowS:!1},v3);const Vp=tr(BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")),Xx=Vp.create(BigInt("-3")),Jx=BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00");So({a:Xx,b:Jx,Fp:Vp,n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650"),h:BigInt(1),lowS:!1,allowedPrivateKeyLengths:[130,131,132]},m3);var Qx={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function s(c,u,l,f,d){if(typeof l!="function")throw new TypeError("The listener must be a function");var h=new i(l,f||c,d),p=n?n+u:u;return c._events[p]?c._events[p].fn?c._events[p]=[c._events[p],h]:c._events[p].push(h):(c._events[p]=h,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new r:delete c._events[u]}function a(){this._events=new r,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],l,f;if(this._eventsCount===0)return u;for(f in l=this._events)e.call(l,f)&&u.push(n?f.slice(1):f);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},a.prototype.listeners=function(u){var l=n?n+u:u,f=this._events[l];if(!f)return[];if(f.fn)return[f.fn];for(var d=0,h=f.length,p=new Array(h);d<h;d++)p[d]=f[d].fn;return p},a.prototype.listenerCount=function(u){var l=n?n+u:u,f=this._events[l];return f?f.fn?1:f.length:0},a.prototype.emit=function(u,l,f,d,h,p){var g=n?n+u:u;if(!this._events[g])return!1;var m=this._events[g],B=arguments.length,$,x;if(m.fn){switch(m.once&&this.removeListener(u,m.fn,void 0,!0),B){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,l),!0;case 3:return m.fn.call(m.context,l,f),!0;case 4:return m.fn.call(m.context,l,f,d),!0;case 5:return m.fn.call(m.context,l,f,d,h),!0;case 6:return m.fn.call(m.context,l,f,d,h,p),!0}for(x=1,$=new Array(B-1);x<B;x++)$[x-1]=arguments[x];m.fn.apply(m.context,$)}else{var _=m.length,T;for(x=0;x<_;x++)switch(m[x].once&&this.removeListener(u,m[x].fn,void 0,!0),B){case 1:m[x].fn.call(m[x].context);break;case 2:m[x].fn.call(m[x].context,l);break;case 3:m[x].fn.call(m[x].context,l,f);break;case 4:m[x].fn.call(m[x].context,l,f,d);break;default:if(!$)for(T=1,$=new Array(B-1);T<B;T++)$[T-1]=arguments[T];m[x].fn.apply(m[x].context,$)}}return!0},a.prototype.on=function(u,l,f){return s(this,u,l,f,!1)},a.prototype.once=function(u,l,f){return s(this,u,l,f,!0)},a.prototype.removeListener=function(u,l,f,d){var h=n?n+u:u;if(!this._events[h])return this;if(!l)return o(this,h),this;var p=this._events[h];if(p.fn)p.fn===l&&(!d||p.once)&&(!f||p.context===f)&&o(this,h);else{for(var g=0,m=[],B=p.length;g<B;g++)(p[g].fn!==l||d&&!p[g].once||f&&p[g].context!==f)&&m.push(p[g]);m.length?this._events[h]=m.length===1?m[0]:m:o(this,h)}return this},a.prototype.removeAllListeners=function(u){var l;return u?(l=n?n+u:u,this._events[l]&&o(this,l)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=n,a.EventEmitter=a,t.exports=a})(Qx);function e6(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,d=0;const h=u.length;for(;d!==h&&u[d]===0;)d++,l++;const p=(h-d)*s+1>>>0,g=new Uint8Array(p);for(;d!==h;){let $=u[d],x=0;for(let _=p-1;($!==0||x<f)&&_!==-1;_--,x++)$+=256*g[_]>>>0,g[_]=$%n>>>0,$=$/n>>>0;if($!==0)throw new Error("Non-zero carry");f=x,d++}let m=p-f;for(;m!==p&&g[m]===0;)m++;let B=r.repeat(l);for(;m<p;++m)B+=t.charAt(g[m]);return B}function a(u){if(typeof u!="string")throw new TypeError("Expected String");if(u.length===0)return new Uint8Array;let l=0,f=0,d=0;for(;u[l]===r;)f++,l++;const h=(u.length-l)*i+1>>>0,p=new Uint8Array(h);for(;l<u.length;){const $=u.charCodeAt(l);if($>255)return;let x=e[$];if(x===255)return;let _=0;for(let T=h-1;(x!==0||_<d)&&T!==-1;T--,_++)x+=n*p[T]>>>0,p[T]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");d=_,l++}let g=h-d;for(;g!==h&&p[g]===0;)g++;const m=new Uint8Array(f+(h-g));let B=f;for(;g!==h;)m[B++]=p[g++];return m}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 t6="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",as=e6(t6);function n6(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 r6(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 i6=new TextEncoder,s6=50;function o6(t,e,n){i6.encodeInto(t,e.subarray(n))}function a6(t,e,n){t.length>s6?o6(t,e,n):r6(t,e,n)}const c6=4096;function Kp(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>=c6&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const u6=new TextDecoder,l6=200;function f6(t,e,n){const r=t.subarray(e,e+n);return u6.decode(r)}function h6(t,e,n){return n>l6?f6(t,e,n):Kp(t,e,n)}class zo{constructor(e,n){this.type=e,this.data=n}}class Dt extends Error{constructor(e){super(e);const n=Object.create(Dt.prototype);Object.setPrototypeOf(this,n),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Dt.name})}}const cs=4294967295;function d6(t,e,n){const r=n/4294967296,i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Hp(t,e,n){const r=Math.floor(n/4294967296),i=n;t.setUint32(e,r),t.setUint32(e+4,i)}function Gp(t,e){const n=t.getInt32(e),r=t.getUint32(e+4);return n*4294967296+r}function p6(t,e){const n=t.getUint32(e),r=t.getUint32(e+4);return n*4294967296+r}const g6=-1,y6=4294967296-1,b6=17179869184-1;function w6({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=b6)if(e===0&&t<=y6){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),Hp(r,4,t),n}}function m6(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 v6(t){if(t instanceof Date){const e=m6(t);return w6(e)}else return null}function E6(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=Gp(e,4),r=e.getUint32(0);return{sec:n,nsec:r}}default:throw new Dt(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function x6(t){const e=E6(t);return new Date(e.sec*1e3+e.nsec/1e6)}const _6={type:g6,encode:v6,decode:x6};class Vo{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(_6)}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 zo(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 zo(o,s)}}}return e instanceof zo?e:null}decode(e,n,r){const i=n<0?this.builtInDecoders[-1-n]:this.decoders[n];return i?i(e,n,r):new zo(n,e)}}Vo.defaultCodec=new Vo;function I6(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function xu(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):I6(t)?new Uint8Array(t):Uint8Array.from(t)}const S6=100,O6=2048;class _u{constructor(e){this.entered=!1,this.extensionCodec=e?.extensionCodec??Vo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??S6,this.initialBufferSize=e?.initialBufferSize??O6,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 _u({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=n6(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),a6(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=xu(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),d6(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),Hp(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 B6(t,e){return new _u(e).encodeSharedRef(t)}function Iu(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const A6=16,D6=16;class $6{constructor(e=A6,n=D6){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=Kp(e,n,r),o=Uint8Array.prototype.slice.call(e,n,n+r);return this.store(o,s),s}}const Su="array",us="map_key",Wp="map_value",T6=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Dt("The type of key must be string or number but "+typeof t)};class P6{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=Su,n.position=0,n.size=e,n.array=new Array(e)}pushMapState(e){const n=this.getUninitializedStateFromPool();n.type=us,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===Su){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===us||e.type===Wp){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 ls=-1,Ou=new DataView(new ArrayBuffer(0)),R6=new Uint8Array(Ou.buffer);try{Ou.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 Zp=new RangeError("Insufficient data"),N6=new $6;class Bu{constructor(e){this.totalPos=0,this.pos=0,this.view=Ou,this.bytes=R6,this.headByte=ls,this.stack=new P6,this.entered=!1,this.extensionCodec=e?.extensionCodec??Vo.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??cs,this.maxBinLength=e?.maxBinLength??cs,this.maxArrayLength=e?.maxArrayLength??cs,this.maxMapLength=e?.maxMapLength??cs,this.maxExtLength=e?.maxExtLength??cs,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:N6,this.mapKeyConverter=e?.mapKeyConverter??T6}clone(){return new Bu({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=ls,this.stack.reset()}setBuffer(e){const n=xu(e);this.bytes=n,this.view=new DataView(n.buffer,n.byteOffset,n.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===ls&&!this.hasRemaining(1))this.setBuffer(e);else{const n=this.bytes.subarray(this.pos),r=xu(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 ${Iu(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 Dt(`Unrecognized type byte: ${Iu(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const i=r.top();if(i.type===Su)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===us){if(n==="__proto__")throw new Dt("The key __proto__ is not allowed");i.key=this.mapKeyConverter(n),i.type=Wp;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=us;continue e}}return n}}readHeadByte(){return this.headByte===ls&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=ls}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 Dt(`Unrecognized array type byte: ${Iu(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Dt(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Dt(`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 Dt(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+n+e)throw Zp;const r=this.pos+n;let i;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?i=this.keyDecoder.decode(this.bytes,r,e):i=h6(this.bytes,r,e),this.pos+=n+e,i}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===us:!1}decodeBinary(e,n){if(e>this.maxBinLength)throw new Dt(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+n))throw Zp;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 Dt(`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=p6(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Gp(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 C6(t,e){return new Bu(e).decode(t)}function Au(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Yp(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Au(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fs(t,e){e||(e=t.reduce((i,s)=>i+s.length,0));const n=Yp(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return Au(n)}function U6(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var F6=U6,k6=F6;const Xp=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")},L6=t=>new TextEncoder().encode(t),q6=t=>new TextDecoder().decode(t);class M6{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 j6{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 Jp(this,e)}}class z6{constructor(e){this.decoders=e}or(e){return Jp(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 Jp=(t,e)=>new z6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class V6{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new M6(e,n,r),this.decoder=new j6(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ko=({name:t,prefix:e,encode:n,decode:r})=>new V6(t,e,n,r),hs=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=k6(n,e);return Ko({prefix:t,name:e,encode:r,decode:s=>Xp(i(s))})},K6=(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},H6=(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},qe=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ko({prefix:e,name:t,encode(i){return H6(i,r,n)},decode(i){return K6(i,r,n,t)}}),G6=Ko({prefix:"\0",name:"identity",encode:t=>q6(t),decode:t=>L6(t)});var W6=Object.freeze({__proto__:null,identity:G6});const Z6=qe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Y6=Object.freeze({__proto__:null,base2:Z6});const X6=qe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var J6=Object.freeze({__proto__:null,base8:X6});const Q6=hs({prefix:"9",name:"base10",alphabet:"0123456789"});var e4=Object.freeze({__proto__:null,base10:Q6});const t4=qe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),n4=qe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var r4=Object.freeze({__proto__:null,base16:t4,base16upper:n4});const i4=qe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),s4=qe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),o4=qe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),a4=qe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),c4=qe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),u4=qe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),l4=qe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),f4=qe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),h4=qe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var d4=Object.freeze({__proto__:null,base32:i4,base32upper:s4,base32pad:o4,base32padupper:a4,base32hex:c4,base32hexupper:u4,base32hexpad:l4,base32hexpadupper:f4,base32z:h4});const p4=hs({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),g4=hs({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var y4=Object.freeze({__proto__:null,base36:p4,base36upper:g4});const b4=hs({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),w4=hs({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var m4=Object.freeze({__proto__:null,base58btc:b4,base58flickr:w4});const v4=qe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),E4=qe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),x4=qe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),_4=qe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var I4=Object.freeze({__proto__:null,base64:v4,base64pad:E4,base64url:x4,base64urlpad:_4});const Qp=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}"),S4=Qp.reduce((t,e,n)=>(t[n]=e,t),[]),O4=Qp.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function B4(t){return t.reduce((e,n)=>(e+=S4[n],e),"")}function A4(t){const e=[];for(const n of t){const r=O4[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const D4=Ko({prefix:"\u{1F680}",name:"base256emoji",encode:B4,decode:A4});var $4=Object.freeze({__proto__:null,base256emoji:D4}),T4=t0,e0=128,P4=127,R4=~P4,N4=Math.pow(2,31);function t0(t,e,n){e=e||[],n=n||0;for(var r=n;t>=N4;)e[n++]=t&255|e0,t/=128;for(;t&R4;)e[n++]=t&255|e0,t>>>=7;return e[n]=t|0,t0.bytes=n-r+1,e}var C4=Du,U4=128,n0=127;function Du(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Du.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&n0)<<i:(o&n0)*Math.pow(2,i),i+=7}while(o>=U4);return Du.bytes=s-r,n}var F4=Math.pow(2,7),k4=Math.pow(2,14),L4=Math.pow(2,21),q4=Math.pow(2,28),M4=Math.pow(2,35),j4=Math.pow(2,42),z4=Math.pow(2,49),V4=Math.pow(2,56),K4=Math.pow(2,63),H4=function(t){return t<F4?1:t<k4?2:t<L4?3:t<q4?4:t<M4?5:t<j4?6:t<z4?7:t<V4?8:t<K4?9:10},G4={encode:T4,decode:C4,encodingLength:H4},r0=G4;const i0=(t,e,n=0)=>(r0.encode(t,e,n),e),s0=t=>r0.encodingLength(t),$u=(t,e)=>{const n=e.byteLength,r=s0(t),i=r+s0(n),s=new Uint8Array(i+n);return i0(t,s,0),i0(n,s,r),s.set(e,i),new W4(t,n,e,s)};class W4{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const o0=({name:t,code:e,encode:n})=>new Z4(t,e,n);class Z4{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?$u(this.code,n):n.then(r=>$u(this.code,r))}else throw Error("Unknown type, must be binary type")}}const a0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Y4=o0({name:"sha2-256",code:18,encode:a0("SHA-256")}),X4=o0({name:"sha2-512",code:19,encode:a0("SHA-512")});var J4=Object.freeze({__proto__:null,sha256:Y4,sha512:X4});const c0=0,Q4="identity",u0=Xp;var e_=Object.freeze({__proto__:null,identity:{code:c0,name:Q4,encode:u0,digest:t=>$u(c0,u0(t))}});new TextEncoder,new TextDecoder;const l0={...W6,...Y6,...J6,...e4,...r4,...d4,...y4,...m4,...I4,...$4};({...J4,...e_});function f0(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const h0=f0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Tu=f0("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=Yp(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),d0={utf8:h0,"utf-8":h0,hex:l0.base16,latin1:Tu,ascii:Tu,binary:Tu,...l0};function Lt(t,e="utf8"){const n=d0[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Au(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}function mt(t,e="utf8"){const n=d0[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 t_={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"}},n_="Input must be an string, Buffer or Uint8Array";function r_(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(n_);return e}function i_(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Ho(t){return(4294967296+t).toString(16).substring(1)}function s_(t,e,n){let r=`
|
|
17
17
|
`+t+" = ";for(let i=0;i<e.length;i+=2){if(n===32)r+=Ho(e[i]).toUpperCase(),r+=" ",r+=Ho(e[i+1]).toUpperCase();else if(n===64)r+=Ho(e[i+1]).toUpperCase(),r+=Ho(e[i]).toUpperCase();else throw new Error("Invalid size "+n);i%6===4?r+=`
|
|
18
|
-
`+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function o_(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 p0={normalizeInput:r_,toHex:i_,debugPrint:s_,testSpeed:o_};const Go=p0;function Wo(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 g0(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 y0(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function ir(t,e,n,r,i,s){const o=fs[i],a=fs[i+1],c=fs[s],u=fs[s+1];Wo(te,t,e),g0(te,t,o,a);let l=te[r]^te[t],f=te[r+1]^te[t+1];te[r]=f,te[r+1]=l,Wo(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=l>>>24^f<<8,te[e+1]=f>>>24^l<<8,Wo(te,t,e),g0(te,t,c,u),l=te[r]^te[t],f=te[r+1]^te[t+1],te[r]=l>>>16^f<<16,te[r+1]=f>>>16^l<<16,Wo(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=f>>>31^l<<1,te[e+1]=l>>>31^f<<1}const b0=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),a_=[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],Ye=new Uint8Array(a_.map(function(t){return t*2})),te=new Uint32Array(32),fs=new Uint32Array(32);function w0(t,e){let n=0;for(n=0;n<16;n++)te[n]=t.h[n],te[n+16]=b0[n];for(te[24]=te[24]^t.t,te[25]=te[25]^t.t/4294967296,e&&(te[28]=~te[28],te[29]=~te[29]),n=0;n<32;n++)fs[n]=y0(t.b,4*n);for(n=0;n<12;n++)ir(0,8,16,24,Ye[n*16+0],Ye[n*16+1]),ir(2,10,18,26,Ye[n*16+2],Ye[n*16+3]),ir(4,12,20,28,Ye[n*16+4],Ye[n*16+5]),ir(6,14,22,30,Ye[n*16+6],Ye[n*16+7]),ir(0,10,20,30,Ye[n*16+8],Ye[n*16+9]),ir(2,12,22,24,Ye[n*16+10],Ye[n*16+11]),ir(4,14,16,26,Ye[n*16+12],Ye[n*16+13]),ir(6,8,18,28,Ye[n*16+14],Ye[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^te[n]^te[n+16]}const sr=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 m0(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};sr.fill(0),sr[0]=t,e&&(sr[1]=e.length),sr[2]=1,sr[3]=1,n&&sr.set(n,32),r&&sr.set(r,48);for(let s=0;s<16;s++)i.h[s]=b0[s]^y0(sr,s*4);return e&&(Pu(i,e),i.c=128),i}function Pu(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,w0(t,!1),t.c=0),t.b[t.c++]=e[n]}function v0(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;w0(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 E0(t,e,n,r,i){n=n||64,t=Go.normalizeInput(t),r&&(r=Go.normalizeInput(r)),i&&(i=Go.normalizeInput(i));const s=m0(n,e,r,i);return Pu(s,t),v0(s)}function c_(t,e,n,r,i){const s=E0(t,e,n,r,i);return Go.toHex(s)}var u_={blake2b:E0,blake2bHex:c_,blake2bInit:m0,blake2bUpdate:Pu,blake2bFinal:v0};const x0=p0;function l_(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function or(t,e,n,r,i,s){ae[t]=ae[t]+ae[e]+i,ae[r]=Zo(ae[r]^ae[t],16),ae[n]=ae[n]+ae[r],ae[e]=Zo(ae[e]^ae[n],12),ae[t]=ae[t]+ae[e]+s,ae[r]=Zo(ae[r]^ae[t],8),ae[n]=ae[n]+ae[r],ae[e]=Zo(ae[e]^ae[n],7)}function Zo(t,e){return t>>>e^t<<32-e}const _0=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xe=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]),ae=new Uint32Array(16),Me=new Uint32Array(16);function I0(t,e){let n=0;for(n=0;n<8;n++)ae[n]=t.h[n],ae[n+8]=_0[n];for(ae[12]^=t.t,ae[13]^=t.t/4294967296,e&&(ae[14]=~ae[14]),n=0;n<16;n++)Me[n]=l_(t.b,4*n);for(n=0;n<10;n++)or(0,4,8,12,Me[Xe[n*16+0]],Me[Xe[n*16+1]]),or(1,5,9,13,Me[Xe[n*16+2]],Me[Xe[n*16+3]]),or(2,6,10,14,Me[Xe[n*16+4]],Me[Xe[n*16+5]]),or(3,7,11,15,Me[Xe[n*16+6]],Me[Xe[n*16+7]]),or(0,5,10,15,Me[Xe[n*16+8]],Me[Xe[n*16+9]]),or(1,6,11,12,Me[Xe[n*16+10]],Me[Xe[n*16+11]]),or(2,7,8,13,Me[Xe[n*16+12]],Me[Xe[n*16+13]]),or(3,4,9,14,Me[Xe[n*16+14]],Me[Xe[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=ae[n]^ae[n+8]}function S0(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(_0),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Ru(r,e),r.c=64),r}function Ru(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,I0(t,!1),t.c=0),t.b[t.c++]=e[n]}function O0(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;I0(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 B0(t,e,n){n=n||32,t=x0.normalizeInput(t);const r=S0(n,e);return Ru(r,t),O0(r)}function f_(t,e,n){const r=B0(t,e,n);return x0.toHex(r)}var h_={blake2s:B0,blake2sHex:f_,blake2sInit:S0,blake2sUpdate:Ru,blake2sFinal:O0};const hs=u_,ds=h_;var d_={blake2b:hs.blake2b,blake2bHex:hs.blake2bHex,blake2bInit:hs.blake2bInit,blake2bUpdate:hs.blake2bUpdate,blake2bFinal:hs.blake2bFinal,blake2s:ds.blake2s,blake2sHex:ds.blake2sHex,blake2sInit:ds.blake2sInit,blake2sUpdate:ds.blake2sUpdate,blake2sFinal:ds.blake2sFinal},p_=Object.defineProperty,g_=Object.defineProperties,y_=Object.getOwnPropertyDescriptors,A0=Object.getOwnPropertySymbols,b_=Object.prototype.hasOwnProperty,w_=Object.prototype.propertyIsEnumerable,D0=(t,e,n)=>e in t?p_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ei=(t,e)=>{for(var n in e||(e={}))b_.call(e,n)&&D0(t,n,e[n]);if(A0)for(var n of A0(e))w_.call(e,n)&&D0(t,n,e[n]);return t},ps=(t,e)=>g_(t,y_(e));const m_=":";function Pn(t){const[e,n]=t.split(m_);return{namespace:e,reference:n}}function $0(t,e){return t.includes(":")?[t]:e.chains||[]}var v_=Object.defineProperty,E_=Object.defineProperties,x_=Object.getOwnPropertyDescriptors,T0=Object.getOwnPropertySymbols,__=Object.prototype.hasOwnProperty,I_=Object.prototype.propertyIsEnumerable,Nu=(t,e,n)=>e in t?v_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,P0=(t,e)=>{for(var n in e||(e={}))__.call(e,n)&&Nu(t,n,e[n]);if(T0)for(var n of T0(e))I_.call(e,n)&&Nu(t,n,e[n]);return t},S_=(t,e)=>E_(t,x_(e)),R0=(t,e,n)=>Nu(t,typeof e!="symbol"?e+"":e,n);const O_="ReactNative",$t={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},B_="js";function Yo(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function ar(){return!Pr()&&!!bc()&&navigator.product===O_}function A_(){return ar()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function D_(){return ar()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function xi(){return!Yo()&&!!bc()&&!!Pr()}function gs(){return ar()?$t.reactNative:Yo()?$t.node:xi()?$t.browser:$t.unknown}function N0(){var t;try{return ar()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function $_(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 T_(t){var e,n;const r=C0();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!=="")),S_(P0(P0({},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 C0(){return kh()||{name:"",description:"",url:"",icons:[""]}}function P_(){if(gs()===$t.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=EE();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 R_(){var t;const e=gs();return e===$t.browser?[e,((t=Lh())==null?void 0:t.host)||"unknown"].join(":"):e}function U0(t,e,n){const r=P_(),i=R_();return[[t,e].join("-"),[B_,n].join("-"),r,i].join("/")}function N_({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=U0(t,e,r),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=$_(u[1]||"",f);return u[0]+"?"+d}function qr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function Cu(t){return Object.fromEntries(t.entries())}function Uu(t){return new Map(Object.entries(t))}function Mr(t=H.FIVE_MINUTES,e){const n=H.toMiliseconds(t||H.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 cn(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 F0(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 C_(t){return F0("topic",t)}function U_(t){return F0("id",t)}function L0(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 Te(t,e){return H.fromMiliseconds((e||Date.now())+H.toMiliseconds(t))}function cr(t){return Date.now()>=H.toMiliseconds(t)}function de(t,e){return`${t}${e?`:${e}`:""}`}function jr(t=[],e=[]){return[...new Set([...t,...e])]}async function F_({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=L_(s,t,e),a=gs();if(a===$t.browser){if(!((r=Pr())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}k_(o)}else a===$t.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function L_(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}${z_(r,!0)}`}else i=`${i}/wc?${r}`;return i}function k_(t){let e="_self";j_()?e="_top":(M_()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function q_(t,e){let n="";try{if(xi()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function k0(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function q0(){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 Fu(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function M_(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function j_(){try{return window.self!==window.top}catch{return!1}}function z_(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function M0(t){return Buffer.from(t,"base64").toString("utf-8")}function V_(t){return new Promise(e=>setTimeout(e,t))}class K_{constructor({limit:e}){R0(this,"limit"),R0(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 Xo=BigInt(2**32-1),j0=BigInt(32);function z0(t,e=!1){return e?{h:Number(t&Xo),l:Number(t>>j0&Xo)}:{h:Number(t>>j0&Xo)|0,l:Number(t&Xo)|0}}function V0(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}=z0(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const K0=(t,e,n)=>t>>>n,H0=(t,e,n)=>t<<32-n|e>>>n,ur=(t,e,n)=>t>>>n|e<<32-n,lr=(t,e,n)=>t<<32-n|e>>>n,ys=(t,e,n)=>t<<64-n|e>>>n-32,bs=(t,e,n)=>t>>>n-32|e<<64-n,H_=(t,e)=>e,G_=(t,e)=>t,W_=(t,e,n)=>t<<n|e>>>32-n,Z_=(t,e,n)=>e<<n|t>>>32-n,Y_=(t,e,n)=>e<<n-32|t>>>64-n,X_=(t,e,n)=>t<<n-32|e>>>64-n;function Yt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const Lu=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),ku=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,J_=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Q_=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,e5=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),t5=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,_i=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Jo(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 Xt(t,...e){if(!Jo(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 Qo(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 fr(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 qu(t,e){Xt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function ws(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Mu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function un(t,e){return t<<32-e|t>>>e}const G0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function W0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Nn=G0?t=>t:t=>W0(t);function n5(t){for(let e=0;e<t.length;e++)t[e]=W0(t[e]);return t}const hr=G0?t=>t:n5,Z0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",r5=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ii(t){if(Xt(t),Z0)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=r5[t[n]];return e}const Cn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Y0(t){if(t>=Cn._0&&t<=Cn._9)return t-Cn._0;if(t>=Cn.A&&t<=Cn.F)return t-(Cn.A-10);if(t>=Cn.a&&t<=Cn.f)return t-(Cn.a-10)}function ea(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Z0)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=Y0(t.charCodeAt(s)),a=Y0(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 X0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Jt(t){return typeof t=="string"&&(t=X0(t)),Xt(t),t}function dr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Xt(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 ta{}function ms(t){const e=r=>t().update(Jt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function i5(t){const e=(r,i)=>t(i).update(Jt(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function zr(t=32){if(_i&&typeof _i.getRandomValues=="function")return _i.getRandomValues(new Uint8Array(t));if(_i&&typeof _i.randomBytes=="function")return Uint8Array.from(_i.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const s5=BigInt(0),vs=BigInt(1),o5=BigInt(2),a5=BigInt(7),c5=BigInt(256),u5=BigInt(113),J0=[],Q0=[],eg=[];for(let t=0,e=vs,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],J0.push(2*(5*r+n)),Q0.push((t+1)*(t+2)/2%64);let i=s5;for(let s=0;s<7;s++)e=(e<<vs^(e>>a5)*u5)%c5,e&o5&&(i^=vs<<(vs<<BigInt(s))-vs);eg.push(i)}const tg=V0(eg,!0),l5=tg[0],f5=tg[1],ng=(t,e,n)=>n>32?Y_(t,e,n):W_(t,e,n),rg=(t,e,n)=>n>32?X_(t,e,n):Z_(t,e,n);function h5(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=ng(u,l,1)^n[a],d=rg(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Q0[o],c=ng(i,s,a),u=rg(i,s,a),l=J0[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]^=l5[r],t[1]^=f5[r]}qt(n)}class ju extends ta{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=ws(this.state)}clone(){return this._cloneInto()}keccak(){hr(this.state32),h5(this.state32,this.rounds),hr(this.state32),this.posOut=0,this.pos=0}update(e){fr(this),e=Jt(e),Xt(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){fr(this,!1),Xt(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(qu(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,qt(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ju(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 d5=(t,e,n)=>ms(()=>new ju(e,t,n)),p5=d5(1,136,256/8);function g5(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 y5(t,e,n){return t&e^~t&n}function b5(t,e,n){return t&e^t&n^e&n}class ig extends ta{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=Mu(this.buffer)}update(e){fr(this),e=Jt(e),Xt(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=Mu(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){fr(this),qu(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qt(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;g5(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Mu(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 pr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Je=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Qe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),w5=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]),gr=new Uint32Array(64);class m5 extends ig{constructor(e=32){super(64,e,8,!1),this.A=pr[0]|0,this.B=pr[1]|0,this.C=pr[2]|0,this.D=pr[3]|0,this.E=pr[4]|0,this.F=pr[5]|0,this.G=pr[6]|0,this.H=pr[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)gr[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=gr[f-15],h=gr[f-2],p=un(d,7)^un(d,18)^d>>>3,g=un(h,17)^un(h,19)^h>>>10;gr[f]=g+gr[f-7]+p+gr[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 d=un(a,6)^un(a,11)^un(a,25),h=l+d+y5(a,c,u)+w5[f]+gr[f]|0,p=(un(r,2)^un(r,13)^un(r,22))+b5(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+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(){qt(gr)}destroy(){this.set(0,0,0,0,0,0,0,0),qt(this.buffer)}}const sg=V0(["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))),v5=sg[0],E5=sg[1],yr=new Uint32Array(80),br=new Uint32Array(80);class zu extends ig{constructor(e=64){super(128,e,16,!1),this.Ah=Qe[0]|0,this.Al=Qe[1]|0,this.Bh=Qe[2]|0,this.Bl=Qe[3]|0,this.Ch=Qe[4]|0,this.Cl=Qe[5]|0,this.Dh=Qe[6]|0,this.Dl=Qe[7]|0,this.Eh=Qe[8]|0,this.El=Qe[9]|0,this.Fh=Qe[10]|0,this.Fl=Qe[11]|0,this.Gh=Qe[12]|0,this.Gl=Qe[13]|0,this.Hh=Qe[14]|0,this.Hl=Qe[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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)yr[x]=e.getUint32(n),br[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=yr[x-15]|0,T=br[x-15]|0,P=ur(_,T,1)^ur(_,T,8)^K0(_,T,7),C=lr(_,T,1)^lr(_,T,8)^H0(_,T,7),U=yr[x-2]|0,D=br[x-2]|0,j=ur(U,D,19)^ys(U,D,61)^K0(U,D,6),M=lr(U,D,19)^bs(U,D,61)^H0(U,D,6),E=J_(C,M,br[x-7],br[x-16]),b=Q_(E,P,j,yr[x-7],yr[x-16]);yr[x]=b|0,br[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=ur(f,d,14)^ur(f,d,18)^ys(f,d,41),T=lr(f,d,14)^lr(f,d,18)^bs(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=e5($,T,C,E5[x],br[x]),D=t5(U,B,_,P,v5[x],yr[x]),j=U|0,M=ur(r,i,28)^ys(r,i,34)^ys(r,i,39),E=lr(r,i,28)^bs(r,i,34)^bs(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=Yt(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=Lu(j,E,v);r=ku(y,D,M,b),i=y|0}({h:r,l:i}=Yt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Yt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Yt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Yt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=Yt(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=Yt(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=Yt(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=Yt(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){qt(yr,br)}destroy(){qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class x5 extends zu{constructor(){super(48),this.Ah=Je[0]|0,this.Al=Je[1]|0,this.Bh=Je[2]|0,this.Bl=Je[3]|0,this.Ch=Je[4]|0,this.Cl=Je[5]|0,this.Dh=Je[6]|0,this.Dl=Je[7]|0,this.Eh=Je[8]|0,this.El=Je[9]|0,this.Fh=Je[10]|0,this.Fl=Je[11]|0,this.Gh=Je[12]|0,this.Gl=Je[13]|0,this.Hh=Je[14]|0,this.Hl=Je[15]|0}}const et=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _5 extends zu{constructor(){super(32),this.Ah=et[0]|0,this.Al=et[1]|0,this.Bh=et[2]|0,this.Bl=et[3]|0,this.Ch=et[4]|0,this.Cl=et[5]|0,this.Dh=et[6]|0,this.Dl=et[7]|0,this.Eh=et[8]|0,this.El=et[9]|0,this.Fh=et[10]|0,this.Fl=et[11]|0,this.Gh=et[12]|0,this.Gl=et[13]|0,this.Hh=et[14]|0,this.Hl=et[15]|0}}const na=ms(()=>new m5),I5=ms(()=>new zu),S5=ms(()=>new x5),O5=ms(()=>new _5),B5=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]),Pe=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Y=new Uint32Array(32);function wr(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],g=Y[2*r+1],m=Lu(c,l,o);u=ku(m,u,f,a),c=m|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:H_(g,p),Dl:G_(g)},{h,l:d}=Yt(h,d,g,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:ur(f,l,24),Bl:lr(f,l,24)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=g}function mr(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],g=Y[2*r+1],m=Lu(c,l,o);u=ku(m,u,f,a),c=m|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:ur(g,p,16),Dl:lr(g,p,16)},{h,l:d}=Yt(h,d,g,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:ys(f,l,63),Bl:bs(f,l,63)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=g}function A5(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 D5 extends ta{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=ws(this.buffer)}update(e){fr(this),e=Jt(e),Xt(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&&(hr(i),this.compress(i,0,!1),hr(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));hr(f);for(let d=0;c+n<s;d+=i.length,c+=n)this.length+=n,this.compress(f,d,!1);hr(f);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){fr(this),qu(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,qt(this.buffer.subarray(n)),hr(r),this.compress(r,0,!0),hr(r);const i=ws(e);this.get().forEach((s,o)=>i[o]=Nn(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 $5 extends D5{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Pe[0]|0,this.v0h=Pe[1]|0,this.v1l=Pe[2]|0,this.v1h=Pe[3]|0,this.v2l=Pe[4]|0,this.v2h=Pe[5]|0,this.v3l=Pe[6]|0,this.v3h=Pe[7]|0,this.v4l=Pe[8]|0,this.v4h=Pe[9]|0,this.v5l=Pe[10]|0,this.v5h=Pe[11]|0,this.v6l=Pe[12]|0,this.v6h=Pe[13]|0,this.v7l=Pe[14]|0,this.v7h=Pe[15]|0,A5(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Jt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Jt(s);const a=ws(s);this.v4l^=Nn(a[0]),this.v4h^=Nn(a[1]),this.v5l^=Nn(a[2]),this.v5h^=Nn(a[3])}if(i!==void 0){i=Jt(i);const a=ws(i);this.v6l^=Nn(a[0]),this.v6h^=Nn(a[1]),this.v7l^=Nn(a[2]),this.v7h^=Nn(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:d,v6l:h,v6h:p,v7l:g,v7h:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.v6l=h|0,this.v6h=p|0,this.v7l=g|0,this.v7h=m|0}compress(e,n,r){this.get().forEach((c,u)=>Y[u]=c),Y.set(Pe,16);let{h:i,l:s}=z0(BigInt(this.length));Y[24]=Pe[8]^s,Y[25]=Pe[9]^i,r&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=B5;for(let c=0;c<12;c++)wr(0,4,8,12,e,n+2*a[o++]),mr(0,4,8,12,e,n+2*a[o++]),wr(1,5,9,13,e,n+2*a[o++]),mr(1,5,9,13,e,n+2*a[o++]),wr(2,6,10,14,e,n+2*a[o++]),mr(2,6,10,14,e,n+2*a[o++]),wr(3,7,11,15,e,n+2*a[o++]),mr(3,7,11,15,e,n+2*a[o++]),wr(0,5,10,15,e,n+2*a[o++]),mr(0,5,10,15,e,n+2*a[o++]),wr(1,6,11,12,e,n+2*a[o++]),mr(1,6,11,12,e,n+2*a[o++]),wr(2,7,8,13,e,n+2*a[o++]),mr(2,7,8,13,e,n+2*a[o++]),wr(3,4,9,14,e,n+2*a[o++]),mr(3,4,9,14,e,n+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],qt(Y)}destroy(){this.destroyed=!0,qt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const T5=i5(t=>new $5(t)),P5="https://rpc.walletconnect.org/v1";function og(t){const e=`Ethereum Signed Message:
|
|
19
|
-
${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(p5(n)).toString("hex")}async function R5(t,e,n,r,i,s){switch(n.t){case"eip191":return await N5(t,e,n.s);case"eip1271":return await C5(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function N5(t,e,n){const r=F8(n);return
|
|
20
|
-
- ${m}`).join("")}`:void 0,g=sa(t.resources);if(g){const m=
|
|
21
|
-
`)};function Q5(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function eI(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Vr(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(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 tI(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:nI(e,n,r)}}}function nI(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function pg(t){return Vr(t),`urn:recap:${Q5(t).replace(/=/g,"")}`}function Es(t){const e=eI(t.replace("urn:recap:",""));return Vr(e),e}function rI(t,e,n){const r=tI(t,e,n);return pg(r)}function iI(t){return t&&t.includes("urn:recap:")}function sI(t,e){const n=Es(t),r=Es(e),i=oI(n,r);return pg(i)}function oI(t,e){Vr(t),Vr(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]=W5(G5({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function aI(t="",e){Vr(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,d)=>f.action.localeCompare(d.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 gg(t){var e;const n=Es(t);Vr(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function yg(t){const e=Es(t);Vr(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 sa(t){if(!t)return;const e=t?.[t.length-1];return iI(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function bg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hu(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Gu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!bg(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 wg(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 cI(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 vr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Si(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function uI(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const lI=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fI(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Wu(t){if(typeof t=="string")t=fI(t);else if(bg(t))t=Zu(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function hI(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function dI(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 pI=(t,e)=>{function n(r,...i){if(vt(r),!lI)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?vt(u):vt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&vt(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");vt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,vt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(vt(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 mg(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&&!yI(e))throw new Error("invalid output, must be aligned");return e}function vg(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 gI(t,e,n){Hu(n);const r=new Uint8Array(16),i=uI(r);return vg(i,0,BigInt(e),n),vg(i,8,BigInt(t),n),r}function yI(t){return t.byteOffset%4===0}function Zu(t){return Uint8Array.from(t)}const Eg=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),bI=Eg("expand 16-byte k"),wI=Eg("expand 32-byte k"),mI=vr(bI),vI=vr(wI);function ce(t,e){return t<<e|t>>>32-e}function Yu(t){return t.byteOffset%4===0}const oa=64,EI=16,xg=2**32-1,_g=new Uint32Array;function xI(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(oa),l=vr(u),f=Yu(i)&&Yu(s),d=f?vr(i):_g,h=f?vr(s):_g;for(let p=0;p<c;o++){if(t(e,n,r,l,o,a),o>=xg)throw new Error("arx: counter overflow");const g=Math.min(oa,c-p);if(f&&g===oa){const m=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let B=0,$;B<EI;B++)$=m+B,h[$]=d[$]^l[B];p+=oa;continue}for(let m=0,B;m<g;m++)B=p+m,s[B]=i[B]^u[m];p+=g}}function _I(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=hI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Gu(i),Gu(o),Hu(s),Hu(n),(a,c,u,l,f=0)=>{vt(a),vt(c),vt(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),vt(l),Gu(f),f<0||f>=xg)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let p=a.length,g,m;if(p===32)h.push(g=Zu(a)),m=vI;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),m=mI,h.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Yu(c)||h.push(c=Zu(c));const B=vr(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(m,B,vr(c.subarray(0,16)),B),c=c.subarray(16)}const $=16-i;if($!==c.length)throw new Error(`arx: nonce must be ${$} or 16 bytes`);if($!==12){const _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,h.push(c)}const x=vr(c);return xI(t,m,B,x,u,l,f,o),Si(...h),l}}const je=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class II{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=Wu(e),vt(e,32);const n=je(e,0),r=je(e,2),i=je(e,4),s=je(e,6),o=je(e,8),a=je(e,10),c=je(e,12),u=je(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]=je(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],d=o[5],h=o[6],p=o[7],g=o[8],m=o[9],B=je(e,n+0),$=je(e,n+2),x=je(e,n+4),_=je(e,n+6),T=je(e,n+8),P=je(e,n+10),C=je(e,n+12),U=je(e,n+14);let D=s[0]+(B&8191),j=s[1]+((B>>>13|$<<3)&8191),M=s[2]+(($>>>10|x<<6)&8191),E=s[3]+((x>>>7|_<<9)&8191),b=s[4]+((_>>>4|T<<12)&8191),v=s[5]+(T>>>1&8191),y=s[6]+((T>>>14|P<<2)&8191),w=s[7]+((P>>>11|C<<5)&8191),I=s[8]+((C>>>8|U<<8)&8191),O=s[9]+(U>>>5|i),S=0,A=S+D*a+j*(5*m)+M*(5*g)+E*(5*p)+b*(5*h);S=A>>>13,A&=8191,A+=v*(5*d)+y*(5*f)+w*(5*l)+I*(5*u)+O*(5*c),S+=A>>>13,A&=8191;let R=S+D*c+j*a+M*(5*m)+E*(5*g)+b*(5*p);S=R>>>13,R&=8191,R+=v*(5*h)+y*(5*d)+w*(5*f)+I*(5*l)+O*(5*u),S+=R>>>13,R&=8191;let L=S+D*u+j*c+M*a+E*(5*m)+b*(5*g);S=L>>>13,L&=8191,L+=v*(5*p)+y*(5*h)+w*(5*d)+I*(5*f)+O*(5*l),S+=L>>>13,L&=8191;let F=S+D*l+j*u+M*c+E*a+b*(5*m);S=F>>>13,F&=8191,F+=v*(5*g)+y*(5*p)+w*(5*h)+I*(5*d)+O*(5*f),S+=F>>>13,F&=8191;let k=S+D*f+j*l+M*u+E*c+b*a;S=k>>>13,k&=8191,k+=v*(5*m)+y*(5*g)+w*(5*p)+I*(5*h)+O*(5*d),S+=k>>>13,k&=8191;let N=S+D*d+j*f+M*l+E*u+b*c;S=N>>>13,N&=8191,N+=v*a+y*(5*m)+w*(5*g)+I*(5*p)+O*(5*h),S+=N>>>13,N&=8191;let q=S+D*h+j*d+M*f+E*l+b*u;S=q>>>13,q&=8191,q+=v*c+y*a+w*(5*m)+I*(5*g)+O*(5*p),S+=q>>>13,q&=8191;let z=S+D*p+j*h+M*d+E*f+b*l;S=z>>>13,z&=8191,z+=v*u+y*c+w*a+I*(5*m)+O*(5*g),S+=z>>>13,z&=8191;let W=S+D*g+j*p+M*h+E*d+b*f;S=W>>>13,W&=8191,W+=v*l+y*u+w*c+I*a+O*(5*m),S+=W>>>13,W&=8191;let K=S+D*m+j*g+M*p+E*h+b*d;S=K>>>13,K&=8191,K+=v*f+y*l+w*u+I*c+O*a,S+=K>>>13,K&=8191,S=(S<<2)+S|0,S=S+A|0,A=S&8191,S=S>>>13,R+=S,s[0]=A,s[1]=R,s[2]=L,s[3]=F,s[4]=k,s[5]=N,s[6]=q,s[7]=z,s[8]=W,s[9]=K}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;Si(r)}update(e){wg(this),e=Wu(e),vt(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(){Si(this.h,this.r,this.buffer,this.pad)}digestInto(e){wg(this),cI(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 SI(t){const e=(r,i)=>t(i).update(Wu(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const OI=SI(t=>new II(t));function BI(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],d=e[2],h=e[3],p=e[4],g=e[5],m=e[6],B=e[7],$=i,x=n[0],_=n[1],T=n[2],P=o,C=a,U=c,D=u,j=l,M=f,E=d,b=h,v=p,y=g,w=m,I=B,O=$,S=x,A=_,R=T;for(let F=0;F<s;F+=2)P=P+j|0,O=ce(O^P,16),v=v+O|0,j=ce(j^v,12),P=P+j|0,O=ce(O^P,8),v=v+O|0,j=ce(j^v,7),C=C+M|0,S=ce(S^C,16),y=y+S|0,M=ce(M^y,12),C=C+M|0,S=ce(S^C,8),y=y+S|0,M=ce(M^y,7),U=U+E|0,A=ce(A^U,16),w=w+A|0,E=ce(E^w,12),U=U+E|0,A=ce(A^U,8),w=w+A|0,E=ce(E^w,7),D=D+b|0,R=ce(R^D,16),I=I+R|0,b=ce(b^I,12),D=D+b|0,R=ce(R^D,8),I=I+R|0,b=ce(b^I,7),P=P+M|0,R=ce(R^P,16),w=w+R|0,M=ce(M^w,12),P=P+M|0,R=ce(R^P,8),w=w+R|0,M=ce(M^w,7),C=C+E|0,O=ce(O^C,16),I=I+O|0,E=ce(E^I,12),C=C+E|0,O=ce(O^C,8),I=I+O|0,E=ce(E^I,7),U=U+b|0,S=ce(S^U,16),v=v+S|0,b=ce(b^v,12),U=U+b|0,S=ce(S^U,8),v=v+S|0,b=ce(b^v,7),D=D+j|0,A=ce(A^D,16),y=y+A|0,j=ce(j^y,12),D=D+j|0,A=ce(A^D,8),y=y+A|0,j=ce(j^y,7);let L=0;r[L++]=o+P|0,r[L++]=a+C|0,r[L++]=c+U|0,r[L++]=u+D|0,r[L++]=l+j|0,r[L++]=f+M|0,r[L++]=d+E|0,r[L++]=h+b|0,r[L++]=p+v|0,r[L++]=g+y|0,r[L++]=m+w|0,r[L++]=B+I|0,r[L++]=$+O|0,r[L++]=x+S|0,r[L++]=_+A|0,r[L++]=T+R|0}const AI=_I(BI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),DI=new Uint8Array(16),Ig=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(DI.subarray(n))},$I=new Uint8Array(32);function Sg(t,e,n,r,i){const s=t(e,n,$I),o=OI.create(s);i&&Ig(o,i),Ig(o,r);const a=gI(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Si(s,a),c}const TI=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=mg(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Sg(t,e,n,a,r);return s.set(c,o),Si(c),s},decrypt(i,s){s=mg(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Sg(t,e,n,o,r);if(!dI(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Si(c),s}}),Og=pI({blockSize:64,nonceLength:12,tagLength:16},TI(AI));class Bg extends ta{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Qo(e);const r=Jt(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),qt(s)}update(e){return fr(this),this.iHash.update(e),this}digestInto(e){fr(this),Xt(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 aa=(t,e,n)=>new Bg(t,e).update(n).digest();aa.create=(t,e)=>new Bg(t,e);function PI(t,e,n){return Qo(t),n===void 0&&(n=new Uint8Array(t.outputLen)),aa(t,Jt(n),Jt(e))}const Xu=Uint8Array.from([0]),Ag=Uint8Array.of();function RI(t,e,n,r=32){Qo(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=Ag);const o=new Uint8Array(s*i),a=aa.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Xu[0]=l+1,c.update(l===0?Ag:u).update(n).update(Xu).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),qt(u,Xu),o.slice(0,r)}const NI=(t,e,n,r,i)=>RI(t,PI(t,e,n),r,i),ca=na,Ju=BigInt(0),Qu=BigInt(1);function ua(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Kr(t,e,n=""){const r=Jo(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 la(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Dg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ju:BigInt("0x"+t)}function fa(t){return Dg(Ii(t))}function ha(t){return Xt(t),Dg(Ii(Uint8Array.from(t).reverse()))}function el(t,e){return ea(t.toString(16).padStart(e*2,"0"))}function tl(t,e){return el(t,e).reverse()}function tt(t,e,n){let r;if(typeof e=="string")try{r=ea(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Jo(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 nl=t=>typeof t=="bigint"&&Ju<=t;function CI(t,e,n){return nl(t)&&nl(e)&&nl(n)&&e<=t&&t<n}function rl(t,e,n,r){if(!CI(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $g(t){let e;for(e=0;t>Ju;t>>=Qu,e+=1);return e}const xs=t=>(Qu<<BigInt(t))-Qu;function UI(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 h=[];for(;d<e;){s=u();const p=s.slice();h.push(p),d+=s.length}return dr(...h)};return(d,h)=>{c(),l(d);let p;for(;!(p=h(f()));)l();return c(),p}}function da(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 Tg(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 Et=BigInt(0),ut=BigInt(1),Hr=BigInt(2),Pg=BigInt(3),Rg=BigInt(4),Ng=BigInt(5),FI=BigInt(7),Cg=BigInt(8),LI=BigInt(9),Ug=BigInt(16);function Tt(t,e){const n=t%e;return n>=Et?n:e+n}function Qt(t,e,n){let r=t;for(;e-- >Et;)r*=r,r%=n;return r}function Fg(t,e){if(t===Et)throw new Error("invert: expected non-zero number");if(e<=Et)throw new Error("invert: expected positive modulus, got "+e);let n=Tt(t,e),r=e,i=Et,s=ut;for(;n!==Et;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==ut)throw new Error("invert: does not exist");return Tt(i,e)}function il(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function Lg(t,e){const n=(t.ORDER+ut)/Rg,r=t.pow(e,n);return il(t,r,e),r}function kI(t,e){const n=(t.ORDER-Ng)/Cg,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 il(t,a,e),a}function qI(t){const e=Er(t),n=kg(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+FI)/Ug;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const g=a.eql(a.sqr(l),c),m=a.cmov(u,l,g);return il(a,m,c),m}}function kg(t){if(t<Pg)throw new Error("sqrt is not defined for small field");let e=t-ut,n=0;for(;e%Hr===Et;)e/=Hr,n++;let r=Hr;const i=Er(t);for(;Mg(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return Lg;let s=i.pow(r,e);const o=(e+ut)/Hr;return function(a,c){if(a.is0(c))return c;if(Mg(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),f=a.pow(c,e),d=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(h++,p=a.sqr(p),h===u)throw new Error("Cannot find square root");const g=ut<<BigInt(u-h-1),m=a.pow(l,g);u=h,l=a.sqr(m),f=a.mul(f,l),d=a.mul(d,m)}return d}}function MI(t){return t%Rg===Pg?Lg:t%Cg===Ng?kI:t%Ug===LI?qI(t):kg(t)}const jI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zI(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=jI.reduce((r,i)=>(r[i]="function",r),e);return da(t,n),t}function VI(t,e,n){if(n<Et)throw new Error("invalid exponent, negatives unsupported");if(n===Et)return t.ONE;if(n===ut)return e;let r=t.ONE,i=e;for(;n>Et;)n&ut&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ut;return r}function qg(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 Mg(t,e){const n=(t.ORDER-ut)/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 jg(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 Er(t,e,n=!1,r={}){if(t<=Et)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 d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=jg(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:xs(c),ZERO:Et,ONE:ut,allowedLengths:a,create:d=>Tt(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Et<=d&&d<t},is0:d=>d===Et,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ut)===ut,neg:d=>Tt(-d,t),eql:(d,h)=>d===h,sqr:d=>Tt(d*d,t),add:(d,h)=>Tt(d+h,t),sub:(d,h)=>Tt(d-h,t),mul:(d,h)=>Tt(d*h,t),pow:(d,h)=>VI(f,d,h),div:(d,h)=>Tt(d*Fg(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Fg(d,t),sqrt:s||(d=>(l||(l=MI(t)),l(f,d))),toBytes:d=>n?tl(d,u):el(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const g=new Uint8Array(u);g.set(d,n?0:g.length-d.length),d=g}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?ha(d):fa(d);if(o&&(p=Tt(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>qg(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function zg(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 Vg(t){const e=zg(t);return e+Math.ceil(e/2)}function KI(t,e,n=!1){const r=t.length,i=zg(e),s=Vg(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ha(t):fa(t),a=Tt(o,e-ut)+ut;return n?tl(a,i):el(a,i)}const Oi=BigInt(0),Gr=BigInt(1);function pa(t,e){const n=e.negate();return t?n:e}function sl(t,e){const n=qg(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Kg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ol(t,e){Kg(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 Hg(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+=Gr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function HI(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 GI(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 al=new WeakMap,Gg=new WeakMap;function cl(t){return Gg.get(t)||1}function Wg(t){if(t!==Oi)throw new Error("invalid wNAF")}class WI{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>Oi;)n&Gr&&(r=r.add(i)),i=i.double(),n>>=Gr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=ol(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=ol(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=Hg(r,a,o);r=c,l?s=s.add(pa(d,n[h])):i=i.add(pa(f,n[u]))}return Wg(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=ol(e,this.bits);for(let o=0;o<s.windows&&r!==Oi;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Hg(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return Wg(r),i}getPrecomputes(e,n,r){let i=al.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),al.set(n,i))),i}cached(e,n,r){const i=cl(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=cl(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Kg(n,this.bits),Gg.set(e,n),al.delete(e)}hasCache(e){return cl(e)!==1}}function ZI(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Oi||r>Oi;)n&Gr&&(s=s.add(i)),r&Gr&&(o=o.add(i)),i=i.double(),n>>=Gr,r>>=Gr;return{p1:s,p2:o}}function YI(t,e,n,r){HI(n,t),GI(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=$g(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),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Zg(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zI(e),e}else return Er(t,{isLE:n})}function XI(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>Oi))throw new Error(`CURVE.${a} must be positive bigint`)}const i=Zg(e.p,n.Fp,r),s=Zg(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),X0("HashToScalar-");const _s=BigInt(0),Bi=BigInt(1),ga=BigInt(2);function JI(t){return da(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(Ei({},t))}function QI(t){const e=JI(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||zr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?ga**BigInt(254):ga**BigInt(447),p=a?BigInt(8)*ga**BigInt(251)-Bi:BigInt(4)*ga**BigInt(445)-Bi,g=h+p+Bi,m=E=>Tt(E,n),B=$(f);function $(E){return tl(m(E),l)}function x(E){const b=tt("u coordinate",E,l);return a&&(b[31]&=127),m(ha(b))}function _(E){return ha(i(tt("scalar",E,l)))}function T(E,b){const v=U(x(b),_(E));if(v===_s)throw new Error("invalid private or public key received");return $(v)}function P(E){return T(E,B)}function C(E,b,v){const y=m(E*(b-v));return b=m(b-y),v=m(v+y),{x_2:b,x_3:v}}function U(E,b){rl("u",E,_s,n),rl("scalar",b,h,g);const v=b,y=E;let w=Bi,I=_s,O=E,S=Bi,A=_s;for(let L=BigInt(u-1);L>=_s;L--){const F=v>>L&Bi;A^=F,{x_2:w,x_3:O}=C(A,w,O),{x_2:I,x_3:S}=C(A,I,S),A=F;const k=w+I,N=m(k*k),q=w-I,z=m(q*q),W=N-z,K=O+S,Z=O-S,Q=m(Z*k),ee=m(K*q),ie=Q+ee,he=Q-ee;O=m(ie*ie),S=m(y*m(he*he)),w=m(N*z),I=m(W*(N+m(d*W)))}({x_2:w,x_3:O}=C(A,w,O)),{x_2:I,x_3:S}=C(A,I,S);const R=s(I);return m(w*R)}const D={secretKey:l,publicKey:l,seed:l},j=(E=c(l))=>(Xt(E,D.seed),E);function M(E){const b=j(E);return{secretKey:b,publicKey:P(b)}}return{keygen:M,getSharedSecret:(E,b)=>T(E,b),getPublicKey:E=>P(E),scalarMult:T,scalarMultBase:P,utils:{randomSecretKey:j,randomPrivateKey:j},GuBytes:B.slice(),lengths:D}}const eS=BigInt(1),Yg=BigInt(2),tS=BigInt(3),nS=BigInt(5),rS=BigInt(8),Xg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),iS={p:Xg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:rS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sS(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Xg,o=t*t%s*t%s,a=Qt(o,Yg,s)*o%s,c=Qt(a,eS,s)*t%s,u=Qt(c,nS,s)*c%s,l=Qt(u,e,s)*u%s,f=Qt(l,n,s)*l%s,d=Qt(f,r,s)*f%s,h=Qt(d,i,s)*d%s,p=Qt(h,i,s)*d%s,g=Qt(p,e,s)*u%s;return{pow_p_5_8:Qt(g,Yg,s)*t%s,b2:o}}function oS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const aS=Er(iS.p,{isLE:!0}),ul=(()=>{const t=aS.ORDER;return QI({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=sS(e);return Tt(Qt(n,tS,t)*r,t)},adjustScalarBytes:oS})})(),Jg=(t,e)=>(t+(t>=0?e:-e)/Qg)/e;function cS(t,e,n){const[[r,i],[s,o]]=e,a=Jg(o*t,n),c=Jg(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<Fn,d=l<Fn;f&&(u=-u),d&&(l=-l);const h=xs(Math.ceil($g(n)/2))+Ai;if(u<Fn||u>=h||l<Fn||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function ll(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function fl(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return ua(n.lowS,"lowS"),ua(n.prehash,"prehash"),n.format!==void 0&&ll(n.format),n}class uS extends Error{constructor(e=""){super(e)}}const Un={Err:uS,_tlv:{encode:(t,e)=>{const{Err:n}=Un;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=la(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?la(i.length/2|128):"";return la(t)+s+i+e},decode(t,e){const{Err:n}=Un;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}=Un;if(t<Fn)throw new e("integer: negative integers are not allowed");let n=la(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}=Un;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 fa(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Un,i=tt("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}=Un,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Fn=BigInt(0),Ai=BigInt(1),Qg=BigInt(2),ya=BigInt(3),lS=BigInt(4);function Di(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=tt("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 fS(t,e={}){const n=XI("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;da(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=t1(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,b,v){const{x:y,y:w}=b.toAffine(),I=r.toBytes(y);if(ua(v,"isCompressed"),v){l();const O=!r.isOdd(w);return dr(e1(O),I)}else return dr(Uint8Array.of(4),I,r.toBytes(w))}function d(E){Kr(E,void 0,"Point");const{publicKey:b,publicKeyUncompressed:v}=u,y=E.length,w=E[0],I=E.subarray(1);if(y===b&&(w===2||w===3)){const O=r.fromBytes(I);if(!r.isValid(O))throw new Error("bad point: is not on curve, wrong x");const S=g(O);let A;try{A=r.sqrt(S)}catch(L){const F=L instanceof Error?": "+L.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}l();const R=r.isOdd(A);return(w&1)===1!==R&&(A=r.neg(A)),{x:O,y:A}}else if(y===v&&w===4){const O=r.BYTES,S=r.fromBytes(I.subarray(0,O)),A=r.fromBytes(I.subarray(O,O*2));if(!m(S,A))throw new Error("bad point: is not on curve");return{x:S,y:A}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${v}`)}const h=e.toBytes||f,p=e.fromBytes||d;function g(E){const b=r.sqr(E),v=r.mul(b,E);return r.add(r.add(v,r.mul(E,s.a)),s.b)}function m(E,b){const v=r.sqr(b),y=g(E);return r.eql(v,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,ya),lS),$=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,$)))throw new Error("bad curve params: a or b");function x(E,b,v=!1){if(!r.isValid(b)||v&&r.is0(b))throw new Error(`bad point coordinate ${E}`);return b}function _(E){if(!(E instanceof D))throw new Error("ProjectivePoint expected")}function T(E){if(!c||!c.basises)throw new Error("no endo");return cS(E,c.basises,i.ORDER)}const P=Tg((E,b)=>{const{X:v,Y:y,Z:w}=E;if(r.eql(w,r.ONE))return{x:v,y};const I=E.is0();b==null&&(b=I?r.ONE:r.inv(w));const O=r.mul(v,b),S=r.mul(y,b),A=r.mul(w,b);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:O,y:S}}),C=Tg(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:v}=E.toAffine();if(!r.isValid(b)||!r.isValid(v))throw new Error("bad point: x or y not field elements");if(!m(b,v))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(E,b,v,y,w){return v=new D(r.mul(v.X,E),v.Y,v.Z),b=pa(y,b),v=pa(w,v),b.add(v)}class D{constructor(b,v,y){this.X=x("x",b),this.Y=x("y",v,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:v,y}=b||{};if(!b||!r.isValid(v)||!r.isValid(y))throw new Error("invalid affine point");if(b instanceof D)throw new Error("projective point not allowed");return r.is0(v)&&r.is0(y)?D.ZERO:new D(v,y,r.ONE)}static fromBytes(b){const v=D.fromAffine(p(Kr(b,void 0,"point")));return v.assertValidity(),v}static fromHex(b){return D.fromBytes(tt("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return M.createCache(this,b),v||this.multiply(ya),this}assertValidity(){C(this)}hasEvenY(){const{y:b}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(b)}equals(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b,A=r.eql(r.mul(v,S),r.mul(I,w)),R=r.eql(r.mul(y,S),r.mul(O,w));return A&&R}negate(){return new D(this.X,r.neg(this.Y),this.Z)}double(){const{a:b,b:v}=s,y=r.mul(v,ya),{X:w,Y:I,Z:O}=this;let S=r.ZERO,A=r.ZERO,R=r.ZERO,L=r.mul(w,w),F=r.mul(I,I),k=r.mul(O,O),N=r.mul(w,I);return N=r.add(N,N),R=r.mul(w,O),R=r.add(R,R),S=r.mul(b,R),A=r.mul(y,k),A=r.add(S,A),S=r.sub(F,A),A=r.add(F,A),A=r.mul(S,A),S=r.mul(N,S),R=r.mul(y,R),k=r.mul(b,k),N=r.sub(L,k),N=r.mul(b,N),N=r.add(N,R),R=r.add(L,L),L=r.add(R,L),L=r.add(L,k),L=r.mul(L,N),A=r.add(A,L),k=r.mul(I,O),k=r.add(k,k),L=r.mul(k,N),S=r.sub(S,L),R=r.mul(k,F),R=r.add(R,R),R=r.add(R,R),new D(S,A,R)}add(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b;let A=r.ZERO,R=r.ZERO,L=r.ZERO;const F=s.a,k=r.mul(s.b,ya);let N=r.mul(v,I),q=r.mul(y,O),z=r.mul(w,S),W=r.add(v,y),K=r.add(I,O);W=r.mul(W,K),K=r.add(N,q),W=r.sub(W,K),K=r.add(v,w);let Z=r.add(I,S);return K=r.mul(K,Z),Z=r.add(N,z),K=r.sub(K,Z),Z=r.add(y,w),A=r.add(O,S),Z=r.mul(Z,A),A=r.add(q,z),Z=r.sub(Z,A),L=r.mul(F,K),A=r.mul(k,z),L=r.add(A,L),A=r.sub(q,L),L=r.add(q,L),R=r.mul(A,L),q=r.add(N,N),q=r.add(q,N),z=r.mul(F,z),K=r.mul(k,K),q=r.add(q,z),z=r.sub(N,z),z=r.mul(F,z),K=r.add(K,z),N=r.mul(q,K),R=r.add(R,N),N=r.mul(Z,K),A=r.mul(W,A),A=r.sub(A,N),N=r.mul(W,q),L=r.mul(Z,L),L=r.add(L,N),new D(A,R,L)}subtract(b){return this.add(b.negate())}is0(){return this.equals(D.ZERO)}multiply(b){const{endo:v}=e;if(!i.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,w;const I=O=>M.cached(this,O,S=>sl(D,S));if(v){const{k1neg:O,k1:S,k2neg:A,k2:R}=T(b),{p:L,f:F}=I(S),{p:k,f:N}=I(R);w=F.add(N),y=U(v.beta,L,k,O,A)}else{const{p:O,f:S}=I(b);y=O,w=S}return sl(D,[y,w])[0]}multiplyUnsafe(b){const{endo:v}=e,y=this;if(!i.isValid(b))throw new Error("invalid scalar: out of range");if(b===Fn||y.is0())return D.ZERO;if(b===Ai)return y;if(M.hasCache(this))return this.multiply(b);if(v){const{k1neg:w,k1:I,k2neg:O,k2:S}=T(b),{p1:A,p2:R}=ZI(D,y,I,S);return U(v.beta,A,R,w,O)}else return M.unsafe(y,b)}multiplyAndAddUnsafe(b,v,y){const w=this.multiplyUnsafe(v).add(b.multiplyUnsafe(y));return w.is0()?void 0:w}toAffine(b){return P(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return o===Ai?!0:b?b(D,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return o===Ai?this:b?b(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(b=!0){return ua(b,"isCompressed"),this.assertValidity(),h(D,this,b)}toHex(b=!0){return Ii(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return sl(D,b)}static msm(b,v){return YI(D,i,b,v)}static fromPrivateKey(b){return D.BASE.multiply(Di(i,b))}}D.BASE=new D(s.Gx,s.Gy,r.ONE),D.ZERO=new D(r.ZERO,r.ONE,r.ZERO),D.Fp=r,D.Fn=i;const j=i.BITS,M=new WI(D,e.endo?Math.ceil(j/2):j);return D.BASE.precompute(8),D}function e1(t){return Uint8Array.of(t?2:3)}function t1(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function hS(t,e={}){const{Fn:n}=t,r=e.randomBytes||zr,i=Object.assign(t1(t.Fp,n),{seed:Vg(n.ORDER)});function s(d){try{return!!Di(n,d)}catch{return!1}}function o(d,h){const{publicKey:p,publicKeyUncompressed:g}=i;try{const m=d.length;return h===!0&&m!==p||h===!1&&m!==g?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=r(i.seed)){return KI(Kr(d,i.seed,"seed"),n.ORDER)}function c(d,h=!0){return t.BASE.multiply(Di(n,d)).toBytes(h)}function u(d){const h=a(d);return{secretKey:h,publicKey:c(h)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:h,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||h===p)return;const m=tt("key",d).length;return m===p||m===g}function f(d,h,p=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");const g=Di(n,d);return t.fromHex(h).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:d=>Di(n,d),precompute(d=8,h=t.BASE){return h.precompute(d,!1)}},lengths:i})}function dS(t,e,n={}){Qo(e),da(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||zr,i=n.hmac||((v,...y)=>aa(e,v,dr(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=hS(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function m(v){const y=a>>Ai;return v>y}function B(v,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return y}function $(v,y){ll(y);const w=h.signature,I=y==="compact"?w:y==="recovered"?w+1:void 0;return Kr(v,I,`${y} signature`)}class x{constructor(y,w,I){this.r=B("r",y),this.s=B("s",w),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(y,w=g){$(y,w);let I;if(w==="der"){const{r:R,s:L}=Un.toSig(Kr(y));return new x(R,L)}w==="recovered"&&(I=y[0],w="compact",y=y.subarray(1));const O=o.BYTES,S=y.subarray(0,O),A=y.subarray(O,O*2);return new x(o.fromBytes(S),o.fromBytes(A),I)}static fromHex(y,w){return this.fromBytes(ea(y),w)}addRecoveryBit(y){return new x(this.r,this.s,y)}recoverPublicKey(y){const w=s.ORDER,{r:I,s:O,recovery:S}=this;if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");if(a*Qg<w&&S>1)throw new Error("recovery id is ambiguous for h>1 curve");const A=S===2||S===3?I+a:I;if(!s.isValid(A))throw new Error("recovery id 2 or 3 invalid");const R=s.toBytes(A),L=t.fromBytes(dr(e1((S&1)===0),R)),F=o.inv(A),k=T(tt("msgHash",y)),N=o.create(-k*F),q=o.create(O*F),z=t.BASE.multiplyUnsafe(N).add(L.multiplyUnsafe(q));if(z.is0())throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return m(this.s)}toBytes(y=g){if(ll(y),y==="der")return ea(Un.hexFromSig(this));const w=o.toBytes(this.r),I=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return dr(Uint8Array.of(this.recovery),w,I)}return dr(w,I)}toHex(y){return Ii(this.toBytes(y))}assertValidity(){}static fromCompact(y){return x.fromBytes(tt("sig",y),"compact")}static fromDER(y){return x.fromBytes(tt("sig",y),"der")}normalizeS(){return this.hasHighS()?new x(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Ii(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ii(this.toBytes("compact"))}}const _=n.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const y=fa(v),w=v.length*8-c;return w>0?y>>BigInt(w):y},T=n.bits2int_modN||function(v){return o.create(_(v))},P=xs(c);function C(v){return rl("num < 2^"+c,v,Fn,P),o.toBytes(v)}function U(v,y){return Kr(v,void 0,"message"),y?Kr(e(v),void 0,"prehashed message"):v}function D(v,y,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:I,prehash:O,extraEntropy:S}=fl(w,p);v=U(v,O);const A=T(v),R=Di(o,y),L=[C(R),C(A)];if(S!=null&&S!==!1){const q=S===!0?r(h.secretKey):S;L.push(tt("extraEntropy",q))}const F=dr(...L),k=A;function N(q){const z=_(q);if(!o.isValidNot0(z))return;const W=o.inv(z),K=t.BASE.multiply(z).toAffine(),Z=o.create(K.x);if(Z===Fn)return;const Q=o.create(W*o.create(k+Z*R));if(Q===Fn)return;let ee=(K.x===Z?0:2)|Number(K.y&Ai),ie=Q;return I&&m(Q)&&(ie=o.neg(Q),ee^=1),new x(Z,ie,ee)}return{seed:F,k2sig:N}}function j(v,y,w={}){v=tt("message",v);const{seed:I,k2sig:O}=D(v,y,w);return UI(e.outputLen,o.BYTES,i)(I,O)}function M(v){let y;const w=typeof v=="string"||Jo(v),I=!w&&v!==null&&typeof v=="object"&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!w&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)y=new x(v.r,v.s);else if(w){try{y=x.fromBytes(tt("sig",v),"der")}catch(O){if(!(O instanceof Un.Err))throw O}if(!y)try{y=x.fromBytes(tt("sig",v),"compact")}catch{return!1}}return y||!1}function E(v,y,w,I={}){const{lowS:O,prehash:S,format:A}=fl(I,p);if(w=tt("publicKey",w),y=U(tt("message",y),S),"strict"in I)throw new Error("options.strict was renamed to lowS");const R=A===void 0?M(v):x.fromBytes(tt("sig",v),A);if(R===!1)return!1;try{const L=t.fromBytes(w);if(O&&R.hasHighS())return!1;const{r:F,s:k}=R,N=T(y),q=o.inv(k),z=o.create(N*q),W=o.create(F*q),K=t.BASE.multiplyUnsafe(z).add(L.multiplyUnsafe(W));return K.is0()?!1:o.create(K.x)===F}catch{return!1}}function b(v,y,w={}){const{prehash:I}=fl(w,p);return y=U(y,I),x.fromBytes(v,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:j,verify:E,recoverPublicKey:b,Signature:x,hash:e})}function pS(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=Er(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 gS(t){const{CURVE:e,curveOpts:n}=pS(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 yS(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,jg(n.Fn.ORDER,n.Fn.BITS))})}function bS(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=gS(t),s=fS(e,n),o=dS(s,r,i);return yS(t,o)}function hl(t,e){const n=r=>bS(ps(Ei({},t),{hash:r}));return ps(Ei({},n(e)),{create:n})}const n1={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},r1={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},i1={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},wS=Er(n1.p),mS=Er(r1.p),vS=Er(i1.p),ES=hl(ps(Ei({},n1),{Fp:wS,lowS:!1}),na);hl(ps(Ei({},r1),{Fp:mS,lowS:!1}),S5),hl(ps(Ei({},i1),{Fp:vS,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),I5);const xS=ES,s1="base10",lt="base16",xt="base64pad",xr="base64url",Is="utf8",o1=0,Ln=1,Ss=2,_S=0,a1=1,Os=12,dl=32;function IS(){const t=ul.utils.randomPrivateKey(),e=ul.getPublicKey(t);return{privateKey:mt(t,lt),publicKey:mt(e,lt)}}function pl(){const t=zr(dl);return mt(t,lt)}function SS(t,e){const n=ul.getSharedSecret(kt(t,lt),kt(e,lt)),r=NI(ca,n,void 0,void 0,dl);return mt(r,lt)}function ba(t){const e=ca(kt(t,lt));return mt(e,lt)}function Mt(t){const e=ca(kt(t,Is));return mt(e,lt)}function c1(t){return kt(`${t}`,s1)}function Wr(t){return Number(mt(t,s1))}function u1(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function l1(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function OS(t){const e=c1(typeof t.type<"u"?t.type:o1);if(Wr(e)===Ln&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?kt(t.senderPublicKey,lt):void 0,r=typeof t.iv<"u"?kt(t.iv,lt):zr(Os),i=kt(t.symKey,lt),s=Og(i,r).encrypt(kt(t.message,Is)),o=f1({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===xr?u1(o):o}function BS(t){const e=kt(t.symKey,lt),{sealed:n,iv:r}=Bs({encoded:t.encoded,encoding:t.encoding}),i=Og(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return mt(i,Is)}function AS(t,e){const n=c1(Ss),r=zr(Os),i=kt(t,Is),s=f1({type:n,sealed:i,iv:r});return e===xr?u1(s):s}function DS(t,e){const{sealed:n}=Bs({encoded:t,encoding:e});return mt(n,Is)}function f1(t){if(Wr(t.type)===Ss)return mt(us([t.type,t.sealed]),xt);if(Wr(t.type)===Ln){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return mt(us([t.type,t.senderPublicKey,t.iv,t.sealed]),xt)}return mt(us([t.type,t.iv,t.sealed]),xt)}function Bs(t){const e=(t.encoding||xt)===xr?l1(t.encoded):t.encoded,n=kt(e,xt),r=n.slice(_S,a1),i=a1;if(Wr(r)===Ln){const c=i+dl,u=c+Os,l=n.slice(i,c),f=n.slice(c,u),d=n.slice(u);return{type:r,sealed:d,iv:f,senderPublicKey:l}}if(Wr(r)===Ss){const c=n.slice(i),u=zr(Os);return{type:r,sealed:c,iv:u}}const s=i+Os,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function $S(t,e){const n=Bs({encoded:t,encoding:e?.encoding});return h1({type:Wr(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?mt(n.senderPublicKey,lt):void 0,receiverPublicKey:e?.receiverPublicKey})}function h1(t){const e=t?.type||o1;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 d1(t){return t.type===Ln&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function p1(t){return t.type===Ss}function TS(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return us([new Uint8Array([4]),e,n])}function PS(t,e){const[n,r,i]=t.split("."),s=Buffer.from(l1(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=ca(c),l=TS(e);if(!xS.verify(us([o,a]),u,l))throw new Error("Invalid signature");return yc(t).payload}const RS="irn";function wa(t){return t?.relay||{protocol:RS}}function $i(t){const e=t_[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var NS=Object.defineProperty,CS=Object.defineProperties,US=Object.getOwnPropertyDescriptors,g1=Object.getOwnPropertySymbols,FS=Object.prototype.hasOwnProperty,LS=Object.prototype.propertyIsEnumerable,y1=(t,e,n)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gl=(t,e)=>{for(var n in e||(e={}))FS.call(e,n)&&y1(t,n,e[n]);if(g1)for(var n of g1(e))LS.call(e,n)&&y1(t,n,e[n]);return t},kS=(t,e)=>CS(t,US(e));function qS(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 b1(t){if(!t.includes("wc:")){const u=M0(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:MS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:qS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function MS(t){return t.startsWith("//")?t.substring(2):t}function jS(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 w1(t){const e=new URLSearchParams,n=gl(gl(kS(gl({},jS(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 ma(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var zS=Object.defineProperty,VS=Object.defineProperties,KS=Object.getOwnPropertyDescriptors,m1=Object.getOwnPropertySymbols,HS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,v1=(t,e,n)=>e in t?zS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,WS=(t,e)=>{for(var n in e||(e={}))HS.call(e,n)&&v1(t,n,e[n]);if(m1)for(var n of m1(e))GS.call(e,n)&&v1(t,n,e[n]);return t},ZS=(t,e)=>VS(t,KS(e));function Ti(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function E1(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Ti(n.accounts))}),[...new Set(e)]}function YS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.methods)}),[...new Set(e)]}function XS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.events)}),[...new Set(e)]}function JS(t,e){const n=[];return Object.values(t).forEach(r=>{Ti(r.accounts).includes(e)&&n.push(...r.methods)}),n}function QS(t,e){const n=[];return Object.values(t).forEach(r=>{Ti(r.accounts).includes(e)&&n.push(...r.events)}),n}function x1(t){return t.includes(":")}function e9(t){return x1(t)?t.split(":")[0]:t}function _1(t){var e,n,r;const i={};if(!As(t))return i;for(const[s,o]of Object.entries(t)){const a=x1(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=e9(s);i[l]=ZS(WS({},i[l]),{chains:jr(a,(e=i[l])==null?void 0:e.chains),methods:jr(c,(n=i[l])==null?void 0:n.methods),events:jr(u,(r=i[l])==null?void 0:r.events)})}return i}function t9(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 I1(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=t9(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=jr(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function n9(t,e){var n,r,i,s,o,a;const c=_1(t),u=_1(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const d of f)l[d]={chains:jr((n=c[d])==null?void 0:n.chains,(r=u[d])==null?void 0:r.chains),methods:jr((i=c[d])==null?void 0:i.methods,(s=u[d])==null?void 0:s.methods),events:jr((o=c[d])==null?void 0:o.events,(a=u[d])==null?void 0:a.events)};return l}const r9={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}},i9={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 G(t,e){const{message:n,code:r}=i9[t];return{message:e?`${n} ${e}`:n,code:r}}function xe(t,e){const{message:n,code:r}=r9[t];return{message:e?`${n} ${e}`:n,code:r}}function Pi(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function As(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Re(t){return typeof t>"u"}function Oe(t,e){return e&&Re(t)?!0:typeof t=="string"&&!!t.trim().length}function yl(t,e){return e&&Re(t)?!0:typeof t=="number"&&!isNaN(t)}function s9(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return qr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Ti(a),f=n[o];(!qr($0(o,f),l)||!qr(f.methods,c)||!qr(f.events,u))&&(s=!1)}),s):!1}function Ds(t){return Oe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function o9(t){if(Oe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Ds(n)}}return!1}function a9(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(Oe(t,!1)){if(e(t))return!0;const n=M0(t);return e(n)}}catch{}return!1}function c9(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function u9(t){return t?.topic}function l9(t,e){let n=null;return Oe(t?.publicKey,!1)||(n=G("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function S1(t){let e=!0;return Pi(t)?t.length&&(e=t.every(n=>Oe(n,!1))):e=!1,e}function f9(t,e,n){let r=null;return Pi(e)&&e.length?e.forEach(i=>{r||Ds(i)||(r=xe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Ds(t)||(r=xe("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 h9(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=f9(i,$0(i,s),`${e} ${n}`);o&&(r=o)}),r}function d9(t,e){let n=null;return Pi(t)?t.forEach(r=>{n||o9(r)||(n=xe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=xe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function p9(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=d9(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function g9(t,e){let n=null;return S1(t?.methods)?S1(t?.events)||(n=xe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=xe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function O1(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=g9(r,`${e}, namespace`);i&&(n=i)}),n}function y9(t,e,n){let r=null;if(t&&As(t)){const i=O1(t,e);i&&(r=i);const s=h9(t,e,n);s&&(r=s)}else r=G("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function bl(t,e){let n=null;if(t&&As(t)){const r=O1(t,e);r&&(n=r);const i=p9(t,e);i&&(n=i)}else n=G("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function B1(t){return Oe(t.protocol,!0)}function b9(t,e){let n=!1;return e&&!t?n=!0:t&&Pi(t)&&t.length&&t.forEach(r=>{n=B1(r)}),n}function w9(t){return typeof t=="number"}function _t(t){return typeof t<"u"&&typeof t!==null}function m9(t){return!(!t||typeof t!="object"||!t.code||!yl(t.code,!1)||!t.message||!Oe(t.message,!1))}function v9(t){return!(Re(t)||!Oe(t.method,!1))}function E9(t){return!(Re(t)||Re(t.result)&&Re(t.error)||!yl(t.id,!1)||!Oe(t.jsonrpc,!1))}function x9(t){return!(Re(t)||!Oe(t.name,!1))}function A1(t,e){return!(!Ds(e)||!E1(t).includes(e))}function _9(t,e,n){return Oe(n,!1)?JS(t,e).includes(n):!1}function I9(t,e,n){return Oe(n,!1)?QS(t,e).includes(n):!1}function D1(t,e,n){let r=null;const i=S9(t),s=O9(e),o=Object.keys(i),a=Object.keys(s),c=$1(Object.keys(t)),u=$1(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
|
|
18
|
+
`+new Array(t.length+4).join(" "):i<e.length-2&&(r+=" ")}console.log(r)}function o_(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 p0={normalizeInput:r_,toHex:i_,debugPrint:s_,testSpeed:o_};const Go=p0;function Wo(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 g0(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 y0(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function or(t,e,n,r,i,s){const o=ds[i],a=ds[i+1],c=ds[s],u=ds[s+1];Wo(te,t,e),g0(te,t,o,a);let l=te[r]^te[t],f=te[r+1]^te[t+1];te[r]=f,te[r+1]=l,Wo(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=l>>>24^f<<8,te[e+1]=f>>>24^l<<8,Wo(te,t,e),g0(te,t,c,u),l=te[r]^te[t],f=te[r+1]^te[t+1],te[r]=l>>>16^f<<16,te[r+1]=f>>>16^l<<16,Wo(te,n,r),l=te[e]^te[n],f=te[e+1]^te[n+1],te[e]=f>>>31^l<<1,te[e+1]=l>>>31^f<<1}const b0=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),a_=[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],Ye=new Uint8Array(a_.map(function(t){return t*2})),te=new Uint32Array(32),ds=new Uint32Array(32);function w0(t,e){let n=0;for(n=0;n<16;n++)te[n]=t.h[n],te[n+16]=b0[n];for(te[24]=te[24]^t.t,te[25]=te[25]^t.t/4294967296,e&&(te[28]=~te[28],te[29]=~te[29]),n=0;n<32;n++)ds[n]=y0(t.b,4*n);for(n=0;n<12;n++)or(0,8,16,24,Ye[n*16+0],Ye[n*16+1]),or(2,10,18,26,Ye[n*16+2],Ye[n*16+3]),or(4,12,20,28,Ye[n*16+4],Ye[n*16+5]),or(6,14,22,30,Ye[n*16+6],Ye[n*16+7]),or(0,10,20,30,Ye[n*16+8],Ye[n*16+9]),or(2,12,22,24,Ye[n*16+10],Ye[n*16+11]),or(4,14,16,26,Ye[n*16+12],Ye[n*16+13]),or(6,8,18,28,Ye[n*16+14],Ye[n*16+15]);for(n=0;n<16;n++)t.h[n]=t.h[n]^te[n]^te[n+16]}const ar=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 m0(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};ar.fill(0),ar[0]=t,e&&(ar[1]=e.length),ar[2]=1,ar[3]=1,n&&ar.set(n,32),r&&ar.set(r,48);for(let s=0;s<16;s++)i.h[s]=b0[s]^y0(ar,s*4);return e&&(Pu(i,e),i.c=128),i}function Pu(t,e){for(let n=0;n<e.length;n++)t.c===128&&(t.t+=t.c,w0(t,!1),t.c=0),t.b[t.c++]=e[n]}function v0(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;w0(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 E0(t,e,n,r,i){n=n||64,t=Go.normalizeInput(t),r&&(r=Go.normalizeInput(r)),i&&(i=Go.normalizeInput(i));const s=m0(n,e,r,i);return Pu(s,t),v0(s)}function c_(t,e,n,r,i){const s=E0(t,e,n,r,i);return Go.toHex(s)}var u_={blake2b:E0,blake2bHex:c_,blake2bInit:m0,blake2bUpdate:Pu,blake2bFinal:v0};const x0=p0;function l_(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function cr(t,e,n,r,i,s){ae[t]=ae[t]+ae[e]+i,ae[r]=Zo(ae[r]^ae[t],16),ae[n]=ae[n]+ae[r],ae[e]=Zo(ae[e]^ae[n],12),ae[t]=ae[t]+ae[e]+s,ae[r]=Zo(ae[r]^ae[t],8),ae[n]=ae[n]+ae[r],ae[e]=Zo(ae[e]^ae[n],7)}function Zo(t,e){return t>>>e^t<<32-e}const _0=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Xe=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]),ae=new Uint32Array(16),Me=new Uint32Array(16);function I0(t,e){let n=0;for(n=0;n<8;n++)ae[n]=t.h[n],ae[n+8]=_0[n];for(ae[12]^=t.t,ae[13]^=t.t/4294967296,e&&(ae[14]=~ae[14]),n=0;n<16;n++)Me[n]=l_(t.b,4*n);for(n=0;n<10;n++)cr(0,4,8,12,Me[Xe[n*16+0]],Me[Xe[n*16+1]]),cr(1,5,9,13,Me[Xe[n*16+2]],Me[Xe[n*16+3]]),cr(2,6,10,14,Me[Xe[n*16+4]],Me[Xe[n*16+5]]),cr(3,7,11,15,Me[Xe[n*16+6]],Me[Xe[n*16+7]]),cr(0,5,10,15,Me[Xe[n*16+8]],Me[Xe[n*16+9]]),cr(1,6,11,12,Me[Xe[n*16+10]],Me[Xe[n*16+11]]),cr(2,7,8,13,Me[Xe[n*16+12]],Me[Xe[n*16+13]]),cr(3,4,9,14,Me[Xe[n*16+14]],Me[Xe[n*16+15]]);for(n=0;n<8;n++)t.h[n]^=ae[n]^ae[n+8]}function S0(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(_0),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^n<<8^t,n>0&&(Ru(r,e),r.c=64),r}function Ru(t,e){for(let n=0;n<e.length;n++)t.c===64&&(t.t+=t.c,I0(t,!1),t.c=0),t.b[t.c++]=e[n]}function O0(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;I0(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 B0(t,e,n){n=n||32,t=x0.normalizeInput(t);const r=S0(n,e);return Ru(r,t),O0(r)}function f_(t,e,n){const r=B0(t,e,n);return x0.toHex(r)}var h_={blake2s:B0,blake2sHex:f_,blake2sInit:S0,blake2sUpdate:Ru,blake2sFinal:O0};const ps=u_,gs=h_;var d_={blake2b:ps.blake2b,blake2bHex:ps.blake2bHex,blake2bInit:ps.blake2bInit,blake2bUpdate:ps.blake2bUpdate,blake2bFinal:ps.blake2bFinal,blake2s:gs.blake2s,blake2sHex:gs.blake2sHex,blake2sInit:gs.blake2sInit,blake2sUpdate:gs.blake2sUpdate,blake2sFinal:gs.blake2sFinal},p_=Object.defineProperty,g_=Object.defineProperties,y_=Object.getOwnPropertyDescriptors,A0=Object.getOwnPropertySymbols,b_=Object.prototype.hasOwnProperty,w_=Object.prototype.propertyIsEnumerable,D0=(t,e,n)=>e in t?p_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,_i=(t,e)=>{for(var n in e||(e={}))b_.call(e,n)&&D0(t,n,e[n]);if(A0)for(var n of A0(e))w_.call(e,n)&&D0(t,n,e[n]);return t},ys=(t,e)=>g_(t,y_(e));const m_=":";function Pn(t){const[e,n]=t.split(m_);return{namespace:e,reference:n}}function $0(t,e){return t.includes(":")?[t]:e.chains||[]}var v_=Object.defineProperty,E_=Object.defineProperties,x_=Object.getOwnPropertyDescriptors,T0=Object.getOwnPropertySymbols,__=Object.prototype.hasOwnProperty,I_=Object.prototype.propertyIsEnumerable,Nu=(t,e,n)=>e in t?v_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,P0=(t,e)=>{for(var n in e||(e={}))__.call(e,n)&&Nu(t,n,e[n]);if(T0)for(var n of T0(e))I_.call(e,n)&&Nu(t,n,e[n]);return t},S_=(t,e)=>E_(t,x_(e)),R0=(t,e,n)=>Nu(t,typeof e!="symbol"?e+"":e,n);const O_="ReactNative",$t={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},B_="js";function Yo(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}function ur(){return!Nr()&&!!bc()&&navigator.product===O_}function A_(){return ur()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="android"}function D_(){return ur()&&typeof global<"u"&&typeof(global==null?void 0:global.Platform)<"u"&&(global==null?void 0:global.Platform.OS)==="ios"}function Ii(){return!Yo()&&!!bc()&&!!Nr()}function bs(){return ur()?$t.reactNative:Yo()?$t.node:Ii()?$t.browser:$t.unknown}function N0(){var t;try{return ur()&&typeof global<"u"&&typeof(global==null?void 0:global.Application)<"u"?(t=global.Application)==null?void 0:t.applicationId:void 0}catch{return}}function $_(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 T_(t){var e,n;const r=C0();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!=="")),S_(P0(P0({},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 C0(){return Lh()||{name:"",description:"",url:"",icons:[""]}}function P_(){if(bs()===$t.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=EE();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 R_(){var t;const e=bs();return e===$t.browser?[e,((t=kh())==null?void 0:t.host)||"unknown"].join(":"):e}function U0(t,e,n){const r=P_(),i=R_();return[[t,e].join("-"),[B_,n].join("-"),r,i].join("/")}function N_({protocol:t,version:e,relayUrl:n,sdkVersion:r,auth:i,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=n.split("?"),l=U0(t,e,r),f={auth:i,ua:l,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},d=$_(u[1]||"",f);return u[0]+"?"+d}function jr(t,e){return t.filter(n=>e.includes(n)).length===t.length}function Cu(t){return Object.fromEntries(t.entries())}function Uu(t){return new Map(Object.entries(t))}function zr(t=H.FIVE_MINUTES,e){const n=H.toMiliseconds(t||H.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 cn(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 F0(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 C_(t){return F0("topic",t)}function U_(t){return F0("id",t)}function k0(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 Te(t,e){return H.fromMiliseconds((e||Date.now())+H.toMiliseconds(t))}function lr(t){return Date.now()>=H.toMiliseconds(t)}function de(t,e){return`${t}${e?`:${e}`:""}`}function Vr(t=[],e=[]){return[...new Set([...t,...e])]}async function F_({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=k_(s,t,e),a=bs();if(a===$t.browser){if(!((r=Nr())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}L_(o)}else a===$t.reactNative&&typeof(global==null?void 0:global.Linking)<"u"&&await global.Linking.openURL(o)}catch(i){console.error(i)}}function k_(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}${z_(r,!0)}`}else i=`${i}/wc?${r}`;return i}function L_(t){let e="_self";j_()?e="_top":(M_()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function q_(t,e){let n="";try{if(Ii()&&(n=localStorage.getItem(e),n))return n;n=await t.getItem(e)}catch(r){console.error(r)}return n}function L0(t,e){if(!t.includes(e))return null;const n=t.split(/([&,?,=])/),r=n.indexOf(e);return n[r+2]}function q0(){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 Fu(){return typeof process<"u"&&process.env.IS_VITEST==="true"}function M_(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function j_(){try{return window.self!==window.top}catch{return!1}}function z_(t,e=!1){const n=Buffer.from(t).toString("base64");return e?n.replace(/[=]/g,""):n}function M0(t){return Buffer.from(t,"base64").toString("utf-8")}function V_(t){return new Promise(e=>setTimeout(e,t))}class K_{constructor({limit:e}){R0(this,"limit"),R0(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 Xo=BigInt(2**32-1),j0=BigInt(32);function z0(t,e=!1){return e?{h:Number(t&Xo),l:Number(t>>j0&Xo)}:{h:Number(t>>j0&Xo)|0,l:Number(t&Xo)|0}}function V0(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}=z0(t[s],e);[r[s],i[s]]=[o,a]}return[r,i]}const K0=(t,e,n)=>t>>>n,H0=(t,e,n)=>t<<32-n|e>>>n,fr=(t,e,n)=>t>>>n|e<<32-n,hr=(t,e,n)=>t<<32-n|e>>>n,ws=(t,e,n)=>t<<64-n|e>>>n-32,ms=(t,e,n)=>t>>>n-32|e<<64-n,H_=(t,e)=>e,G_=(t,e)=>t,W_=(t,e,n)=>t<<n|e>>>32-n,Z_=(t,e,n)=>e<<n|t>>>32-n,Y_=(t,e,n)=>e<<n-32|t>>>64-n,X_=(t,e,n)=>t<<n-32|e>>>64-n;function Yt(t,e,n,r){const i=(e>>>0)+(r>>>0);return{h:t+n+(i/2**32|0)|0,l:i|0}}const ku=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Lu=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,J_=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Q_=(t,e,n,r,i)=>e+n+r+i+(t/2**32|0)|0,e5=(t,e,n,r,i)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(i>>>0),t5=(t,e,n,r,i,s)=>e+n+r+i+s+(t/2**32|0)|0,Si=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Jo(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 Xt(t,...e){if(!Jo(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 Qo(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 dr(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 qu(t,e){Xt(t);const n=e.outputLen;if(t.length<n)throw new Error("digestInto() expects output buffer of length at least "+n)}function vs(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function qt(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Mu(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function un(t,e){return t<<32-e|t>>>e}const G0=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function W0(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Nn=G0?t=>t:t=>W0(t);function n5(t){for(let e=0;e<t.length;e++)t[e]=W0(t[e]);return t}const pr=G0?t=>t:n5,Z0=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",r5=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Oi(t){if(Xt(t),Z0)return t.toHex();let e="";for(let n=0;n<t.length;n++)e+=r5[t[n]];return e}const Cn={_0:48,_9:57,A:65,F:70,a:97,f:102};function Y0(t){if(t>=Cn._0&&t<=Cn._9)return t-Cn._0;if(t>=Cn.A&&t<=Cn.F)return t-(Cn.A-10);if(t>=Cn.a&&t<=Cn.f)return t-(Cn.a-10)}function ea(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Z0)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=Y0(t.charCodeAt(s)),a=Y0(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 X0(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Jt(t){return typeof t=="string"&&(t=X0(t)),Xt(t),t}function gr(...t){let e=0;for(let r=0;r<t.length;r++){const i=t[r];Xt(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 ta{}function Es(t){const e=r=>t().update(Jt(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function i5(t){const e=(r,i)=>t(i).update(Jt(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Kr(t=32){if(Si&&typeof Si.getRandomValues=="function")return Si.getRandomValues(new Uint8Array(t));if(Si&&typeof Si.randomBytes=="function")return Uint8Array.from(Si.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const s5=BigInt(0),xs=BigInt(1),o5=BigInt(2),a5=BigInt(7),c5=BigInt(256),u5=BigInt(113),J0=[],Q0=[],eg=[];for(let t=0,e=xs,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],J0.push(2*(5*r+n)),Q0.push((t+1)*(t+2)/2%64);let i=s5;for(let s=0;s<7;s++)e=(e<<xs^(e>>a5)*u5)%c5,e&o5&&(i^=xs<<(xs<<BigInt(s))-xs);eg.push(i)}const tg=V0(eg,!0),l5=tg[0],f5=tg[1],ng=(t,e,n)=>n>32?Y_(t,e,n):W_(t,e,n),rg=(t,e,n)=>n>32?X_(t,e,n):Z_(t,e,n);function h5(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=ng(u,l,1)^n[a],d=rg(u,l,1)^n[a+1];for(let h=0;h<50;h+=10)t[o+h]^=f,t[o+h+1]^=d}let i=t[2],s=t[3];for(let o=0;o<24;o++){const a=Q0[o],c=ng(i,s,a),u=rg(i,s,a),l=J0[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]^=l5[r],t[1]^=f5[r]}qt(n)}class ju extends ta{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=vs(this.state)}clone(){return this._cloneInto()}keccak(){pr(this.state32),h5(this.state32,this.rounds),pr(this.state32),this.posOut=0,this.pos=0}update(e){dr(this),e=Jt(e),Xt(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){dr(this,!1),Xt(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(qu(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,qt(this.state)}_cloneInto(e){const{blockLen:n,suffix:r,outputLen:i,rounds:s,enableXOF:o}=this;return e||(e=new ju(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 d5=(t,e,n)=>Es(()=>new ju(e,t,n)),p5=d5(1,136,256/8);function g5(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 y5(t,e,n){return t&e^~t&n}function b5(t,e,n){return t&e^t&n^e&n}class ig extends ta{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=Mu(this.buffer)}update(e){dr(this),e=Jt(e),Xt(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=Mu(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){dr(this),qu(e,this),this.finished=!0;const{buffer:n,view:r,blockLen:i,isLE:s}=this;let{pos:o}=this;n[o++]=128,qt(this.buffer.subarray(o)),this.padOffset>i-o&&(this.process(r,0),o=0);for(let f=o;f<i;f++)n[f]=0;g5(r,i-8,BigInt(this.length*8),s),this.process(r,0);const a=Mu(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 yr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Je=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Qe=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),w5=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]),br=new Uint32Array(64);class m5 extends ig{constructor(e=32){super(64,e,8,!1),this.A=yr[0]|0,this.B=yr[1]|0,this.C=yr[2]|0,this.D=yr[3]|0,this.E=yr[4]|0,this.F=yr[5]|0,this.G=yr[6]|0,this.H=yr[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)br[f]=e.getUint32(n,!1);for(let f=16;f<64;f++){const d=br[f-15],h=br[f-2],p=un(d,7)^un(d,18)^d>>>3,g=un(h,17)^un(h,19)^h>>>10;br[f]=g+br[f-7]+p+br[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 d=un(a,6)^un(a,11)^un(a,25),h=l+d+y5(a,c,u)+w5[f]+br[f]|0,p=(un(r,2)^un(r,13)^un(r,22))+b5(r,i,s)|0;l=u,u=c,c=a,a=o+h|0,o=s,s=i,i=r,r=h+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(){qt(br)}destroy(){this.set(0,0,0,0,0,0,0,0),qt(this.buffer)}}const sg=V0(["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))),v5=sg[0],E5=sg[1],wr=new Uint32Array(80),mr=new Uint32Array(80);class zu extends ig{constructor(e=64){super(128,e,16,!1),this.Ah=Qe[0]|0,this.Al=Qe[1]|0,this.Bh=Qe[2]|0,this.Bl=Qe[3]|0,this.Ch=Qe[4]|0,this.Cl=Qe[5]|0,this.Dh=Qe[6]|0,this.Dl=Qe[7]|0,this.Eh=Qe[8]|0,this.El=Qe[9]|0,this.Fh=Qe[10]|0,this.Fl=Qe[11]|0,this.Gh=Qe[12]|0,this.Gl=Qe[13]|0,this.Hh=Qe[14]|0,this.Hl=Qe[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:d,Gh:h,Gl:p,Hh:g,Hl:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.Gh=h|0,this.Gl=p|0,this.Hh=g|0,this.Hl=m|0}process(e,n){for(let x=0;x<16;x++,n+=4)wr[x]=e.getUint32(n),mr[x]=e.getUint32(n+=4);for(let x=16;x<80;x++){const _=wr[x-15]|0,T=mr[x-15]|0,P=fr(_,T,1)^fr(_,T,8)^K0(_,T,7),C=hr(_,T,1)^hr(_,T,8)^H0(_,T,7),U=wr[x-2]|0,D=mr[x-2]|0,j=fr(U,D,19)^ws(U,D,61)^K0(U,D,6),M=hr(U,D,19)^ms(U,D,61)^H0(U,D,6),E=J_(C,M,mr[x-7],mr[x-16]),b=Q_(E,P,j,wr[x-7],wr[x-16]);wr[x]=b|0,mr[x]=E|0}let{Ah:r,Al:i,Bh:s,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:f,El:d,Fh:h,Fl:p,Gh:g,Gl:m,Hh:B,Hl:$}=this;for(let x=0;x<80;x++){const _=fr(f,d,14)^fr(f,d,18)^ws(f,d,41),T=hr(f,d,14)^hr(f,d,18)^ms(f,d,41),P=f&h^~f&g,C=d&p^~d&m,U=e5($,T,C,E5[x],mr[x]),D=t5(U,B,_,P,v5[x],wr[x]),j=U|0,M=fr(r,i,28)^ws(r,i,34)^ws(r,i,39),E=hr(r,i,28)^ms(r,i,34)^ms(r,i,39),b=r&s^r&a^s&a,v=i&o^i&c^o&c;B=g|0,$=m|0,g=h|0,m=p|0,h=f|0,p=d|0,{h:f,l:d}=Yt(u|0,l|0,D|0,j|0),u=a|0,l=c|0,a=s|0,c=o|0,s=r|0,o=i|0;const y=ku(j,E,v);r=Lu(y,D,M,b),i=y|0}({h:r,l:i}=Yt(this.Ah|0,this.Al|0,r|0,i|0)),{h:s,l:o}=Yt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Yt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Yt(this.Dh|0,this.Dl|0,u|0,l|0),{h:f,l:d}=Yt(this.Eh|0,this.El|0,f|0,d|0),{h,l:p}=Yt(this.Fh|0,this.Fl|0,h|0,p|0),{h:g,l:m}=Yt(this.Gh|0,this.Gl|0,g|0,m|0),{h:B,l:$}=Yt(this.Hh|0,this.Hl|0,B|0,$|0),this.set(r,i,s,o,a,c,u,l,f,d,h,p,g,m,B,$)}roundClean(){qt(wr,mr)}destroy(){qt(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}class x5 extends zu{constructor(){super(48),this.Ah=Je[0]|0,this.Al=Je[1]|0,this.Bh=Je[2]|0,this.Bl=Je[3]|0,this.Ch=Je[4]|0,this.Cl=Je[5]|0,this.Dh=Je[6]|0,this.Dl=Je[7]|0,this.Eh=Je[8]|0,this.El=Je[9]|0,this.Fh=Je[10]|0,this.Fl=Je[11]|0,this.Gh=Je[12]|0,this.Gl=Je[13]|0,this.Hh=Je[14]|0,this.Hl=Je[15]|0}}const et=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class _5 extends zu{constructor(){super(32),this.Ah=et[0]|0,this.Al=et[1]|0,this.Bh=et[2]|0,this.Bl=et[3]|0,this.Ch=et[4]|0,this.Cl=et[5]|0,this.Dh=et[6]|0,this.Dl=et[7]|0,this.Eh=et[8]|0,this.El=et[9]|0,this.Fh=et[10]|0,this.Fl=et[11]|0,this.Gh=et[12]|0,this.Gl=et[13]|0,this.Hh=et[14]|0,this.Hl=et[15]|0}}const na=Es(()=>new m5),I5=Es(()=>new zu),S5=Es(()=>new x5),O5=Es(()=>new _5),B5=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]),Pe=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),Y=new Uint32Array(32);function vr(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],g=Y[2*r+1],m=ku(c,l,o);u=Lu(m,u,f,a),c=m|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:H_(g,p),Dl:G_(g)},{h,l:d}=Yt(h,d,g,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:fr(f,l,24),Bl:hr(f,l,24)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=g}function Er(t,e,n,r,i,s){const o=i[s],a=i[s+1];let c=Y[2*t],u=Y[2*t+1],l=Y[2*e],f=Y[2*e+1],d=Y[2*n],h=Y[2*n+1],p=Y[2*r],g=Y[2*r+1],m=ku(c,l,o);u=Lu(m,u,f,a),c=m|0,{Dh:g,Dl:p}={Dh:g^u,Dl:p^c},{Dh:g,Dl:p}={Dh:fr(g,p,16),Dl:hr(g,p,16)},{h,l:d}=Yt(h,d,g,p),{Bh:f,Bl:l}={Bh:f^h,Bl:l^d},{Bh:f,Bl:l}={Bh:ws(f,l,63),Bl:ms(f,l,63)},Y[2*t]=c,Y[2*t+1]=u,Y[2*e]=l,Y[2*e+1]=f,Y[2*n]=d,Y[2*n+1]=h,Y[2*r]=p,Y[2*r+1]=g}function A5(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 D5 extends ta{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=vs(this.buffer)}update(e){dr(this),e=Jt(e),Xt(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&&(pr(i),this.compress(i,0,!1),pr(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));pr(f);for(let d=0;c+n<s;d+=i.length,c+=n)this.length+=n,this.compress(f,d,!1);pr(f);continue}r.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){dr(this),qu(e,this);const{pos:n,buffer32:r}=this;this.finished=!0,qt(this.buffer.subarray(n)),pr(r),this.compress(r,0,!0),pr(r);const i=vs(e);this.get().forEach((s,o)=>i[o]=Nn(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 $5 extends D5{constructor(e={}){const n=e.dkLen===void 0?64:e.dkLen;super(128,n),this.v0l=Pe[0]|0,this.v0h=Pe[1]|0,this.v1l=Pe[2]|0,this.v1h=Pe[3]|0,this.v2l=Pe[4]|0,this.v2h=Pe[5]|0,this.v3l=Pe[6]|0,this.v3h=Pe[7]|0,this.v4l=Pe[8]|0,this.v4h=Pe[9]|0,this.v5l=Pe[10]|0,this.v5h=Pe[11]|0,this.v6l=Pe[12]|0,this.v6h=Pe[13]|0,this.v7l=Pe[14]|0,this.v7h=Pe[15]|0,A5(n,e,64,16,16);let{key:r,personalization:i,salt:s}=e,o=0;if(r!==void 0&&(r=Jt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Jt(s);const a=vs(s);this.v4l^=Nn(a[0]),this.v4h^=Nn(a[1]),this.v5l^=Nn(a[2]),this.v5h^=Nn(a[3])}if(i!==void 0){i=Jt(i);const a=vs(i);this.v6l^=Nn(a[0]),this.v6h^=Nn(a[1]),this.v7l^=Nn(a[2]),this.v7h^=Nn(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:d,v6l:h,v6h:p,v7l:g,v7h:m}=this;return[e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m]}set(e,n,r,i,s,o,a,c,u,l,f,d,h,p,g,m){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=d|0,this.v6l=h|0,this.v6h=p|0,this.v7l=g|0,this.v7h=m|0}compress(e,n,r){this.get().forEach((c,u)=>Y[u]=c),Y.set(Pe,16);let{h:i,l:s}=z0(BigInt(this.length));Y[24]=Pe[8]^s,Y[25]=Pe[9]^i,r&&(Y[28]=~Y[28],Y[29]=~Y[29]);let o=0;const a=B5;for(let c=0;c<12;c++)vr(0,4,8,12,e,n+2*a[o++]),Er(0,4,8,12,e,n+2*a[o++]),vr(1,5,9,13,e,n+2*a[o++]),Er(1,5,9,13,e,n+2*a[o++]),vr(2,6,10,14,e,n+2*a[o++]),Er(2,6,10,14,e,n+2*a[o++]),vr(3,7,11,15,e,n+2*a[o++]),Er(3,7,11,15,e,n+2*a[o++]),vr(0,5,10,15,e,n+2*a[o++]),Er(0,5,10,15,e,n+2*a[o++]),vr(1,6,11,12,e,n+2*a[o++]),Er(1,6,11,12,e,n+2*a[o++]),vr(2,7,8,13,e,n+2*a[o++]),Er(2,7,8,13,e,n+2*a[o++]),vr(3,4,9,14,e,n+2*a[o++]),Er(3,4,9,14,e,n+2*a[o++]);this.v0l^=Y[0]^Y[16],this.v0h^=Y[1]^Y[17],this.v1l^=Y[2]^Y[18],this.v1h^=Y[3]^Y[19],this.v2l^=Y[4]^Y[20],this.v2h^=Y[5]^Y[21],this.v3l^=Y[6]^Y[22],this.v3h^=Y[7]^Y[23],this.v4l^=Y[8]^Y[24],this.v4h^=Y[9]^Y[25],this.v5l^=Y[10]^Y[26],this.v5h^=Y[11]^Y[27],this.v6l^=Y[12]^Y[28],this.v6h^=Y[13]^Y[29],this.v7l^=Y[14]^Y[30],this.v7h^=Y[15]^Y[31],qt(Y)}destroy(){this.destroyed=!0,qt(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const T5=i5(t=>new $5(t)),P5="https://rpc.walletconnect.org/v1";function og(t){const e=`Ethereum Signed Message:
|
|
19
|
+
${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(p5(n)).toString("hex")}async function R5(t,e,n,r,i,s){switch(n.t){case"eip191":return await N5(t,e,n.s);case"eip1271":return await C5(t,e,n.s,r,i,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${n.t}`)}}function N5(t,e,n){const r=F8(n);return kx({payload:og(e),signature:r}).toLowerCase()===t.toLowerCase()}async function C5(t,e,n,r,i,s){const o=Pn(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=n.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),f=(e.startsWith("0x")?e:og(e)).substring(2),d=a+f+c+l+u,h=await fetch(`${s||P5}/?chainId=${r}&projectId=${i}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:U5(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:d},"latest"]})}),{result:p}=await h.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function U5(){return Date.now()+Math.floor(Math.random()*1e3)}function F5(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 as.encode(s)}function k5(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=T5(r,{dkLen:32});return as.encode(i)}function ag(t){const e=new Uint8Array(na(L5(t)));return as.encode(e)}function L5(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 cg(t){const e=Buffer.from(t,"base64"),n=C6(e).txn;if(!n)throw new Error("Invalid signed transaction: missing 'txn' field");const r=B6(n),i=Buffer.from("TX"),s=Buffer.concat([i,Buffer.from(r)]),o=O5(s);return Rx.encode(o).replace(/=+$/,"")}function Vu(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 q5(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(Vu(e.length)),i.push(e),i.push(Buffer.from([18])),i.push(Vu(n.length)),i.push(n),i.push(Buffer.from([26])),i.push(Vu(r.length)),i.push(r);const s=Buffer.concat(i),o=na(s);return Buffer.from(o).toString("hex").toUpperCase()}function M5(t){var e,n;const r=[];try{if(typeof t=="string")return r.push(t),r;if(typeof t!="object")return r;t!=null&&t.id&&r.push(t.id);const i=(n=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:n.transactionHashes;i&&r.push(...i)}catch(i){console.warn("getWalletSendCallsHashes failed: ",i)}return r}var j5=Object.defineProperty,z5=Object.defineProperties,V5=Object.getOwnPropertyDescriptors,ug=Object.getOwnPropertySymbols,K5=Object.prototype.hasOwnProperty,H5=Object.prototype.propertyIsEnumerable,lg=(t,e,n)=>e in t?j5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,G5=(t,e)=>{for(var n in e||(e={}))K5.call(e,n)&&lg(t,n,e[n]);if(ug)for(var n of ug(e))H5.call(e,n)&&lg(t,n,e[n]);return t},W5=(t,e)=>z5(t,V5(e));const fg="did:pkh:",Z5={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Y5=t=>t?Z5[t]||t:"",ra=t=>t?.split(":"),X5=t=>{const e=t&&ra(t);if(e)return t.includes(fg)?e[3]:e[1]},J5=t=>{const e=t&&ra(t);if(e)return t.includes(fg)?e[2]:e[0]},Ku=t=>{const e=t&&ra(t);if(e)return e[2]+":"+e[3]},ia=t=>{const e=t&&ra(t);if(e)return e.pop()};async function hg(t){const{cacao:e,projectId:n}=t,{s:r,p:i}=e,s=dg(i,i.iss),o=ia(i.iss);return await R5(o,s,r,Ku(i.iss),n)}const dg=(t,e)=>{const n=J5(e);if(!n)throw new Error("Invalid issuer: "+e);const r=`${t.domain} wants you to sign in with your ${Y5(n)} account:`,i=ia(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${X5(e)}`,u=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,f=t.exp?`Expiration Time: ${t.exp}`:void 0,d=t.nbf?`Not Before: ${t.nbf}`:void 0,h=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(m=>`
|
|
20
|
+
- ${m}`).join("")}`:void 0,g=sa(t.resources);if(g){const m=_s(g);s=aI(s,m)}return[r,i,"",s,"",o,a,c,u,l,f,d,h,p].filter(m=>m!=null).join(`
|
|
21
|
+
`)};function Q5(t){return Buffer.from(JSON.stringify(t)).toString("base64")}function eI(t){return JSON.parse(Buffer.from(t,"base64").toString("utf-8"))}function Hr(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 tI(t,e,n,r={}){return n?.sort((i,s)=>i.localeCompare(s)),{att:{[t]:nI(e,n,r)}}}function nI(t,e,n={}){e=e?.sort((i,s)=>i.localeCompare(s));const r=e.map(i=>({[`${t}/${i}`]:[n]}));return Object.assign({},...r)}function pg(t){return Hr(t),`urn:recap:${Q5(t).replace(/=/g,"")}`}function _s(t){const e=eI(t.replace("urn:recap:",""));return Hr(e),e}function rI(t,e,n){const r=tI(t,e,n);return pg(r)}function iI(t){return t&&t.includes("urn:recap:")}function sI(t,e){const n=_s(t),r=_s(e),i=oI(n,r);return pg(i)}function oI(t,e){Hr(t),Hr(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]=W5(G5({},r.att[i]),{[a]:((c=t.att[i])==null?void 0:c[a])||((u=e.att[i])==null?void 0:u[a])})})}),r}function aI(t="",e){Hr(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,d)=>f.action.localeCompare(d.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 gg(t){var e;const n=_s(t);Hr(n);const r=(e=n.att)==null?void 0:e.eip155;return r?Object.keys(r).map(i=>i.split("/")[1]):[]}function yg(t){const e=_s(t);Hr(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 sa(t){if(!t)return;const e=t?.[t.length-1];return iI(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function bg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Hu(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function Gu(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function vt(t,...e){if(!bg(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 wg(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 cI(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 xr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Bi(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function uI(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const lI=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function fI(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Wu(t){if(typeof t=="string")t=fI(t);else if(bg(t))t=Zu(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function hI(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function dI(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 pI=(t,e)=>{function n(r,...i){if(vt(r),!lI)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?vt(u):vt(u,t.nonceLength)}const s=t.tagLength;s&&i[1]!==void 0&&vt(i[1]);const o=e(r,...i),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");vt(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,vt(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(vt(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 mg(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&&!yI(e))throw new Error("invalid output, must be aligned");return e}function vg(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 gI(t,e,n){Hu(n);const r=new Uint8Array(16),i=uI(r);return vg(i,0,BigInt(e),n),vg(i,8,BigInt(t),n),r}function yI(t){return t.byteOffset%4===0}function Zu(t){return Uint8Array.from(t)}const Eg=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),bI=Eg("expand 16-byte k"),wI=Eg("expand 32-byte k"),mI=xr(bI),vI=xr(wI);function ce(t,e){return t<<e|t>>>32-e}function Yu(t){return t.byteOffset%4===0}const oa=64,EI=16,xg=2**32-1,_g=new Uint32Array;function xI(t,e,n,r,i,s,o,a){const c=i.length,u=new Uint8Array(oa),l=xr(u),f=Yu(i)&&Yu(s),d=f?xr(i):_g,h=f?xr(s):_g;for(let p=0;p<c;o++){if(t(e,n,r,l,o,a),o>=xg)throw new Error("arx: counter overflow");const g=Math.min(oa,c-p);if(f&&g===oa){const m=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let B=0,$;B<EI;B++)$=m+B,h[$]=d[$]^l[B];p+=oa;continue}for(let m=0,B;m<g;m++)B=p+m,s[B]=i[B]^u[m];p+=g}}function _I(t,e){const{allowShortKeys:n,extendNonceFn:r,counterLength:i,counterRight:s,rounds:o}=hI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return Gu(i),Gu(o),Hu(s),Hu(n),(a,c,u,l,f=0)=>{vt(a),vt(c),vt(u);const d=u.length;if(l===void 0&&(l=new Uint8Array(d)),vt(l),Gu(f),f<0||f>=xg)throw new Error("arx: counter overflow");if(l.length<d)throw new Error(`arx: output (${l.length}) is shorter than data (${d})`);const h=[];let p=a.length,g,m;if(p===32)h.push(g=Zu(a)),m=vI;else if(p===16&&n)g=new Uint8Array(32),g.set(a),g.set(a,16),m=mI,h.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);Yu(c)||h.push(c=Zu(c));const B=xr(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(m,B,xr(c.subarray(0,16)),B),c=c.subarray(16)}const $=16-i;if($!==c.length)throw new Error(`arx: nonce must be ${$} or 16 bytes`);if($!==12){const _=new Uint8Array(12);_.set(c,s?0:12-c.length),c=_,h.push(c)}const x=xr(c);return xI(t,m,B,x,u,l,f,o),Bi(...h),l}}const je=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class II{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=Wu(e),vt(e,32);const n=je(e,0),r=je(e,2),i=je(e,4),s=je(e,6),o=je(e,8),a=je(e,10),c=je(e,12),u=je(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]=je(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],d=o[5],h=o[6],p=o[7],g=o[8],m=o[9],B=je(e,n+0),$=je(e,n+2),x=je(e,n+4),_=je(e,n+6),T=je(e,n+8),P=je(e,n+10),C=je(e,n+12),U=je(e,n+14);let D=s[0]+(B&8191),j=s[1]+((B>>>13|$<<3)&8191),M=s[2]+(($>>>10|x<<6)&8191),E=s[3]+((x>>>7|_<<9)&8191),b=s[4]+((_>>>4|T<<12)&8191),v=s[5]+(T>>>1&8191),y=s[6]+((T>>>14|P<<2)&8191),w=s[7]+((P>>>11|C<<5)&8191),I=s[8]+((C>>>8|U<<8)&8191),O=s[9]+(U>>>5|i),S=0,A=S+D*a+j*(5*m)+M*(5*g)+E*(5*p)+b*(5*h);S=A>>>13,A&=8191,A+=v*(5*d)+y*(5*f)+w*(5*l)+I*(5*u)+O*(5*c),S+=A>>>13,A&=8191;let R=S+D*c+j*a+M*(5*m)+E*(5*g)+b*(5*p);S=R>>>13,R&=8191,R+=v*(5*h)+y*(5*d)+w*(5*f)+I*(5*l)+O*(5*u),S+=R>>>13,R&=8191;let k=S+D*u+j*c+M*a+E*(5*m)+b*(5*g);S=k>>>13,k&=8191,k+=v*(5*p)+y*(5*h)+w*(5*d)+I*(5*f)+O*(5*l),S+=k>>>13,k&=8191;let F=S+D*l+j*u+M*c+E*a+b*(5*m);S=F>>>13,F&=8191,F+=v*(5*g)+y*(5*p)+w*(5*h)+I*(5*d)+O*(5*f),S+=F>>>13,F&=8191;let L=S+D*f+j*l+M*u+E*c+b*a;S=L>>>13,L&=8191,L+=v*(5*m)+y*(5*g)+w*(5*p)+I*(5*h)+O*(5*d),S+=L>>>13,L&=8191;let N=S+D*d+j*f+M*l+E*u+b*c;S=N>>>13,N&=8191,N+=v*a+y*(5*m)+w*(5*g)+I*(5*p)+O*(5*h),S+=N>>>13,N&=8191;let q=S+D*h+j*d+M*f+E*l+b*u;S=q>>>13,q&=8191,q+=v*c+y*a+w*(5*m)+I*(5*g)+O*(5*p),S+=q>>>13,q&=8191;let z=S+D*p+j*h+M*d+E*f+b*l;S=z>>>13,z&=8191,z+=v*u+y*c+w*a+I*(5*m)+O*(5*g),S+=z>>>13,z&=8191;let W=S+D*g+j*p+M*h+E*d+b*f;S=W>>>13,W&=8191,W+=v*l+y*u+w*c+I*a+O*(5*m),S+=W>>>13,W&=8191;let K=S+D*m+j*g+M*p+E*h+b*d;S=K>>>13,K&=8191,K+=v*f+y*l+w*u+I*c+O*a,S+=K>>>13,K&=8191,S=(S<<2)+S|0,S=S+A|0,A=S&8191,S=S>>>13,R+=S,s[0]=A,s[1]=R,s[2]=k,s[3]=F,s[4]=L,s[5]=N,s[6]=q,s[7]=z,s[8]=W,s[9]=K}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;Bi(r)}update(e){wg(this),e=Wu(e),vt(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(){Bi(this.h,this.r,this.buffer,this.pad)}digestInto(e){wg(this),cI(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 SI(t){const e=(r,i)=>t(i).update(Wu(r)).digest(),n=t(new Uint8Array(32));return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}const OI=SI(t=>new II(t));function BI(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],d=e[2],h=e[3],p=e[4],g=e[5],m=e[6],B=e[7],$=i,x=n[0],_=n[1],T=n[2],P=o,C=a,U=c,D=u,j=l,M=f,E=d,b=h,v=p,y=g,w=m,I=B,O=$,S=x,A=_,R=T;for(let F=0;F<s;F+=2)P=P+j|0,O=ce(O^P,16),v=v+O|0,j=ce(j^v,12),P=P+j|0,O=ce(O^P,8),v=v+O|0,j=ce(j^v,7),C=C+M|0,S=ce(S^C,16),y=y+S|0,M=ce(M^y,12),C=C+M|0,S=ce(S^C,8),y=y+S|0,M=ce(M^y,7),U=U+E|0,A=ce(A^U,16),w=w+A|0,E=ce(E^w,12),U=U+E|0,A=ce(A^U,8),w=w+A|0,E=ce(E^w,7),D=D+b|0,R=ce(R^D,16),I=I+R|0,b=ce(b^I,12),D=D+b|0,R=ce(R^D,8),I=I+R|0,b=ce(b^I,7),P=P+M|0,R=ce(R^P,16),w=w+R|0,M=ce(M^w,12),P=P+M|0,R=ce(R^P,8),w=w+R|0,M=ce(M^w,7),C=C+E|0,O=ce(O^C,16),I=I+O|0,E=ce(E^I,12),C=C+E|0,O=ce(O^C,8),I=I+O|0,E=ce(E^I,7),U=U+b|0,S=ce(S^U,16),v=v+S|0,b=ce(b^v,12),U=U+b|0,S=ce(S^U,8),v=v+S|0,b=ce(b^v,7),D=D+j|0,A=ce(A^D,16),y=y+A|0,j=ce(j^y,12),D=D+j|0,A=ce(A^D,8),y=y+A|0,j=ce(j^y,7);let k=0;r[k++]=o+P|0,r[k++]=a+C|0,r[k++]=c+U|0,r[k++]=u+D|0,r[k++]=l+j|0,r[k++]=f+M|0,r[k++]=d+E|0,r[k++]=h+b|0,r[k++]=p+v|0,r[k++]=g+y|0,r[k++]=m+w|0,r[k++]=B+I|0,r[k++]=$+O|0,r[k++]=x+S|0,r[k++]=_+A|0,r[k++]=T+R|0}const AI=_I(BI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),DI=new Uint8Array(16),Ig=(t,e)=>{t.update(e);const n=e.length%16;n&&t.update(DI.subarray(n))},$I=new Uint8Array(32);function Sg(t,e,n,r,i){const s=t(e,n,$I),o=OI.create(s);i&&Ig(o,i),Ig(o,r);const a=gI(r.length,i?i.length:0,!0);o.update(a);const c=o.digest();return Bi(s,a),c}const TI=t=>(e,n,r)=>({encrypt(i,s){const o=i.length;s=mg(o+16,s,!1),s.set(i);const a=s.subarray(0,-16);t(e,n,a,a,1);const c=Sg(t,e,n,a,r);return s.set(c,o),Bi(c),s},decrypt(i,s){s=mg(i.length-16,s,!1);const o=i.subarray(0,-16),a=i.subarray(-16),c=Sg(t,e,n,o,r);if(!dI(a,c))throw new Error("invalid tag");return s.set(i.subarray(0,-16)),t(e,n,s,s,1),Bi(c),s}}),Og=pI({blockSize:64,nonceLength:12,tagLength:16},TI(AI));class Bg extends ta{constructor(e,n){super(),this.finished=!1,this.destroyed=!1,Qo(e);const r=Jt(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),qt(s)}update(e){return dr(this),this.iHash.update(e),this}digestInto(e){dr(this),Xt(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 aa=(t,e,n)=>new Bg(t,e).update(n).digest();aa.create=(t,e)=>new Bg(t,e);function PI(t,e,n){return Qo(t),n===void 0&&(n=new Uint8Array(t.outputLen)),aa(t,Jt(n),Jt(e))}const Xu=Uint8Array.from([0]),Ag=Uint8Array.of();function RI(t,e,n,r=32){Qo(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=Ag);const o=new Uint8Array(s*i),a=aa.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<s;l++)Xu[0]=l+1,c.update(l===0?Ag:u).update(n).update(Xu).digestInto(u),o.set(u,i*l),a._cloneInto(c);return a.destroy(),c.destroy(),qt(u,Xu),o.slice(0,r)}const NI=(t,e,n,r,i)=>RI(t,PI(t,e,n),r,i),ca=na,Ju=BigInt(0),Qu=BigInt(1);function ua(t,e=""){if(typeof t!="boolean"){const n=e&&`"${e}"`;throw new Error(n+"expected boolean, got type="+typeof t)}return t}function Gr(t,e,n=""){const r=Jo(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 la(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Dg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Ju:BigInt("0x"+t)}function fa(t){return Dg(Oi(t))}function ha(t){return Xt(t),Dg(Oi(Uint8Array.from(t).reverse()))}function el(t,e){return ea(t.toString(16).padStart(e*2,"0"))}function tl(t,e){return el(t,e).reverse()}function tt(t,e,n){let r;if(typeof e=="string")try{r=ea(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Jo(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 nl=t=>typeof t=="bigint"&&Ju<=t;function CI(t,e,n){return nl(t)&&nl(e)&&nl(n)&&e<=t&&t<n}function rl(t,e,n,r){if(!CI(e,n,r))throw new Error("expected valid "+t+": "+n+" <= n < "+r+", got "+e)}function $g(t){let e;for(e=0;t>Ju;t>>=Qu,e+=1);return e}const Is=t=>(Qu<<BigInt(t))-Qu;function UI(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 h=[];for(;d<e;){s=u();const p=s.slice();h.push(p),d+=s.length}return gr(...h)};return(d,h)=>{c(),l(d);let p;for(;!(p=h(f()));)l();return c(),p}}function da(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 Tg(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 Et=BigInt(0),ut=BigInt(1),Wr=BigInt(2),Pg=BigInt(3),Rg=BigInt(4),Ng=BigInt(5),FI=BigInt(7),Cg=BigInt(8),kI=BigInt(9),Ug=BigInt(16);function Tt(t,e){const n=t%e;return n>=Et?n:e+n}function Qt(t,e,n){let r=t;for(;e-- >Et;)r*=r,r%=n;return r}function Fg(t,e){if(t===Et)throw new Error("invert: expected non-zero number");if(e<=Et)throw new Error("invert: expected positive modulus, got "+e);let n=Tt(t,e),r=e,i=Et,s=ut;for(;n!==Et;){const o=r/n,a=r%n,c=i-s*o;r=n,n=a,i=s,s=c}if(r!==ut)throw new Error("invert: does not exist");return Tt(i,e)}function il(t,e,n){if(!t.eql(t.sqr(e),n))throw new Error("Cannot find square root")}function kg(t,e){const n=(t.ORDER+ut)/Rg,r=t.pow(e,n);return il(t,r,e),r}function LI(t,e){const n=(t.ORDER-Ng)/Cg,r=t.mul(e,Wr),i=t.pow(r,n),s=t.mul(e,i),o=t.mul(t.mul(s,Wr),i),a=t.mul(s,t.sub(o,t.ONE));return il(t,a,e),a}function qI(t){const e=_r(t),n=Lg(t),r=n(e,e.neg(e.ONE)),i=n(e,r),s=n(e,e.neg(r)),o=(t+FI)/Ug;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,r);const f=a.mul(u,i),d=a.mul(u,s),h=a.eql(a.sqr(l),c),p=a.eql(a.sqr(f),c);u=a.cmov(u,l,h),l=a.cmov(d,f,p);const g=a.eql(a.sqr(l),c),m=a.cmov(u,l,g);return il(a,m,c),m}}function Lg(t){if(t<Pg)throw new Error("sqrt is not defined for small field");let e=t-ut,n=0;for(;e%Wr===Et;)e/=Wr,n++;let r=Wr;const i=_r(t);for(;Mg(i,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(n===1)return kg;let s=i.pow(r,e);const o=(e+ut)/Wr;return function(a,c){if(a.is0(c))return c;if(Mg(a,c)!==1)throw new Error("Cannot find square root");let u=n,l=a.mul(a.ONE,s),f=a.pow(c,e),d=a.pow(c,o);for(;!a.eql(f,a.ONE);){if(a.is0(f))return a.ZERO;let h=1,p=a.sqr(f);for(;!a.eql(p,a.ONE);)if(h++,p=a.sqr(p),h===u)throw new Error("Cannot find square root");const g=ut<<BigInt(u-h-1),m=a.pow(l,g);u=h,l=a.sqr(m),f=a.mul(f,l),d=a.mul(d,m)}return d}}function MI(t){return t%Rg===Pg?kg:t%Cg===Ng?LI:t%Ug===kI?qI(t):Lg(t)}const jI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function zI(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},n=jI.reduce((r,i)=>(r[i]="function",r),e);return da(t,n),t}function VI(t,e,n){if(n<Et)throw new Error("invalid exponent, negatives unsupported");if(n===Et)return t.ONE;if(n===ut)return e;let r=t.ONE,i=e;for(;n>Et;)n&ut&&(r=t.mul(r,i)),i=t.sqr(i),n>>=ut;return r}function qg(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 Mg(t,e){const n=(t.ORDER-ut)/Wr,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 jg(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 _r(t,e,n=!1,r={}){if(t<=Et)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 d=e;d.BITS&&(i=d.BITS),d.sqrt&&(s=d.sqrt),typeof d.isLE=="boolean"&&(n=d.isLE),typeof d.modFromBytes=="boolean"&&(o=d.modFromBytes),a=d.allowedLengths}else typeof e=="number"&&(i=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:u}=jg(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:Is(c),ZERO:Et,ONE:ut,allowedLengths:a,create:d=>Tt(d,t),isValid:d=>{if(typeof d!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof d);return Et<=d&&d<t},is0:d=>d===Et,isValidNot0:d=>!f.is0(d)&&f.isValid(d),isOdd:d=>(d&ut)===ut,neg:d=>Tt(-d,t),eql:(d,h)=>d===h,sqr:d=>Tt(d*d,t),add:(d,h)=>Tt(d+h,t),sub:(d,h)=>Tt(d-h,t),mul:(d,h)=>Tt(d*h,t),pow:(d,h)=>VI(f,d,h),div:(d,h)=>Tt(d*Fg(h,t),t),sqrN:d=>d*d,addN:(d,h)=>d+h,subN:(d,h)=>d-h,mulN:(d,h)=>d*h,inv:d=>Fg(d,t),sqrt:s||(d=>(l||(l=MI(t)),l(f,d))),toBytes:d=>n?tl(d,u):el(d,u),fromBytes:(d,h=!0)=>{if(a){if(!a.includes(d.length)||d.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+d.length);const g=new Uint8Array(u);g.set(d,n?0:g.length-d.length),d=g}if(d.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+d.length);let p=n?ha(d):fa(d);if(o&&(p=Tt(p,t)),!h&&!f.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:d=>qg(f,d),cmov:(d,h,p)=>p?h:d});return Object.freeze(f)}function zg(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 Vg(t){const e=zg(t);return e+Math.ceil(e/2)}function KI(t,e,n=!1){const r=t.length,i=zg(e),s=Vg(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=n?ha(t):fa(t),a=Tt(o,e-ut)+ut;return n?tl(a,i):el(a,i)}const Ai=BigInt(0),Zr=BigInt(1);function pa(t,e){const n=e.negate();return t?n:e}function sl(t,e){const n=qg(t.Fp,e.map(r=>r.Z));return e.map((r,i)=>t.fromAffine(r.toAffine(n[i])))}function Kg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function ol(t,e){Kg(t,e);const n=Math.ceil(e/t)+1,r=2**(t-1),i=2**t,s=Is(t),o=BigInt(t);return{windows:n,windowSize:r,mask:s,maxNumber:i,shiftBy:o}}function Hg(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+=Zr);const u=e*r,l=u+Math.abs(a)-1,f=a===0,d=a<0,h=e%2!==0;return{nextN:c,offset:l,isZero:f,isNeg:d,isNegF:h,offsetF:u}}function HI(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 GI(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 al=new WeakMap,Gg=new WeakMap;function cl(t){return Gg.get(t)||1}function Wg(t){if(t!==Ai)throw new Error("invalid wNAF")}class WI{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>Ai;)n&Zr&&(r=r.add(i)),i=i.double(),n>>=Zr;return r}precomputeWindow(e,n){const{windows:r,windowSize:i}=ol(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=ol(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:f,isNegF:d,offsetF:h}=Hg(r,a,o);r=c,l?s=s.add(pa(d,n[h])):i=i.add(pa(f,n[u]))}return Wg(r),{p:i,f:s}}wNAFUnsafe(e,n,r,i=this.ZERO){const s=ol(e,this.bits);for(let o=0;o<s.windows&&r!==Ai;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=Hg(r,o,s);if(r=a,!u){const f=n[c];i=i.add(l?f.negate():f)}}return Wg(r),i}getPrecomputes(e,n,r){let i=al.get(n);return i||(i=this.precomputeWindow(n,e),e!==1&&(typeof r=="function"&&(i=r(i)),al.set(n,i))),i}cached(e,n,r){const i=cl(e);return this.wNAF(i,this.getPrecomputes(i,e,r),n)}unsafe(e,n,r,i){const s=cl(e);return s===1?this._unsafeLadder(e,n,i):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),n,i)}createCache(e,n){Kg(n,this.bits),Gg.set(e,n),al.delete(e)}hasCache(e){return cl(e)!==1}}function ZI(t,e,n,r){let i=e,s=t.ZERO,o=t.ZERO;for(;n>Ai||r>Ai;)n&Zr&&(s=s.add(i)),r&Zr&&(o=o.add(i)),i=i.double(),n>>=Zr,r>>=Zr;return{p1:s,p2:o}}function YI(t,e,n,r){HI(n,t),GI(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=$g(BigInt(i));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Is(c),l=new Array(Number(u)+1).fill(o),f=Math.floor((e.BITS-1)/c)*c;let d=o;for(let h=f;h>=0;h-=c){l.fill(o);for(let g=0;g<s;g++){const m=r[g],B=Number(m>>BigInt(h)&u);l[B]=l[B].add(n[g])}let p=o;for(let g=l.length-1,m=o;g>0;g--)m=m.add(l[g]),p=p.add(m);if(d=d.add(p),h!==0)for(let g=0;g<c;g++)d=d.double()}return d}function Zg(t,e,n){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return zI(e),e}else return _r(t,{isLE:n})}function XI(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>Ai))throw new Error(`CURVE.${a} must be positive bigint`)}const i=Zg(e.p,n.Fp,r),s=Zg(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),X0("HashToScalar-");const Ss=BigInt(0),Di=BigInt(1),ga=BigInt(2);function JI(t){return da(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(_i({},t))}function QI(t){const e=JI(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||Kr,u=a?255:448,l=a?32:56,f=BigInt(a?9:5),d=BigInt(a?121665:39081),h=a?ga**BigInt(254):ga**BigInt(447),p=a?BigInt(8)*ga**BigInt(251)-Di:BigInt(4)*ga**BigInt(445)-Di,g=h+p+Di,m=E=>Tt(E,n),B=$(f);function $(E){return tl(m(E),l)}function x(E){const b=tt("u coordinate",E,l);return a&&(b[31]&=127),m(ha(b))}function _(E){return ha(i(tt("scalar",E,l)))}function T(E,b){const v=U(x(b),_(E));if(v===Ss)throw new Error("invalid private or public key received");return $(v)}function P(E){return T(E,B)}function C(E,b,v){const y=m(E*(b-v));return b=m(b-y),v=m(v+y),{x_2:b,x_3:v}}function U(E,b){rl("u",E,Ss,n),rl("scalar",b,h,g);const v=b,y=E;let w=Di,I=Ss,O=E,S=Di,A=Ss;for(let k=BigInt(u-1);k>=Ss;k--){const F=v>>k&Di;A^=F,{x_2:w,x_3:O}=C(A,w,O),{x_2:I,x_3:S}=C(A,I,S),A=F;const L=w+I,N=m(L*L),q=w-I,z=m(q*q),W=N-z,K=O+S,Z=O-S,Q=m(Z*L),ee=m(K*q),ie=Q+ee,he=Q-ee;O=m(ie*ie),S=m(y*m(he*he)),w=m(N*z),I=m(W*(N+m(d*W)))}({x_2:w,x_3:O}=C(A,w,O)),{x_2:I,x_3:S}=C(A,I,S);const R=s(I);return m(w*R)}const D={secretKey:l,publicKey:l,seed:l},j=(E=c(l))=>(Xt(E,D.seed),E);function M(E){const b=j(E);return{secretKey:b,publicKey:P(b)}}return{keygen:M,getSharedSecret:(E,b)=>T(E,b),getPublicKey:E=>P(E),scalarMult:T,scalarMultBase:P,utils:{randomSecretKey:j,randomPrivateKey:j},GuBytes:B.slice(),lengths:D}}const eS=BigInt(1),Yg=BigInt(2),tS=BigInt(3),nS=BigInt(5),rS=BigInt(8),Xg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),iS={p:Xg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:rS,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function sS(t){const e=BigInt(10),n=BigInt(20),r=BigInt(40),i=BigInt(80),s=Xg,o=t*t%s*t%s,a=Qt(o,Yg,s)*o%s,c=Qt(a,eS,s)*t%s,u=Qt(c,nS,s)*c%s,l=Qt(u,e,s)*u%s,f=Qt(l,n,s)*l%s,d=Qt(f,r,s)*f%s,h=Qt(d,i,s)*d%s,p=Qt(h,i,s)*d%s,g=Qt(p,e,s)*u%s;return{pow_p_5_8:Qt(g,Yg,s)*t%s,b2:o}}function oS(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const aS=_r(iS.p,{isLE:!0}),ul=(()=>{const t=aS.ORDER;return QI({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:n,b2:r}=sS(e);return Tt(Qt(n,tS,t)*r,t)},adjustScalarBytes:oS})})(),Jg=(t,e)=>(t+(t>=0?e:-e)/Qg)/e;function cS(t,e,n){const[[r,i],[s,o]]=e,a=Jg(o*t,n),c=Jg(-i*t,n);let u=t-a*r-c*s,l=-a*i-c*o;const f=u<Fn,d=l<Fn;f&&(u=-u),d&&(l=-l);const h=Is(Math.ceil($g(n)/2))+$i;if(u<Fn||u>=h||l<Fn||l>=h)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:f,k1:u,k2neg:d,k2:l}}function ll(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function fl(t,e){const n={};for(let r of Object.keys(e))n[r]=t[r]===void 0?e[r]:t[r];return ua(n.lowS,"lowS"),ua(n.prehash,"prehash"),n.format!==void 0&&ll(n.format),n}class uS extends Error{constructor(e=""){super(e)}}const Un={Err:uS,_tlv:{encode:(t,e)=>{const{Err:n}=Un;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=la(r);if(i.length/2&128)throw new n("tlv.encode: long form length too big");const s=r>127?la(i.length/2|128):"";return la(t)+s+i+e},decode(t,e){const{Err:n}=Un;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}=Un;if(t<Fn)throw new e("integer: negative integers are not allowed");let n=la(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}=Un;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 fa(t)}},toSig(t){const{Err:e,_int:n,_tlv:r}=Un,i=tt("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}=Un,r=e.encode(2,n.encode(t.r)),i=e.encode(2,n.encode(t.s)),s=r+i;return e.encode(48,s)}},Fn=BigInt(0),$i=BigInt(1),Qg=BigInt(2),ya=BigInt(3),lS=BigInt(4);function Ti(t,e){const{BYTES:n}=t;let r;if(typeof e=="bigint")r=e;else{let i=tt("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 fS(t,e={}){const n=XI("weierstrass",t,e),{Fp:r,Fn:i}=n;let s=n.CURVE;const{h:o,n:a}=s;da(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=t1(r,i);function l(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(E,b,v){const{x:y,y:w}=b.toAffine(),I=r.toBytes(y);if(ua(v,"isCompressed"),v){l();const O=!r.isOdd(w);return gr(e1(O),I)}else return gr(Uint8Array.of(4),I,r.toBytes(w))}function d(E){Gr(E,void 0,"Point");const{publicKey:b,publicKeyUncompressed:v}=u,y=E.length,w=E[0],I=E.subarray(1);if(y===b&&(w===2||w===3)){const O=r.fromBytes(I);if(!r.isValid(O))throw new Error("bad point: is not on curve, wrong x");const S=g(O);let A;try{A=r.sqrt(S)}catch(k){const F=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}l();const R=r.isOdd(A);return(w&1)===1!==R&&(A=r.neg(A)),{x:O,y:A}}else if(y===v&&w===4){const O=r.BYTES,S=r.fromBytes(I.subarray(0,O)),A=r.fromBytes(I.subarray(O,O*2));if(!m(S,A))throw new Error("bad point: is not on curve");return{x:S,y:A}}else throw new Error(`bad point: got length ${y}, expected compressed=${b} or uncompressed=${v}`)}const h=e.toBytes||f,p=e.fromBytes||d;function g(E){const b=r.sqr(E),v=r.mul(b,E);return r.add(r.add(v,r.mul(E,s.a)),s.b)}function m(E,b){const v=r.sqr(b),y=g(E);return r.eql(v,y)}if(!m(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const B=r.mul(r.pow(s.a,ya),lS),$=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(B,$)))throw new Error("bad curve params: a or b");function x(E,b,v=!1){if(!r.isValid(b)||v&&r.is0(b))throw new Error(`bad point coordinate ${E}`);return b}function _(E){if(!(E instanceof D))throw new Error("ProjectivePoint expected")}function T(E){if(!c||!c.basises)throw new Error("no endo");return cS(E,c.basises,i.ORDER)}const P=Tg((E,b)=>{const{X:v,Y:y,Z:w}=E;if(r.eql(w,r.ONE))return{x:v,y};const I=E.is0();b==null&&(b=I?r.ONE:r.inv(w));const O=r.mul(v,b),S=r.mul(y,b),A=r.mul(w,b);if(I)return{x:r.ZERO,y:r.ZERO};if(!r.eql(A,r.ONE))throw new Error("invZ was invalid");return{x:O,y:S}}),C=Tg(E=>{if(E.is0()){if(e.allowInfinityPoint&&!r.is0(E.Y))return;throw new Error("bad point: ZERO")}const{x:b,y:v}=E.toAffine();if(!r.isValid(b)||!r.isValid(v))throw new Error("bad point: x or y not field elements");if(!m(b,v))throw new Error("bad point: equation left != right");if(!E.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(E,b,v,y,w){return v=new D(r.mul(v.X,E),v.Y,v.Z),b=pa(y,b),v=pa(w,v),b.add(v)}class D{constructor(b,v,y){this.X=x("x",b),this.Y=x("y",v,!0),this.Z=x("z",y),Object.freeze(this)}static CURVE(){return s}static fromAffine(b){const{x:v,y}=b||{};if(!b||!r.isValid(v)||!r.isValid(y))throw new Error("invalid affine point");if(b instanceof D)throw new Error("projective point not allowed");return r.is0(v)&&r.is0(y)?D.ZERO:new D(v,y,r.ONE)}static fromBytes(b){const v=D.fromAffine(p(Gr(b,void 0,"point")));return v.assertValidity(),v}static fromHex(b){return D.fromBytes(tt("pointHex",b))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(b=8,v=!0){return M.createCache(this,b),v||this.multiply(ya),this}assertValidity(){C(this)}hasEvenY(){const{y:b}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(b)}equals(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b,A=r.eql(r.mul(v,S),r.mul(I,w)),R=r.eql(r.mul(y,S),r.mul(O,w));return A&&R}negate(){return new D(this.X,r.neg(this.Y),this.Z)}double(){const{a:b,b:v}=s,y=r.mul(v,ya),{X:w,Y:I,Z:O}=this;let S=r.ZERO,A=r.ZERO,R=r.ZERO,k=r.mul(w,w),F=r.mul(I,I),L=r.mul(O,O),N=r.mul(w,I);return N=r.add(N,N),R=r.mul(w,O),R=r.add(R,R),S=r.mul(b,R),A=r.mul(y,L),A=r.add(S,A),S=r.sub(F,A),A=r.add(F,A),A=r.mul(S,A),S=r.mul(N,S),R=r.mul(y,R),L=r.mul(b,L),N=r.sub(k,L),N=r.mul(b,N),N=r.add(N,R),R=r.add(k,k),k=r.add(R,k),k=r.add(k,L),k=r.mul(k,N),A=r.add(A,k),L=r.mul(I,O),L=r.add(L,L),k=r.mul(L,N),S=r.sub(S,k),R=r.mul(L,F),R=r.add(R,R),R=r.add(R,R),new D(S,A,R)}add(b){_(b);const{X:v,Y:y,Z:w}=this,{X:I,Y:O,Z:S}=b;let A=r.ZERO,R=r.ZERO,k=r.ZERO;const F=s.a,L=r.mul(s.b,ya);let N=r.mul(v,I),q=r.mul(y,O),z=r.mul(w,S),W=r.add(v,y),K=r.add(I,O);W=r.mul(W,K),K=r.add(N,q),W=r.sub(W,K),K=r.add(v,w);let Z=r.add(I,S);return K=r.mul(K,Z),Z=r.add(N,z),K=r.sub(K,Z),Z=r.add(y,w),A=r.add(O,S),Z=r.mul(Z,A),A=r.add(q,z),Z=r.sub(Z,A),k=r.mul(F,K),A=r.mul(L,z),k=r.add(A,k),A=r.sub(q,k),k=r.add(q,k),R=r.mul(A,k),q=r.add(N,N),q=r.add(q,N),z=r.mul(F,z),K=r.mul(L,K),q=r.add(q,z),z=r.sub(N,z),z=r.mul(F,z),K=r.add(K,z),N=r.mul(q,K),R=r.add(R,N),N=r.mul(Z,K),A=r.mul(W,A),A=r.sub(A,N),N=r.mul(W,q),k=r.mul(Z,k),k=r.add(k,N),new D(A,R,k)}subtract(b){return this.add(b.negate())}is0(){return this.equals(D.ZERO)}multiply(b){const{endo:v}=e;if(!i.isValidNot0(b))throw new Error("invalid scalar: out of range");let y,w;const I=O=>M.cached(this,O,S=>sl(D,S));if(v){const{k1neg:O,k1:S,k2neg:A,k2:R}=T(b),{p:k,f:F}=I(S),{p:L,f:N}=I(R);w=F.add(N),y=U(v.beta,k,L,O,A)}else{const{p:O,f:S}=I(b);y=O,w=S}return sl(D,[y,w])[0]}multiplyUnsafe(b){const{endo:v}=e,y=this;if(!i.isValid(b))throw new Error("invalid scalar: out of range");if(b===Fn||y.is0())return D.ZERO;if(b===$i)return y;if(M.hasCache(this))return this.multiply(b);if(v){const{k1neg:w,k1:I,k2neg:O,k2:S}=T(b),{p1:A,p2:R}=ZI(D,y,I,S);return U(v.beta,A,R,w,O)}else return M.unsafe(y,b)}multiplyAndAddUnsafe(b,v,y){const w=this.multiplyUnsafe(v).add(b.multiplyUnsafe(y));return w.is0()?void 0:w}toAffine(b){return P(this,b)}isTorsionFree(){const{isTorsionFree:b}=e;return o===$i?!0:b?b(D,this):M.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:b}=e;return o===$i?this:b?b(D,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(b=!0){return ua(b,"isCompressed"),this.assertValidity(),h(D,this,b)}toHex(b=!0){return Oi(this.toBytes(b))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(b=!0){return this.toBytes(b)}_setWindowSize(b){this.precompute(b)}static normalizeZ(b){return sl(D,b)}static msm(b,v){return YI(D,i,b,v)}static fromPrivateKey(b){return D.BASE.multiply(Ti(i,b))}}D.BASE=new D(s.Gx,s.Gy,r.ONE),D.ZERO=new D(r.ZERO,r.ONE,r.ZERO),D.Fp=r,D.Fn=i;const j=i.BITS,M=new WI(D,e.endo?Math.ceil(j/2):j);return D.BASE.precompute(8),D}function e1(t){return Uint8Array.of(t?2:3)}function t1(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function hS(t,e={}){const{Fn:n}=t,r=e.randomBytes||Kr,i=Object.assign(t1(t.Fp,n),{seed:Vg(n.ORDER)});function s(d){try{return!!Ti(n,d)}catch{return!1}}function o(d,h){const{publicKey:p,publicKeyUncompressed:g}=i;try{const m=d.length;return h===!0&&m!==p||h===!1&&m!==g?!1:!!t.fromBytes(d)}catch{return!1}}function a(d=r(i.seed)){return KI(Gr(d,i.seed,"seed"),n.ORDER)}function c(d,h=!0){return t.BASE.multiply(Ti(n,d)).toBytes(h)}function u(d){const h=a(d);return{secretKey:h,publicKey:c(h)}}function l(d){if(typeof d=="bigint")return!1;if(d instanceof t)return!0;const{secretKey:h,publicKey:p,publicKeyUncompressed:g}=i;if(n.allowedLengths||h===p)return;const m=tt("key",d).length;return m===p||m===g}function f(d,h,p=!0){if(l(d)===!0)throw new Error("first arg must be private key");if(l(h)===!1)throw new Error("second arg must be public key");const g=Ti(n,d);return t.fromHex(h).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:d=>Ti(n,d),precompute(d=8,h=t.BASE){return h.precompute(d,!1)}},lengths:i})}function dS(t,e,n={}){Qo(e),da(n,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=n.randomBytes||Kr,i=n.hmac||((v,...y)=>aa(e,v,gr(...y))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h}=hS(t,n),p={prehash:!1,lowS:typeof n.lowS=="boolean"?n.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function m(v){const y=a>>$i;return v>y}function B(v,y){if(!o.isValidNot0(y))throw new Error(`invalid signature ${v}: out of range 1..Point.Fn.ORDER`);return y}function $(v,y){ll(y);const w=h.signature,I=y==="compact"?w:y==="recovered"?w+1:void 0;return Gr(v,I,`${y} signature`)}class x{constructor(y,w,I){this.r=B("r",y),this.s=B("s",w),I!=null&&(this.recovery=I),Object.freeze(this)}static fromBytes(y,w=g){$(y,w);let I;if(w==="der"){const{r:R,s:k}=Un.toSig(Gr(y));return new x(R,k)}w==="recovered"&&(I=y[0],w="compact",y=y.subarray(1));const O=o.BYTES,S=y.subarray(0,O),A=y.subarray(O,O*2);return new x(o.fromBytes(S),o.fromBytes(A),I)}static fromHex(y,w){return this.fromBytes(ea(y),w)}addRecoveryBit(y){return new x(this.r,this.s,y)}recoverPublicKey(y){const w=s.ORDER,{r:I,s:O,recovery:S}=this;if(S==null||![0,1,2,3].includes(S))throw new Error("recovery id invalid");if(a*Qg<w&&S>1)throw new Error("recovery id is ambiguous for h>1 curve");const A=S===2||S===3?I+a:I;if(!s.isValid(A))throw new Error("recovery id 2 or 3 invalid");const R=s.toBytes(A),k=t.fromBytes(gr(e1((S&1)===0),R)),F=o.inv(A),L=T(tt("msgHash",y)),N=o.create(-L*F),q=o.create(O*F),z=t.BASE.multiplyUnsafe(N).add(k.multiplyUnsafe(q));if(z.is0())throw new Error("point at infinify");return z.assertValidity(),z}hasHighS(){return m(this.s)}toBytes(y=g){if(ll(y),y==="der")return ea(Un.hexFromSig(this));const w=o.toBytes(this.r),I=o.toBytes(this.s);if(y==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return gr(Uint8Array.of(this.recovery),w,I)}return gr(w,I)}toHex(y){return Oi(this.toBytes(y))}assertValidity(){}static fromCompact(y){return x.fromBytes(tt("sig",y),"compact")}static fromDER(y){return x.fromBytes(tt("sig",y),"der")}normalizeS(){return this.hasHighS()?new x(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Oi(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Oi(this.toBytes("compact"))}}const _=n.bits2int||function(v){if(v.length>8192)throw new Error("input is too large");const y=fa(v),w=v.length*8-c;return w>0?y>>BigInt(w):y},T=n.bits2int_modN||function(v){return o.create(_(v))},P=Is(c);function C(v){return rl("num < 2^"+c,v,Fn,P),o.toBytes(v)}function U(v,y){return Gr(v,void 0,"message"),y?Gr(e(v),void 0,"prehashed message"):v}function D(v,y,w){if(["recovered","canonical"].some(q=>q in w))throw new Error("sign() legacy options not supported");const{lowS:I,prehash:O,extraEntropy:S}=fl(w,p);v=U(v,O);const A=T(v),R=Ti(o,y),k=[C(R),C(A)];if(S!=null&&S!==!1){const q=S===!0?r(h.secretKey):S;k.push(tt("extraEntropy",q))}const F=gr(...k),L=A;function N(q){const z=_(q);if(!o.isValidNot0(z))return;const W=o.inv(z),K=t.BASE.multiply(z).toAffine(),Z=o.create(K.x);if(Z===Fn)return;const Q=o.create(W*o.create(L+Z*R));if(Q===Fn)return;let ee=(K.x===Z?0:2)|Number(K.y&$i),ie=Q;return I&&m(Q)&&(ie=o.neg(Q),ee^=1),new x(Z,ie,ee)}return{seed:F,k2sig:N}}function j(v,y,w={}){v=tt("message",v);const{seed:I,k2sig:O}=D(v,y,w);return UI(e.outputLen,o.BYTES,i)(I,O)}function M(v){let y;const w=typeof v=="string"||Jo(v),I=!w&&v!==null&&typeof v=="object"&&typeof v.r=="bigint"&&typeof v.s=="bigint";if(!w&&!I)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(I)y=new x(v.r,v.s);else if(w){try{y=x.fromBytes(tt("sig",v),"der")}catch(O){if(!(O instanceof Un.Err))throw O}if(!y)try{y=x.fromBytes(tt("sig",v),"compact")}catch{return!1}}return y||!1}function E(v,y,w,I={}){const{lowS:O,prehash:S,format:A}=fl(I,p);if(w=tt("publicKey",w),y=U(tt("message",y),S),"strict"in I)throw new Error("options.strict was renamed to lowS");const R=A===void 0?M(v):x.fromBytes(tt("sig",v),A);if(R===!1)return!1;try{const k=t.fromBytes(w);if(O&&R.hasHighS())return!1;const{r:F,s:L}=R,N=T(y),q=o.inv(L),z=o.create(N*q),W=o.create(F*q),K=t.BASE.multiplyUnsafe(z).add(k.multiplyUnsafe(W));return K.is0()?!1:o.create(K.x)===F}catch{return!1}}function b(v,y,w={}){const{prehash:I}=fl(w,p);return y=U(y,I),x.fromBytes(v,"recovered").recoverPublicKey(y).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:f,utils:d,lengths:h,Point:t,sign:j,verify:E,recoverPublicKey:b,Signature:x,hash:e})}function pS(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=_r(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 gS(t){const{CURVE:e,curveOpts:n}=pS(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 yS(t,e){const n=e.Point;return Object.assign({},e,{ProjectivePoint:n,CURVE:Object.assign({},t,jg(n.Fn.ORDER,n.Fn.BITS))})}function bS(t){const{CURVE:e,curveOpts:n,hash:r,ecdsaOpts:i}=gS(t),s=fS(e,n),o=dS(s,r,i);return yS(t,o)}function hl(t,e){const n=r=>bS(ys(_i({},t),{hash:r}));return ys(_i({},n(e)),{create:n})}const n1={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},r1={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},i1={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},wS=_r(n1.p),mS=_r(r1.p),vS=_r(i1.p),ES=hl(ys(_i({},n1),{Fp:wS,lowS:!1}),na);hl(ys(_i({},r1),{Fp:mS,lowS:!1}),S5),hl(ys(_i({},i1),{Fp:vS,lowS:!1,allowedPrivateKeyLengths:[130,131,132]}),I5);const xS=ES,s1="base10",lt="base16",xt="base64pad",Ir="base64url",Os="utf8",o1=0,kn=1,Bs=2,_S=0,a1=1,As=12,dl=32;function IS(){const t=ul.utils.randomPrivateKey(),e=ul.getPublicKey(t);return{privateKey:mt(t,lt),publicKey:mt(e,lt)}}function pl(){const t=Kr(dl);return mt(t,lt)}function SS(t,e){const n=ul.getSharedSecret(Lt(t,lt),Lt(e,lt)),r=NI(ca,n,void 0,void 0,dl);return mt(r,lt)}function ba(t){const e=ca(Lt(t,lt));return mt(e,lt)}function Mt(t){const e=ca(Lt(t,Os));return mt(e,lt)}function c1(t){return Lt(`${t}`,s1)}function Yr(t){return Number(mt(t,s1))}function u1(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function l1(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4;return e+"=".repeat(n)}function OS(t){const e=c1(typeof t.type<"u"?t.type:o1);if(Yr(e)===kn&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const n=typeof t.senderPublicKey<"u"?Lt(t.senderPublicKey,lt):void 0,r=typeof t.iv<"u"?Lt(t.iv,lt):Kr(As),i=Lt(t.symKey,lt),s=Og(i,r).encrypt(Lt(t.message,Os)),o=f1({type:e,sealed:s,iv:r,senderPublicKey:n});return t.encoding===Ir?u1(o):o}function BS(t){const e=Lt(t.symKey,lt),{sealed:n,iv:r}=Ds({encoded:t.encoded,encoding:t.encoding}),i=Og(e,r).decrypt(n);if(i===null)throw new Error("Failed to decrypt");return mt(i,Os)}function AS(t,e){const n=c1(Bs),r=Kr(As),i=Lt(t,Os),s=f1({type:n,sealed:i,iv:r});return e===Ir?u1(s):s}function DS(t,e){const{sealed:n}=Ds({encoded:t,encoding:e});return mt(n,Os)}function f1(t){if(Yr(t.type)===Bs)return mt(fs([t.type,t.sealed]),xt);if(Yr(t.type)===kn){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return mt(fs([t.type,t.senderPublicKey,t.iv,t.sealed]),xt)}return mt(fs([t.type,t.iv,t.sealed]),xt)}function Ds(t){const e=(t.encoding||xt)===Ir?l1(t.encoded):t.encoded,n=Lt(e,xt),r=n.slice(_S,a1),i=a1;if(Yr(r)===kn){const c=i+dl,u=c+As,l=n.slice(i,c),f=n.slice(c,u),d=n.slice(u);return{type:r,sealed:d,iv:f,senderPublicKey:l}}if(Yr(r)===Bs){const c=n.slice(i),u=Kr(As);return{type:r,sealed:c,iv:u}}const s=i+As,o=n.slice(i,s),a=n.slice(s);return{type:r,sealed:a,iv:o}}function $S(t,e){const n=Ds({encoded:t,encoding:e?.encoding});return h1({type:Yr(n.type),senderPublicKey:typeof n.senderPublicKey<"u"?mt(n.senderPublicKey,lt):void 0,receiverPublicKey:e?.receiverPublicKey})}function h1(t){const e=t?.type||o1;if(e===kn){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 d1(t){return t.type===kn&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function p1(t){return t.type===Bs}function TS(t){const e=Buffer.from(t.x,"base64"),n=Buffer.from(t.y,"base64");return fs([new Uint8Array([4]),e,n])}function PS(t,e){const[n,r,i]=t.split("."),s=Buffer.from(l1(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=ca(c),l=TS(e);if(!xS.verify(fs([o,a]),u,l))throw new Error("Invalid signature");return yc(t).payload}const RS="irn";function wa(t){return t?.relay||{protocol:RS}}function Pi(t){const e=t_[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var NS=Object.defineProperty,CS=Object.defineProperties,US=Object.getOwnPropertyDescriptors,g1=Object.getOwnPropertySymbols,FS=Object.prototype.hasOwnProperty,kS=Object.prototype.propertyIsEnumerable,y1=(t,e,n)=>e in t?NS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,gl=(t,e)=>{for(var n in e||(e={}))FS.call(e,n)&&y1(t,n,e[n]);if(g1)for(var n of g1(e))kS.call(e,n)&&y1(t,n,e[n]);return t},LS=(t,e)=>CS(t,US(e));function qS(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 b1(t){if(!t.includes("wc:")){const u=M0(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:MS(i[0]),version:parseInt(i[1],10),symKey:a.symKey,relay:qS(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function MS(t){return t.startsWith("//")?t.substring(2):t}function jS(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 w1(t){const e=new URLSearchParams,n=gl(gl(LS(gl({},jS(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 ma(t,e,n){return`${t}?wc_ev=${n}&topic=${e}`}var zS=Object.defineProperty,VS=Object.defineProperties,KS=Object.getOwnPropertyDescriptors,m1=Object.getOwnPropertySymbols,HS=Object.prototype.hasOwnProperty,GS=Object.prototype.propertyIsEnumerable,v1=(t,e,n)=>e in t?zS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,WS=(t,e)=>{for(var n in e||(e={}))HS.call(e,n)&&v1(t,n,e[n]);if(m1)for(var n of m1(e))GS.call(e,n)&&v1(t,n,e[n]);return t},ZS=(t,e)=>VS(t,KS(e));function Ri(t){const e=[];return t.forEach(n=>{const[r,i]=n.split(":");e.push(`${r}:${i}`)}),e}function E1(t){const e=[];return Object.values(t).forEach(n=>{e.push(...Ri(n.accounts))}),[...new Set(e)]}function YS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.methods)}),[...new Set(e)]}function XS(t){const e=[];return Object.values(t).forEach(n=>{e.push(...n.events)}),[...new Set(e)]}function JS(t,e){const n=[];return Object.values(t).forEach(r=>{Ri(r.accounts).includes(e)&&n.push(...r.methods)}),n}function QS(t,e){const n=[];return Object.values(t).forEach(r=>{Ri(r.accounts).includes(e)&&n.push(...r.events)}),n}function x1(t){return t.includes(":")}function e9(t){return x1(t)?t.split(":")[0]:t}function _1(t){var e,n,r;const i={};if(!$s(t))return i;for(const[s,o]of Object.entries(t)){const a=x1(s)?[s]:o.chains,c=o.methods||[],u=o.events||[],l=e9(s);i[l]=ZS(WS({},i[l]),{chains:Vr(a,(e=i[l])==null?void 0:e.chains),methods:Vr(c,(n=i[l])==null?void 0:n.methods),events:Vr(u,(r=i[l])==null?void 0:r.events)})}return i}function t9(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 I1(t,e){e=e.map(r=>r.replace("did:pkh:",""));const n=t9(e);for(const[r,i]of Object.entries(n))i.methods?i.methods=Vr(i.methods,t):i.methods=t,i.events=["chainChanged","accountsChanged"];return n}function n9(t,e){var n,r,i,s,o,a;const c=_1(t),u=_1(e),l={},f=Object.keys(c).concat(Object.keys(u));for(const d of f)l[d]={chains:Vr((n=c[d])==null?void 0:n.chains,(r=u[d])==null?void 0:r.chains),methods:Vr((i=c[d])==null?void 0:i.methods,(s=u[d])==null?void 0:s.methods),events:Vr((o=c[d])==null?void 0:o.events,(a=u[d])==null?void 0:a.events)};return l}const r9={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}},i9={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 G(t,e){const{message:n,code:r}=i9[t];return{message:e?`${n} ${e}`:n,code:r}}function xe(t,e){const{message:n,code:r}=r9[t];return{message:e?`${n} ${e}`:n,code:r}}function Ni(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function $s(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Re(t){return typeof t>"u"}function Oe(t,e){return e&&Re(t)?!0:typeof t=="string"&&!!t.trim().length}function yl(t,e){return e&&Re(t)?!0:typeof t=="number"&&!isNaN(t)}function s9(t,e){const{requiredNamespaces:n}=e,r=Object.keys(t.namespaces),i=Object.keys(n);let s=!0;return jr(i,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=Ri(a),f=n[o];(!jr($0(o,f),l)||!jr(f.methods,c)||!jr(f.events,u))&&(s=!1)}),s):!1}function Ts(t){return Oe(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function o9(t){if(Oe(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const n=e[0]+":"+e[1];return!!e[2]&&Ts(n)}}return!1}function a9(t){function e(n){try{return typeof new URL(n)<"u"}catch{return!1}}try{if(Oe(t,!1)){if(e(t))return!0;const n=M0(t);return e(n)}}catch{}return!1}function c9(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function u9(t){return t?.topic}function l9(t,e){let n=null;return Oe(t?.publicKey,!1)||(n=G("MISSING_OR_INVALID",`${e} controller public key should be a string`)),n}function S1(t){let e=!0;return Ni(t)?t.length&&(e=t.every(n=>Oe(n,!1))):e=!1,e}function f9(t,e,n){let r=null;return Ni(e)&&e.length?e.forEach(i=>{r||Ts(i)||(r=xe("UNSUPPORTED_CHAINS",`${n}, chain ${i} should be a string and conform to "namespace:chainId" format`))}):Ts(t)||(r=xe("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 h9(t,e,n){let r=null;return Object.entries(t).forEach(([i,s])=>{if(r)return;const o=f9(i,$0(i,s),`${e} ${n}`);o&&(r=o)}),r}function d9(t,e){let n=null;return Ni(t)?t.forEach(r=>{n||o9(r)||(n=xe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):n=xe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),n}function p9(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=d9(r?.accounts,`${e} namespace`);i&&(n=i)}),n}function g9(t,e){let n=null;return S1(t?.methods)?S1(t?.events)||(n=xe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):n=xe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),n}function O1(t,e){let n=null;return Object.values(t).forEach(r=>{if(n)return;const i=g9(r,`${e}, namespace`);i&&(n=i)}),n}function y9(t,e,n){let r=null;if(t&&$s(t)){const i=O1(t,e);i&&(r=i);const s=h9(t,e,n);s&&(r=s)}else r=G("MISSING_OR_INVALID",`${e}, ${n} should be an object with data`);return r}function bl(t,e){let n=null;if(t&&$s(t)){const r=O1(t,e);r&&(n=r);const i=p9(t,e);i&&(n=i)}else n=G("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return n}function B1(t){return Oe(t.protocol,!0)}function b9(t,e){let n=!1;return e&&!t?n=!0:t&&Ni(t)&&t.length&&t.forEach(r=>{n=B1(r)}),n}function w9(t){return typeof t=="number"}function _t(t){return typeof t<"u"&&typeof t!==null}function m9(t){return!(!t||typeof t!="object"||!t.code||!yl(t.code,!1)||!t.message||!Oe(t.message,!1))}function v9(t){return!(Re(t)||!Oe(t.method,!1))}function E9(t){return!(Re(t)||Re(t.result)&&Re(t.error)||!yl(t.id,!1)||!Oe(t.jsonrpc,!1))}function x9(t){return!(Re(t)||!Oe(t.name,!1))}function A1(t,e){return!(!Ts(e)||!E1(t).includes(e))}function _9(t,e,n){return Oe(n,!1)?JS(t,e).includes(n):!1}function I9(t,e,n){return Oe(n,!1)?QS(t,e).includes(n):!1}function D1(t,e,n){let r=null;const i=S9(t),s=O9(e),o=Object.keys(i),a=Object.keys(s),c=$1(Object.keys(t)),u=$1(Object.keys(e)),l=c.filter(f=>!u.includes(f));return l.length&&(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces keys don't satisfy requiredNamespaces.
|
|
22
22
|
Required: ${l.toString()}
|
|
23
|
-
Received: ${Object.keys(e).toString()}`)),
|
|
23
|
+
Received: ${Object.keys(e).toString()}`)),jr(o,a)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces chains don't satisfy required namespaces.
|
|
24
24
|
Required: ${o.toString()}
|
|
25
|
-
Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||r)return;const d=
|
|
25
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(f=>{if(!f.includes(":")||r)return;const d=Ri(e[f].accounts);d.includes(f)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces accounts don't satisfy namespace accounts for ${f}
|
|
26
26
|
Required: ${f}
|
|
27
|
-
Approved: ${d.toString()}`))}),o.forEach(f=>{r||(
|
|
27
|
+
Approved: ${d.toString()}`))}),o.forEach(f=>{r||(jr(i[f].methods,s[f].methods)?jr(i[f].events,s[f].events)||(r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces events don't satisfy namespace events for ${f}`)):r=G("NON_CONFORMING_NAMESPACES",`${n} namespaces methods don't satisfy namespace methods for ${f}`))}),r}function S9(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 $1(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function O9(t){const e={};return Object.keys(t).forEach(n=>{if(n.includes(":"))e[n]=t[n];else{const r=Ri(t[n].accounts);r?.forEach(i=>{e[i]={accounts:t[n].accounts.filter(s=>s.includes(`${i}:`)),methods:t[n].methods,events:t[n].events}})}}),e}function B9(t,e){return yl(t,!1)&&t<=e.max&&t>=e.min}function T1(){const t=bs();return new Promise(e=>{switch(t){case $t.browser:e(A9());break;case $t.reactNative:e(D9());break;case $t.node:e($9());break;default:e(!0)}})}function A9(){return Ii()&&navigator?.onLine}async function D9(){if(ur()&&typeof global<"u"&&global!=null&&global.NetInfo){const t=await(global==null?void 0:global.NetInfo.fetch());return t?.isConnected}return!0}function $9(){return!0}function T9(t){switch(bs()){case $t.browser:P9(t);break;case $t.reactNative:R9(t);break}}function P9(t){!ur()&&Ii()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function R9(t){ur()&&typeof global<"u"&&global!=null&&global.NetInfo&&global?.NetInfo.addEventListener(e=>t(e?.isConnected))}function N9(){var t;return Ii()&&Nr()?((t=Nr())==null?void 0:t.visibilityState)==="visible":!0}const wl={};class Ps{static get(e){return wl[e]}static set(e,n){wl[e]=n}static delete(e){delete wl[e]}}function C9(t){const e=as.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function U9({publicKey:t,signature:e,payload:n}){var r;const i=ml(n.method),s=128|parseInt(((r=n.version)==null?void 0:r.toString())||"4"),o=L9(n.address),a=n.era==="00"?new Uint8Array([0]):ml(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${k9(n.tip)}`),f=M9(l),d=new Uint8Array([0,...t,o,...e,...a,...u,...f,...i]),h=q9(d.length+1);return new Uint8Array([...h,s,...d])}function F9(t){const e=ml(t),n=d_.blake2b(e,void 0,32);return"0x"+Buffer.from(n).toString("hex")}function ml(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function k9(t){return t.startsWith("0x")?t.slice(2):t}function L9(t){const e=as.decode(t)[0];return e===42?0:e===60?2:1}function q9(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 M9(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 j9(t){const e=Uint8Array.from(Buffer.from(t.signature,"hex")),n=C9(t.transaction.address),r=U9({publicKey:n,signature:e,payload:t.transaction}),i=Buffer.from(r).toString("hex");return F9(i)}function P1({logger:t,name:e}){const n=typeof t=="string"?Ff({opts:{level:t,name:e}}).logger:t;return n.level=typeof t=="string"?t:t.level,n}const z9="PARSE_ERROR",V9="INVALID_REQUEST",K9="METHOD_NOT_FOUND",H9="INVALID_PARAMS",R1="INTERNAL_ERROR",vl="SERVER_ERROR",G9=[-32700,-32600,-32601,-32602,-32603],Rs={[z9]:{code:-32700,message:"Parse error"},[V9]:{code:-32600,message:"Invalid Request"},[K9]:{code:-32601,message:"Method not found"},[H9]:{code:-32602,message:"Invalid params"},[R1]:{code:-32603,message:"Internal error"},[vl]:{code:-32e3,message:"Server error"}},N1=vl;function W9(t){return G9.includes(t)}function C1(t){return Object.keys(Rs).includes(t)?Rs[t]:Rs[N1]}function Z9(t){const e=Object.values(Rs).find(n=>n.code===t);return e||Rs[N1]}function Y9(t,e,n){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${n} RPC url at ${e}`):t}var U1={};/*! *****************************************************************************
|
|
28
28
|
Copyright (c) Microsoft Corporation.
|
|
29
29
|
|
|
30
30
|
Permission to use, copy, modify, and/or distribute this software for any
|
|
@@ -37,5 +37,5 @@ ${t.length}`,n=new TextEncoder().encode(e+t);return"0x"+Buffer.from(p5(n)).toStr
|
|
|
37
37
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
38
38
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
39
39
|
PERFORMANCE OF THIS SOFTWARE.
|
|
40
|
-
***************************************************************************** */var El=function(t,e){return El=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])},El(t,e)};function X9(t,e){El(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xl=function(){return xl=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},xl.apply(this,arguments)};function J9(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 Q9(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 e7(t,e){return function(n,r){e(n,r,t)}}function t7(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function n7(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 r7(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 i7(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function s7(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function _l(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 F1(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 o7(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F1(arguments[e]));return t}function a7(){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 Ps(t){return this instanceof Ps?(this.v=t,this):new Ps(t)}function c7(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(d){r[d]&&(i[d]=function(h){return new Promise(function(p,g){s.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ps?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function u7(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:Ps(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function l7(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 _l=="function"?_l(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 f7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function h7(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 d7(t){return t&&t.__esModule?t:{default:t}}function p7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function g7(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 y7=Object.freeze({__proto__:null,__extends:X9,get __assign(){return xl},__rest:J9,__decorate:Q9,__param:e7,__metadata:t7,__awaiter:n7,__generator:r7,__createBinding:i7,__exportStar:s7,__values:_l,__read:F1,__spread:o7,__spreadArrays:a7,__await:Ps,__asyncGenerator:c7,__asyncDelegator:u7,__asyncValues:l7,__makeTemplateObject:f7,__importStar:h7,__importDefault:d7,__classPrivateFieldGet:p7,__classPrivateFieldSet:g7}),b7=Gl(y7),kn={},L1;function w7(){if(L1)return kn;L1=1,Object.defineProperty(kn,"__esModule",{value:!0}),kn.isBrowserCryptoAvailable=kn.getSubtleCrypto=kn.getBrowerCrypto=void 0;function t(){return nn?.crypto||nn?.msCrypto||{}}kn.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}kn.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return kn.isBrowserCryptoAvailable=n,kn}var qn={},k1;function m7(){if(k1)return qn;k1=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function n(){return!t()&&!e()}return qn.isBrowser=n,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=b7;e.__exportStar(w7(),t),e.__exportStar(m7(),t)})(U1);function Pt(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function _r(t=6){return BigInt(Pt(t))}function Mn(t,e,n){return{id:n||Pt(),jsonrpc:"2.0",method:t,params:e}}function va(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Il(t,e,n){return{id:t,jsonrpc:"2.0",error:v7(e,n)}}function v7(t,e){return typeof t>"u"?C1(R1):(typeof t=="string"&&(t=Object.assign(Object.assign({},C1(vl)),{message:t})),typeof e<"u"&&(t.data=e),W9(t.code)&&(t=Z9(t.code)),t)}class E7{}class x7 extends E7{constructor(){super()}}class _7 extends x7{constructor(e){super()}}const I7="^wss?:";function S7(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function O7(t,e){const n=S7(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function q1(t){return O7(t,I7)}function B7(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function M1(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Sl(t){return M1(t)&&"method"in t}function Ea(t){return M1(t)&&(ln(t)||jt(t))}function ln(t){return"result"in t}function jt(t){return"error"in t}class A7 extends _7{constructor(e){super(e),this.events=new rt.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(Mn(e.method,e.params||[],e.id||_r().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=>{jt(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),Ea(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 D7=()=>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"),$7=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",j1=t=>t.split("?")[0],z1=10,T7=D7();class P7{constructor(e){if(this.url=e,this.events=new rt.exports.EventEmitter,this.registering=!1,!q1(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(qi(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!q1(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=U1.isReactNative()?void 0:{rejectUnauthorized:!B7(e)},s=new T7(e,[],i);$7()?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"?ti(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Il(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return Y9(e,j1(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>z1&&this.events.setMaxListeners(z1)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${j1(this.url)}`));return this.events.emit("register_error",n),n}}var R7=Object.defineProperty,V1=Object.getOwnPropertySymbols,N7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,K1=(t,e,n)=>e in t?R7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ft=(t,e)=>{for(var n in e||(e={}))N7.call(e,n)&&K1(t,n,e[n]);if(V1)for(var n of V1(e))C7.call(e,n)&&K1(t,n,e[n]);return t};const H1="wc",G1=2,xa="core",fn=`${H1}@2:${xa}:`,U7={name:xa,logger:"error"},F7={database:":memory:"},L7="crypto",W1="client_ed25519_seed",k7=H.ONE_DAY,q7="keychain",M7="0.3",j7="messages",z7="0.3",V7=H.SIX_HOURS,K7="publisher",Z1="irn",H7="error",Y1="wss://relay.walletconnect.org",G7="relayer",Be={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"},W7="_subscription",zt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Z7=.1,Ol="2.23.1",ve={link_mode:"link_mode",relay:"relay"},_a={inbound:"inbound",outbound:"outbound"},Y7="0.3",X7="WALLETCONNECT_CLIENT_ID",X1="WALLETCONNECT_LINK_MODE_APPS",Rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},J7="subscription",Q7="0.3",eO="pairing",tO="0.3",Rs={wc_pairingDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:H.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:H.ONE_DAY,prompt:!1,tag:0},res:{ttl:H.ONE_DAY,prompt:!1,tag:0}}},Zr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},en={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nO="history",rO="0.3",iO="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},sO="0.3",oO="verify-api",aO="https://verify.walletconnect.com",J1="https://verify.walletconnect.org",Ns=J1,cO=`${Ns}/v3`,uO=[aO,J1],lO="echo",fO="https://echo.walletconnect.com",hn={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"},jn={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"},tn={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Yr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Xr={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"},Cs={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"},hO=.1,dO="event-client",pO=86400,gO="https://pulse.walletconnect.org/batch";function yO(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var bO=yO,wO=bO;const Q1=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")},mO=t=>new TextEncoder().encode(t),vO=t=>new TextDecoder().decode(t);class EO{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 xO{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 ey(this,e)}}class _O{constructor(e){this.decoders=e}or(e){return ey(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 ey=(t,e)=>new _O(ft(ft({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class IO{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new EO(e,n,r),this.decoder=new xO(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ia=({name:t,prefix:e,encode:n,decode:r})=>new IO(t,e,n,r),Us=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=wO(n,e);return Ia({prefix:t,name:e,encode:r,decode:s=>Q1(i(s))})},SO=(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},OO=(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},ze=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ia({prefix:e,name:t,encode(i){return OO(i,r,n)},decode(i){return SO(i,r,n,t)}}),BO=Ia({prefix:"\0",name:"identity",encode:t=>vO(t),decode:t=>mO(t)});var AO=Object.freeze({__proto__:null,identity:BO});const DO=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $O=Object.freeze({__proto__:null,base2:DO});const TO=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var PO=Object.freeze({__proto__:null,base8:TO});const RO=Us({prefix:"9",name:"base10",alphabet:"0123456789"});var NO=Object.freeze({__proto__:null,base10:RO});const CO=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UO=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var FO=Object.freeze({__proto__:null,base16:CO,base16upper:UO});const LO=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),kO=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qO=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MO=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jO=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zO=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),VO=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),KO=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),HO=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var GO=Object.freeze({__proto__:null,base32:LO,base32upper:kO,base32pad:qO,base32padupper:MO,base32hex:jO,base32hexupper:zO,base32hexpad:VO,base32hexpadupper:KO,base32z:HO});const WO=Us({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ZO=Us({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var YO=Object.freeze({__proto__:null,base36:WO,base36upper:ZO});const XO=Us({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),JO=Us({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var QO=Object.freeze({__proto__:null,base58btc:XO,base58flickr:JO});const eB=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tB=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nB=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),rB=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iB=Object.freeze({__proto__:null,base64:eB,base64pad:tB,base64url:nB,base64urlpad:rB});const ty=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}"),sB=ty.reduce((t,e,n)=>(t[n]=e,t),[]),oB=ty.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function aB(t){return t.reduce((e,n)=>(e+=sB[n],e),"")}function cB(t){const e=[];for(const n of t){const r=oB[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const uB=Ia({prefix:"\u{1F680}",name:"base256emoji",encode:aB,decode:cB});var lB=Object.freeze({__proto__:null,base256emoji:uB}),fB=ry,ny=128,hB=127,dB=~hB,pB=Math.pow(2,31);function ry(t,e,n){e=e||[],n=n||0;for(var r=n;t>=pB;)e[n++]=t&255|ny,t/=128;for(;t&dB;)e[n++]=t&255|ny,t>>>=7;return e[n]=t|0,ry.bytes=n-r+1,e}var gB=Bl,yB=128,iy=127;function Bl(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Bl.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&iy)<<i:(o&iy)*Math.pow(2,i),i+=7}while(o>=yB);return Bl.bytes=s-r,n}var bB=Math.pow(2,7),wB=Math.pow(2,14),mB=Math.pow(2,21),vB=Math.pow(2,28),EB=Math.pow(2,35),xB=Math.pow(2,42),_B=Math.pow(2,49),IB=Math.pow(2,56),SB=Math.pow(2,63),OB=function(t){return t<bB?1:t<wB?2:t<mB?3:t<vB?4:t<EB?5:t<xB?6:t<_B?7:t<IB?8:t<SB?9:10},BB={encode:fB,decode:gB,encodingLength:OB},sy=BB;const oy=(t,e,n=0)=>(sy.encode(t,e,n),e),ay=t=>sy.encodingLength(t),Al=(t,e)=>{const n=e.byteLength,r=ay(t),i=r+ay(n),s=new Uint8Array(i+n);return oy(t,s,0),oy(n,s,r),s.set(e,i),new AB(t,n,e,s)};class AB{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const cy=({name:t,code:e,encode:n})=>new DB(t,e,n);class DB{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?Al(this.code,n):n.then(r=>Al(this.code,r))}else throw Error("Unknown type, must be binary type")}}const uy=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),$B=cy({name:"sha2-256",code:18,encode:uy("SHA-256")}),TB=cy({name:"sha2-512",code:19,encode:uy("SHA-512")});var PB=Object.freeze({__proto__:null,sha256:$B,sha512:TB});const ly=0,RB="identity",fy=Q1;var NB=Object.freeze({__proto__:null,identity:{code:ly,name:RB,encode:fy,digest:t=>Al(ly,fy(t))}});new TextEncoder,new TextDecoder;const hy=ft(ft(ft(ft(ft(ft(ft(ft(ft(ft({},AO),$O),PO),NO),FO),GO),YO),QO),iB),lB);ft(ft({},PB),NB);function dy(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function CB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?dy(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function py(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gy=py("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Dl=py("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=CB(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),UB=ft({utf8:gy,"utf-8":gy,hex:hy.base16,latin1:Dl,ascii:Dl,binary:Dl},hy);function FB(t,e="utf8"){const n=UB[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?dy(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var LB=Object.defineProperty,kB=(t,e,n)=>e in t?LB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>kB(t,typeof e!="symbol"?e+"":e,n);class qB{constructor(e,n){this.core=e,this.logger=n,dn(this,"keychain",new Map),dn(this,"name",q7),dn(this,"version",M7),dn(this,"initialized",!1),dn(this,"storagePrefix",fn),dn(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),dn(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),dn(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),dn(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=G("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),dn(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MB=Object.defineProperty,jB=(t,e,n)=>e in t?MB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fe=(t,e,n)=>jB(t,typeof e!="symbol"?e+"":e,n);class zB{constructor(e,n,r){this.core=e,this.logger=n,Fe(this,"name",L7),Fe(this,"keychain"),Fe(this,"randomSessionIdentifier",pl()),Fe(this,"initialized",!1),Fe(this,"clientId"),Fe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Fe(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Fe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=Rh(i),o=Ph(s.publicKey);return this.clientId=o,o}),Fe(this,"generateKeyPair",()=>{this.isInitialized();const i=IS();return this.setPrivateKey(i.publicKey,i.privateKey)}),Fe(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Rh(s),a=this.randomSessionIdentifier;return await hE(a,i,k7,o)}),Fe(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=SS(a,s);return this.setSymKey(c,o)}),Fe(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ba(i);return await this.keychain.set(o,i),o}),Fe(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"encode",async(i,s,o)=>{this.isInitialized();const a=h1(o),c=qi(s);if(p1(a))return AS(c,o?.encoding);if(d1(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;i=await this.generateSharedKey(d,h)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return OS({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Fe(this,"decode",async(i,s,o)=>{this.isInitialized();const a=$S(s,o);if(p1(a)){const c=DS(s,o?.encoding);return ti(c)}if(d1(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=BS({symKey:c,encoded:s,encoding:o?.encoding});return ti(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Fe(this,"getPayloadType",(i,s=xt)=>{const o=Bs({encoded:i,encoding:s});return Wr(o.type)}),Fe(this,"getPayloadSenderPublicKey",(i,s=xt)=>{const o=Bs({encoded:i,encoding:s});return o.senderPublicKey?mt(o.senderPublicKey,lt):void 0}),this.core=e,this.logger=Ot(n,this.name),this.keychain=r||new qB(this.core,this.logger)}get context(){return dt(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(W1)}catch{e=pl(),await this.keychain.set(W1,e)}return FB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var VB=Object.defineProperty,KB=Object.defineProperties,HB=Object.getOwnPropertyDescriptors,yy=Object.getOwnPropertySymbols,GB=Object.prototype.hasOwnProperty,WB=Object.prototype.propertyIsEnumerable,$l=(t,e,n)=>e in t?VB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ZB=(t,e)=>{for(var n in e||(e={}))GB.call(e,n)&&$l(t,n,e[n]);if(yy)for(var n of yy(e))WB.call(e,n)&&$l(t,n,e[n]);return t},YB=(t,e)=>KB(t,HB(e)),Nt=(t,e,n)=>$l(t,typeof e!="symbol"?e+"":e,n);class XB extends fm{constructor(e,n){super(e,n),this.logger=e,this.core=n,Nt(this,"messages",new Map),Nt(this,"messagesWithoutClientAck",new Map),Nt(this,"name",j7),Nt(this,"version",z7),Nt(this,"initialized",!1),Nt(this,"storagePrefix",fn),Nt(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}}}),Nt(this,"set",async(r,i,s)=>{this.isInitialized();const o=Mt(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===_a.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,YB(ZB({},c),{[o]:i}))}return await this.persist(),o}),Nt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),Nt(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}),Nt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Mt(i);return typeof s[o]<"u"}),Nt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Mt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),Nt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ot(e,this.name),this.core=n}get context(){return dt(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,Cu(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Cu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JB=Object.defineProperty,QB=Object.defineProperties,eA=Object.getOwnPropertyDescriptors,by=Object.getOwnPropertySymbols,tA=Object.prototype.hasOwnProperty,nA=Object.prototype.propertyIsEnumerable,Tl=(t,e,n)=>e in t?JB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ri=(t,e)=>{for(var n in e||(e={}))tA.call(e,n)&&Tl(t,n,e[n]);if(by)for(var n of by(e))nA.call(e,n)&&Tl(t,n,e[n]);return t},wy=(t,e)=>QB(t,eA(e)),Kt=(t,e,n)=>Tl(t,typeof e!="symbol"?e+"":e,n);class rA extends hm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Kt(this,"events",new rt.exports.EventEmitter),Kt(this,"name",K7),Kt(this,"queue",new Map),Kt(this,"publishTimeout",H.toMiliseconds(H.ONE_MINUTE)),Kt(this,"initialPublishTimeout",H.toMiliseconds(H.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(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||V7,d=s?.prompt||!1,h=s?.tag||0,p=s?.id||_r().toString(),g=$i(wa().protocol),m={id:p,method:s?.publishMethod||g.publish,params:Ri({topic:r,message:i,ttl:f,prompt:d,tag:h,attestation:s?.attestation},s?.tvf)},B=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{Re((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Re((c=m.params)==null?void 0:c.tag)&&((u=m.params)==null||delete u.tag);const $=new Promise(async x=>{const _=({id:P})=>{var C;((C=m.id)==null?void 0:C.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Be.publish,_),x())};this.relayer.events.on(Be.publish,_);const T=cn(new Promise((P,C)=>{this.rpcPublish(m,s).then(P).catch(U=>{this.logger.warn(U,U?.message),C(U)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await T,this.events.removeListener(Be.publish,_)}catch(P){this.queue.set(p,{request:m,opts:s,attempt:1}),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await cn($,this.publishTimeout,B)}catch($){if(this.logger.debug("Failed to Publish Payload"),this.logger.error($),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw $}finally{this.queue.delete(p)}}),Kt(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:d,publishMethod:h,prompt:p,tag:g,ttl:m=H.FIVE_MINUTES}=l,B=l.id||_r().toString(),$=$i(wa().protocol),x=h||$.publish,_={id:B,method:x,params:Ri(wy(Ri({},u),{ttl:m,prompt:p,tag:g,attestation:f}),d)},T=`Failed to publish custom payload, please try again. id:${B} tag:${g}`;try{Re((i=_.params)==null?void 0:i.prompt)&&((s=_.params)==null||delete s.prompt),Re((o=_.params)==null?void 0:o.tag)&&((a=_.params)==null||delete a.tag);const P=new Promise(async C=>{const U=({id:j})=>{var M;((M=_.id)==null?void 0:M.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(Be.publish,U),C())};this.relayer.events.on(Be.publish,U);const D=cn(new Promise((j,M)=>{this.rpcPublish(_,l).then(j).catch(E=>{this.logger.warn(E,E?.message),M(E)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${x} id:${B} tag:${g}`);try{await D,this.events.removeListener(Be.publish,U)}catch(j){this.queue.set(B,{request:_,opts:l,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:B,payload:u,opts:l}}),await cn(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(B)}}),Kt(this,"on",(r,i)=>{this.events.on(r,i)}),Kt(this,"once",(r,i)=>{this.events.once(r,i)}),Kt(this,"off",(r,i)=>{this.events.off(r,i)}),Kt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ot(n,this.name),this.registerEventListeners()}get context(){return dt(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(Be.publish,Ri(Ri({},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,wy(Ri({},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(Br.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Be.connection_stalled);return}this.checkQueue()}),this.relayer.on(Be.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var iA=Object.defineProperty,sA=(t,e,n)=>e in t?iA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ni=(t,e,n)=>sA(t,typeof e!="symbol"?e+"":e,n);class oA{constructor(){Ni(this,"map",new Map),Ni(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Ni(this,"get",e=>this.map.get(e)||[]),Ni(this,"exists",(e,n)=>this.get(e).includes(n)),Ni(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)}),Ni(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var aA=Object.defineProperty,cA=Object.defineProperties,uA=Object.getOwnPropertyDescriptors,my=Object.getOwnPropertySymbols,lA=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,Pl=(t,e,n)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fs=(t,e)=>{for(var n in e||(e={}))lA.call(e,n)&&Pl(t,n,e[n]);if(my)for(var n of my(e))fA.call(e,n)&&Pl(t,n,e[n]);return t},Rl=(t,e)=>cA(t,uA(e)),be=(t,e,n)=>Pl(t,typeof e!="symbol"?e+"":e,n);class hA extends gm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,be(this,"subscriptions",new Map),be(this,"topicMap",new oA),be(this,"events",new rt.exports.EventEmitter),be(this,"name",J7),be(this,"version",Q7),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",fn),be(this,"subscribeTimeout",H.toMiliseconds(H.ONE_MINUTE)),be(this,"initialSubscribeTimeout",H.toMiliseconds(H.ONE_SECOND*15)),be(this,"clientId"),be(this,"batchSubscribeTopicsLimit",500),be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),be(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=wa(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}}),be(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),be(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),be(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),be(this,"on",(r,i)=>{this.events.on(r,i)}),be(this,"once",(r,i)=>{this.events.once(r,i)}),be(this,"off",(r,i)=>{this.events.off(r,i)}),be(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),be(this,"start",async()=>{await this.onConnect()}),be(this,"stop",async()=>{await this.onDisconnect()}),be(this,"restart",async()=>{await this.restore(),await this.onRestart()}),be(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)}),be(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Br.pulse,async()=>{await this.checkPending()}),this.events.on(Rt.created,async r=>{const i=Rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Rt.deleted,async r=>{const i=Rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ot(n,this.name),this.clientId=""}get context(){return dt(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=wa(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=xe("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===ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:$i(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===ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},H.toMiliseconds(H.ONE_SECOND)),o;const u=new Promise(async f=>{const d=h=>{h.topic===e&&(this.events.removeListener(Rt.created,d),f(h.id))};this.events.on(Rt.created,d);try{const h=await cn(new Promise((p,g)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m?.message),g(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Rt.created,d),f(h)}catch{}}),l=await cn(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(Be.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:$i(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 cn(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(Be.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:$i(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 cn(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(Be.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:$i(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,Rl(Fs({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Fs({},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,Fs({},n)),this.topicMap.set(n.topic,e),this.events.emit(Rt.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}=G("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(Rt.deleted,Rl(Fs({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Rt.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(Rt.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}=G("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=>Rl(Fs({},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 V_(H.toMiliseconds(H.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}=G("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 Mt(e+await this.getClientId())}}var dA=Object.defineProperty,vy=Object.getOwnPropertySymbols,pA=Object.prototype.hasOwnProperty,gA=Object.prototype.propertyIsEnumerable,Nl=(t,e,n)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ey=(t,e)=>{for(var n in e||(e={}))pA.call(e,n)&&Nl(t,n,e[n]);if(vy)for(var n of vy(e))gA.call(e,n)&&Nl(t,n,e[n]);return t},ue=(t,e,n)=>Nl(t,typeof e!="symbol"?e+"":e,n);class yA extends dm{constructor(e){var n;super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new rt.exports.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",G7),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",H.toMiliseconds(H.THIRTY_SECONDS+H.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",H.toMiliseconds(H.ONE_SECOND*15)),ue(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||_r().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ue(this,"resetPingTimeout",()=>{Yo()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Be.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Be.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ue(this,"registerProviderListeners",()=>{this.provider.on(zt.payload,this.onPayloadHandler),this.provider.on(zt.connect,this.onConnectHandler),this.provider.on(zt.disconnect,this.onDisconnectHandler),this.provider.on(zt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=P1({logger:(n=e.logger)!=null?n:H7,name:this.name}),this.messages=new XB(this.logger,e.core),this.subscriber=new hA(this,this.logger),this.publisher=new rA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Y1,A_()?this.packageName=N0():D_()&&(this.bundleId=N0()),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 dt(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:ve.relay},_a.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(Rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Rt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,Ey({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||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 cn(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 T1())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=Te(H.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(Be.message,e),await this.recordMessageEvent(e,_a.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(zt.disconnect,s),await cn(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(zt.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(zt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zt.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,H.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Yo())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 A7(new P7(N_({sdkVersion:Ol,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}),Sl(e)){if(!e.method.endsWith(W7))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ey({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ea(e)&&this.events.emit(Be.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_a.inbound),this.events.emit(Be.message,e))}async acknowledgePayload(e){const n=va(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zt.payload,this.onPayloadHandler),this.provider.off(zt.connect,this.onConnectHandler),this.provider.off(zt.disconnect,this.onDisconnectHandler),this.provider.off(zt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await T1();T9(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(Br.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&N9())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Be.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},H.toMiliseconds(Z7)))))}isInitialized(){if(!this.initialized){const{message:e}=G("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 bA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function xy(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function _y(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const wA="[object RegExp]",mA="[object String]",vA="[object Number]",EA="[object Boolean]",Iy="[object Arguments]",xA="[object Symbol]",_A="[object Date]",IA="[object Map]",SA="[object Set]",OA="[object Array]",BA="[object Function]",AA="[object ArrayBuffer]",Cl="[object Object]",DA="[object Error]",$A="[object DataView]",TA="[object Uint8Array]",PA="[object Uint8ClampedArray]",RA="[object Uint16Array]",NA="[object Uint32Array]",CA="[object BigUint64Array]",UA="[object Int8Array]",FA="[object Int16Array]",LA="[object Int32Array]",kA="[object BigInt64Array]",qA="[object Float32Array]",MA="[object Float64Array]";function jA(){}function Sy(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 zA(t,e,n){return Ls(t,e,void 0,void 0,void 0,void 0,n)}function Ls(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 ks(t,e,s,o)}return ks(t,e,s,o)}function ks(t,e,n,r){if(Object.is(t,e))return!0;let i=_y(t),s=_y(e);if(i===Iy&&(i=Cl),s===Iy&&(s=Cl),i!==s)return!1;switch(i){case mA:return t.toString()===e.toString();case vA:{const c=t.valueOf(),u=e.valueOf();return bA(c,u)}case EA:case _A:case xA:return Object.is(t.valueOf(),e.valueOf());case wA:return t.source===e.source&&t.flags===e.flags;case BA: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 IA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!Ls(u,e.get(c),c,t,e,n,r))return!1;return!0}case SA:{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],d=u.findIndex(h=>Ls(f,h,void 0,t,e,n,r));if(d===-1)return!1;u.splice(d,1)}return!0}case OA:case TA:case PA:case RA:case NA:case CA:case UA:case FA:case LA:case kA:case qA:case MA:{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(!Ls(t[c],e[c],c,t,e,n,r))return!1;return!0}case AA:return t.byteLength!==e.byteLength?!1:ks(new Uint8Array(t),new Uint8Array(e),n,r);case $A:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:ks(new Uint8Array(t),new Uint8Array(e),n,r);case DA:return t.name===e.name&&t.message===e.message;case Cl:{if(!(ks(t.constructor,e.constructor,n,r)||Sy(t)&&Sy(e)))return!1;const c=[...Object.keys(t),...xy(t)],u=[...Object.keys(e),...xy(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],d=t[f];if(!Object.hasOwn(e,f))return!1;const h=e[f];if(!Ls(d,h,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function VA(t,e){return zA(t,e,jA)}var KA=Object.defineProperty,Oy=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,GA=Object.prototype.propertyIsEnumerable,Ul=(t,e,n)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,By=(t,e)=>{for(var n in e||(e={}))HA.call(e,n)&&Ul(t,n,e[n]);if(Oy)for(var n of Oy(e))GA.call(e,n)&&Ul(t,n,e[n]);return t},It=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);class Jr extends pm{constructor(e,n,r,i=fn,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,It(this,"map",new Map),It(this,"version",Y7),It(this,"cached",[]),It(this,"initialized",!1),It(this,"getKey"),It(this,"storagePrefix",fn),It(this,"recentlyDeleted",[]),It(this,"recentlyDeletedLimit",200),It(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):c9(o)?this.map.set(o.id,o):u9(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),It(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())}),It(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),It(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>VA(a[c],o[c]))):this.values)),It(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=By(By({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),It(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=Ot(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return dt(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}=G("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=G("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}=G("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}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WA=Object.defineProperty,ZA=(t,e,n)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e,n)=>ZA(t,typeof e!="symbol"?e+"":e,n);class YA{constructor(e,n){this.core=e,this.logger=n,se(this,"name",eO),se(this,"version",tO),se(this,"events",new rt.exports),se(this,"pairings"),se(this,"initialized",!1),se(this,"storagePrefix",fn),se(this,"ignoredPayloadTypes",[Ln]),se(this,"registeredMethods",[]),se(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),se(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),se(this,"create",async r=>{this.isInitialized();const i=pl(),s=await this.core.crypto.setSymKey(i),o=Te(H.FIVE_MINUTES),a={protocol:Z1},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=w1({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Zr.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}}),se(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[hn.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=b1(r.uri);i.props.properties.topic=s,i.addTrace(hn.pairing_uri_validation_success),i.addTrace(hn.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(hn.existing_pairing),l.active)throw i.setError(jn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(hn.pairing_not_expired)}const f=c||Te(H.FIVE_MINUTES),d={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,d),i.addTrace(hn.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Zr.create,d),i.addTrace(hn.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(hn.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(jn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw i.setError(jn.subscribe_pairing_topic_failure),h}return i.addTrace(hn.subscribe_pairing_topic_success),d}),se(this,"activate",async({topic:r})=>{this.isInitialized();const i=Te(H.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),se(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}=Mr();this.events.once(de("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),se(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),se(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),se(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),se(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",xe("USER_DISCONNECTED")),await this.deletePairing(i))}),se(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return w1({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),se(this,"sendRequest",async(r,i,s)=>{const o=Mn(i,s),a=await this.core.crypto.encode(r,o),c=Rs[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),se(this,"sendResult",async(r,i,s)=>{const o=va(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Rs[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"sendError",async(r,i,s)=>{const o=Il(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Rs[c]?Rs[c].res:Rs.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,xe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),se(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>cr(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),se(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)}}),se(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)}}),se(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Zr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{ln(i)?this.events.emit(de("pairing_ping",s),{}):jt(i)&&this.events.emit(de("pairing_ping",s),{error:i.error})},500)}),se(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Zr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=xe("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)}}),se(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(xe("WC_METHOD_UNSUPPORTED",r))}),se(this,"isValidPair",(r,i)=>{var s;if(!_t(r)){const{message:a}=G("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!a9(r.uri)){const{message:a}=G("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}const o=b1(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&H.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(jn.pairing_expired);const{message:a}=G("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),se(this,"isValidPing",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidDisconnect",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidPairingTopic",async r=>{if(!Oe(r,!1)){const{message:i}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(cr(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=G("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ot(n,this.name),this.pairings=new Jr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Be.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==ve.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Sl(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):Ea(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(Vt.expired,async e=>{const{topic:n}=L0(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Zr.expire,{topic:n}))})}}var XA=Object.defineProperty,JA=(t,e,n)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ve=(t,e,n)=>JA(t,typeof e!="symbol"?e+"":e,n);class QA extends lm{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ve(this,"records",new Map),Ve(this,"events",new rt.exports.EventEmitter),Ve(this,"name",nO),Ve(this,"version",rO),Ve(this,"cached",[]),Ve(this,"initialized",!1),Ve(this,"storagePrefix",fn),Ve(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)}),Ve(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:Te(H.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(en.created,o)}),Ve(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=jt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(en.updated,i))}),Ve(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))),Ve(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(en.deleted,s)}}),this.persist()}),Ve(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ve(this,"on",(r,i)=>{this.events.on(r,i)}),Ve(this,"once",(r,i)=>{this.events.once(r,i)}),Ve(this,"off",(r,i)=>{this.events.off(r,i)}),Ve(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(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:Mn(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}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(en.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=G("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(en.created,e=>{const n=en.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.updated,e=>{const n=en.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.deleted,e=>{const n=en.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Br.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{H.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(en.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var eD=Object.defineProperty,tD=(t,e,n)=>e in t?eD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nt=(t,e,n)=>tD(t,typeof e!="symbol"?e+"":e,n);class nD extends ym{constructor(e,n){super(e,n),this.core=e,this.logger=n,nt(this,"expirations",new Map),nt(this,"events",new rt.exports.EventEmitter),nt(this,"name",iO),nt(this,"version",sO),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",fn),nt(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)}),nt(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),nt(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(Vt.created,{target:s,expiration:o})}),nt(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),nt(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(Vt.deleted,{target:i,expiration:s})}}),nt(this,"on",(r,i)=>{this.events.on(r,i)}),nt(this,"once",(r,i)=>{this.events.once(r,i)}),nt(this,"off",(r,i)=>{this.events.off(r,i)}),nt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(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 C_(e);if(typeof e=="number")return U_(e);const{message:n}=G("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(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=G("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}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;H.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Br.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const n=Vt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const n=Vt.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const n=Vt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rD=Object.defineProperty,iD=(t,e,n)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>iD(t,typeof e!="symbol"?e+"":e,n);class sD extends bm{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Ae(this,"name",oO),Ae(this,"abortController"),Ae(this,"isDevEnv"),Ae(this,"verifyUrlV3",cO),Ae(this,"storagePrefix",fn),Ae(this,"version",G1),Ae(this,"publicKey"),Ae(this,"fetchPromise"),Ae(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&H.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ae(this,"register",async i=>{if(!xi()||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=Pr(),l=this.startAbortTimer(H.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",m),u.body.removeChild(g),h("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 m=B=>{if(B.data&&typeof B.data=="string")try{const $=JSON.parse(B.data);if($.type==="verify_attestation"){if(yc($.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",m),d($.attestation===null?"":$.attestation)}}catch($){this.logger.warn($)}};u.body.appendChild(g),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Ae(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(yc(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)}),Ae(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(H.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}),Ae(this,"getVerifyUrl",i=>{let s=i||Ns;return uO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Ns}`),s=Ns),s}),Ae(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(H.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)}}),Ae(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ae(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ae(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")}}),Ae(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ae(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}),Ae(this,"validateAttestation",(i,s)=>{const o=PS(i,s.publicKey),a={hasExpired:H.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=Ot(n,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return dt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),H.toMiliseconds(e))}}var oD=Object.defineProperty,aD=(t,e,n)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ay=(t,e,n)=>aD(t,typeof e!="symbol"?e+"":e,n);class cD extends wm{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,Ay(this,"context",lO),Ay(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${fO}/${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=Ot(n,this.context)}}var uD=Object.defineProperty,Dy=Object.getOwnPropertySymbols,lD=Object.prototype.hasOwnProperty,fD=Object.prototype.propertyIsEnumerable,Fl=(t,e,n)=>e in t?uD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,qs=(t,e)=>{for(var n in e||(e={}))lD.call(e,n)&&Fl(t,n,e[n]);if(Dy)for(var n of Dy(e))fD.call(e,n)&&Fl(t,n,e[n]);return t},Le=(t,e,n)=>Fl(t,typeof e!="symbol"?e+"":e,n);class hD extends mm{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,Le(this,"context",dO),Le(this,"storagePrefix",fn),Le(this,"storageVersion",hO),Le(this,"events",new Map),Le(this,"shouldPersist",!1),Le(this,"init",async()=>{if(!Fu())try{const i={eventId:q0(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:U0(this.core.relayer.protocol,this.core.relayer.version,Ol)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),Le(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=q0(),l=this.core.projectId||"",f=Date.now(),d=qs({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,d),this.shouldPersist=!0),d}),Le(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 qs(qs({},a),this.setMethods(a.eventId))}),Le(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),Le(this,"setEventListeners",()=>{this.core.heartbeat.on(Br.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{H.fromMiliseconds(Date.now())-H.fromMiliseconds(i.timestamp)>pO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),Le(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),Le(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)}),Le(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)}),Le(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Le(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,qs(qs({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),Le(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)}}),Le(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${gO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ol}${s}`,{method:"POST",body:JSON.stringify(i)})}),Le(this,"getAppDomain",()=>C0().url),this.logger=Ot(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 dD=Object.defineProperty,$y=Object.getOwnPropertySymbols,pD=Object.prototype.hasOwnProperty,gD=Object.prototype.propertyIsEnumerable,Ll=(t,e,n)=>e in t?dD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ty=(t,e)=>{for(var n in e||(e={}))pD.call(e,n)&&Ll(t,n,e[n]);if($y)for(var n of $y(e))gD.call(e,n)&&Ll(t,n,e[n]);return t},me=(t,e,n)=>Ll(t,typeof e!="symbol"?e+"":e,n);class kl extends om{constructor(e){var n;super(e),me(this,"protocol",H1),me(this,"version",G1),me(this,"name",xa),me(this,"relayUrl"),me(this,"projectId"),me(this,"customStoragePrefix"),me(this,"events",new rt.exports.EventEmitter),me(this,"logger"),me(this,"heartbeat"),me(this,"relayer"),me(this,"crypto"),me(this,"storage"),me(this,"history"),me(this,"expirer"),me(this,"pairing"),me(this,"verify"),me(this,"echoClient"),me(this,"linkModeSupportedApps"),me(this,"eventClient"),me(this,"initialized",!1),me(this,"logChunkController"),me(this,"on",(a,c)=>this.events.on(a,c)),me(this,"once",(a,c)=>this.events.once(a,c)),me(this,"off",(a,c)=>this.events.off(a,c)),me(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),me(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ve.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||Y1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Qw({level:typeof e?.logger=="string"&&e.logger?e.logger:U7.logger,name:xa}),{logger:s,chunkLoggerController:o}=Ff({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=Ot(s,this.name),this.heartbeat=new qa,this.crypto=new zB(this,this.logger,e?.keychain),this.history=new QA(this,this.logger),this.expirer=new nD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new dw(Ty(Ty({},F7),e?.storageOptions)),this.relayer=new yA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new YA(this,this.logger),this.verify=new sD(this,this.logger,this.storage),this.echoClient=new cD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new hD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new kl(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(X7,r),n}get context(){return dt(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(X1,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(X1)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){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 yD=kl,Py="wc",Ry=2,Ny="client",ql=`${Py}@${Ry}:${Ny}:`,Ml={name:Ny,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Cy="WALLETCONNECT_DEEPLINK_CHOICE",bD="proposal",Uy="Proposal expired",wD="session",Ci=H.SEVEN_DAYS,mD="engine",Ke={wc_sessionPropose:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1104},res:{ttl:H.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1106},res:{ttl:H.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1112},res:{ttl:H.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1114},res:{ttl:H.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:H.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:H.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1119}}},jl={min:H.FIVE_MINUTES,max:H.SEVEN_DAYS},pn={idle:"IDLE",active:"ACTIVE"},vD={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:""}},ED="request",xD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_D="wc",ID="auth",SD="authKeys",OD="pairingTopics",BD="requests",Sa=`${_D}@${1.5}:${ID}:`,Oa=`${Sa}:PUB_KEY`;var AD=Object.defineProperty,DD=Object.defineProperties,$D=Object.getOwnPropertyDescriptors,Fy=Object.getOwnPropertySymbols,TD=Object.prototype.hasOwnProperty,PD=Object.prototype.propertyIsEnumerable,zl=(t,e,n)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fe=(t,e)=>{for(var n in e||(e={}))TD.call(e,n)&&zl(t,n,e[n]);if(Fy)for(var n of Fy(e))PD.call(e,n)&&zl(t,n,e[n]);return t},He=(t,e)=>DD(t,$D(e)),V=(t,e,n)=>zl(t,typeof e!="symbol"?e+"":e,n);class RD extends _m{constructor(e){super(e),V(this,"name",mD),V(this,"events",new rt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:pn.idle,queue:[]}),V(this,"sessionRequestQueue",{state:pn.idle,queue:[]}),V(this,"emittedSessionRequests",new K_({limit:500})),V(this,"requestQueueDelay",H.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(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(Ke)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=He(fe({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=n9(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:f,walletPay:d}=i,h=((r=f?.[0])==null?void 0:r.ttl)||Ke.wc_sessionPropose.req.ttl||H.FIVE_MINUTES;this.validateRequestExpiry(h);let p=s,g,m=!1;try{if(p){const D=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),D}if(!p||!m){const{topic:D,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=D,g=j}if(!p){const{message:D}=G("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(D)}const B=await this.client.core.crypto.generateKeyPair(),$=Te(h),x=fe(He(fe(fe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Z1}],proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:$,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Pt()}),(f||d)&&{requests:{authentication:f?.map(D=>{const{domain:j,chains:M,nonce:E,uri:b,exp:v,nbf:y,type:w,statement:I,requestId:O,resources:S,signatureTypes:A}=D;return{domain:j,chains:M,nonce:E,type:w??"caip122",aud:b,version:"1",iat:new Date().toISOString(),exp:v,nbf:y,statement:I,requestId:O,resources:S,signatureTypes:A}}),walletPay:d}}),_=de("session_connect",x.id),{reject:T,resolve:P,done:C}=Mr(h,Uy),U=({id:D})=>{D===x.id&&(this.client.events.off("proposal_expire",U),this.pendingSessions.delete(x.id),this.events.emit(_,{error:{message:Uy,code:0}}))};return this.client.events.on("proposal_expire",U),this.events.once(_,({error:D,session:j})=>{this.client.events.off("proposal_expire",U),D?T(D):j&&P(j)}),await this.setProposal(x.id,x),await this.sendProposeSession({proposal:x,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:x.id}}}).catch(D=>{throw this.deleteProposal(x.id),D}),{uri:g,approval:C}}),V(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}}),V(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:[tn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Yr.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Yr.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Yr.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:B,optionalNamespaces:$}=p;let x=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});x||(x=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:tn.session_approve_started,properties:{topic:g,trace:[tn.session_approve_started,tn.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),T=m.publicKey,P=await this.client.core.crypto.generateSharedKey(_,T),C=He(fe(fe(fe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:_,metadata:this.client.metadata},expiry:Te(Ci)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),U=ve.relay;x.addTrace(tn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:U,internal:{skipSubscribe:!0}})}catch(j){throw x.setError(Yr.subscribe_session_topic_failure),j}x.addTrace(tn.subscribe_session_topic_success);const D=He(fe({},C),{topic:P,requiredNamespaces:B,optionalNamespaces:$,pairingTopic:g,acknowledged:!1,self:C.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:_,transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(P,D),x.addTrace(tn.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:fe({correlationId:a},this.getTVFApproveParams(D))}}),x.addTrace(tn.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(P,xe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),j}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,Te(Ci)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(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:Ke.wc_sessionPropose.reject}),await this.deleteProposal(r)}),V(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}=Mr(H.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Pt(),u=_r().toString(),l=this.client.session.get(r).namespaces;return this.events.once(de("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}}),V(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=Pt(),{done:s,resolve:o,reject:a}=Mr(H.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(de("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Te(Ci)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:r,request:i,topic:s,expiry:o=Ke.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const c=Pt(),u=_r().toString(),{done:l,resolve:f,reject:d}=Mr(o,"Request expired. Please try again.");this.events.once(de("session_request",c),({error:m,result:B})=>{m?d(m):f(B)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(B=>d(B)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),m()}),new Promise(async m=>{var B;if(!((B=a.sessionConfig)!=null&&B.disableDeepLink)){const $=await q_(this.client.core.storage,Cy);await F_({id:c,topic:s,wcDeepLink:$})}m()}),l()]).then(m=>m[2])}),V(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[tn.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw s.addTrace(f?.message),s.setError(Yr.session_request_response_validation_failure),f}s.addTrace(tn.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,u=this.client.session.get(o);u.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(tn.session_request_response_publish_started),ln(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):jt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(n)}catch(f){throw s.addTrace(f?.message),s.setError(Yr.session_request_response_publish_failure),f}}),V(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=Pt(),s=_r().toString(),{done:o,resolve:a,reject:c}=Mr(H.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(de("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}))}),V(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=_r().toString(),a=Pt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(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:xe("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}=G("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),V(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>s9(r,n)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(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?ve.link_mode:ve.relay;o===ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:d,exp:h,nbf:p,methods:g=[],expiry:m}=n,B=[...n.resources||[]],{topic:$,uri:x}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:$,uri:x}});const _=await this.client.core.crypto.generateKeyPair(),T=ba(_);if(await Promise.all([this.client.auth.authKeys.set(Oa,{responseTopic:T,publicKey:_}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:$})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${$}`),g.length>0){const{namespace:S}=Pn(a[0]);let A=rI(S,"request",g);sa(B)&&(A=sI(A,B.pop())),B.push(A)}const P=m&&m>Ke.wc_sessionAuthenticate.req.ttl?m:Ke.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:B},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(P)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:$,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(Ke.wc_sessionPropose.req.ttl),id:Pt()},{done:j,resolve:M,reject:E}=Mr(P,"Request expired"),b=Pt(),v=de("session_connect",D.id),y=de("session_request",b),w=async({error:S,session:A})=>{this.events.off(y,I),S?E(S):A&&M({session:A})},I=async S=>{var A,R,L;if(await this.deletePendingAuthRequest(b,{message:"fulfilled",code:0}),S.error){const K=xe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===K.code?void 0:(this.events.off(v,w),E(S.error.message))}await this.deleteProposal(D.id),this.events.off(v,w);const{cacaos:F,responder:k}=S.result,N=[],q=[];for(const K of F){await hg({cacao:K,projectId:this.client.core.projectId})||(this.client.logger.error(K,"Signature verification failed"),E(xe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Z}=K,Q=sa(Z.resources),ee=[Ku(Z.iss)],ie=ia(Z.iss);if(Q){const he=gg(Q),Ee=yg(Q);N.push(...he),ee.push(...Ee)}for(const he of ee)q.push(`${he}:${ie}`)}const z=await this.client.core.crypto.generateSharedKey(_,k.publicKey);let W;N.length>0&&(W={topic:z,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:k,controller:k.publicKey,expiry:Te(Ci),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:$,namespaces:I1([...new Set(N)],[...new Set(q)]),transportType:o},await this.client.core.relayer.subscribe(z,{transportType:o}),await this.client.session.set(z,W),$&&await this.client.core.pairing.updateMetadata({topic:$,metadata:k.metadata}),W=this.client.session.get(z)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(R=k.metadata.redirect)!=null&&R.linkMode&&(L=k.metadata.redirect)!=null&&L.universal&&r&&(this.client.core.addLinkModeSupportedApp(k.metadata.redirect.universal),this.client.session.update(z,{transportType:ve.link_mode})),M({auths:F,session:W})};this.events.once(v,w),this.events.once(y,I);let O;try{if(s){const S=Mn("wc_sessionAuthenticate",C,b);this.client.core.history.set($,S);const A=await this.client.core.crypto.encode("",S,{type:Ss,encoding:xr});O=ma(r,$,A)}else await Promise.all([this.sendRequest({topic:$,method:"wc_sessionAuthenticate",params:C,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:b}),this.sendRequest({topic:$,method:"wc_sessionPropose",params:D,expiry:Ke.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch(S){throw this.events.off(v,w),this.events.off(y,I),S}return await this.setProposal(D.id,D),await this.setAuthRequest(b,{request:He(fe({},C),{verifyContext:{}}),pairingTopic:$,transportType:o}),{uri:O??x,response:j}}),V(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Xr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Cs.no_internet_connection),m}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Cs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ve.relay;a===ve.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ba(c),f={type:Ln,receiverPublicKey:c,senderPublicKey:u},d=[],h=[];for(const m of i){if(!await hg({cacao:m,projectId:this.client.core.projectId})){s.setError(Cs.invalid_cacao);const T=xe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:T,encodeOpts:f}),new Error(T.message)}s.addTrace(Xr.cacaos_verified);const{p:B}=m,$=sa(B.resources),x=[Ku(B.iss)],_=ia(B.iss);if($){const T=gg($),P=yg($);d.push(...T),x.push(...P)}for(const T of x)h.push(`${T}:${_}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Xr.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(Ci),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:I1([...new Set(d)],[...new Set(h)]),transportType:a},s.addTrace(Xr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(m){throw s.setError(Cs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Xr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Xr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Xr.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(m){throw s.setError(Cs.authenticated_session_approve_publish_failure),m}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}}),V(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===ve.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ba(o),u={type:Ln,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ke.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)}),V(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return dg(r,i)}),V(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)}),V(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)}}),V(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,xe("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(Cy).catch(u=>this.client.logger.warn(u)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pn.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===i).map(u=>this.deletePendingSessionRequest(u.id,xe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(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(Yr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,xe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),V(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=pn.idle,this.client.events.emit("session_request_expire",{id:n}))}),V(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)])}),V(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}))}),V(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Te(Ke.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),V(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=ve.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})}),V(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Te(Ke.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})}),V(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:d={}}=n,h=Mn(i,s,c);let p;const g=!!l;try{const $=g?xr:xt;p=await this.client.core.crypto.encode(r,h,{encoding:$})}catch($){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),$}let m;if(xD.includes(i)){const $=Mt(JSON.stringify(h)),x=Mt(p);m=await this.client.core.verify.register({id:x,decryptedId:$})}const B=fe(fe({},Ke[i].req),d);if(B.attestation=m,o&&(B.ttl=o),a&&(B.id=a),this.client.core.history.set(r,h),g){const $=ma(l,r,p);await global.Linking.openURL($,this.client.name)}else B.tvf=He(fe({},f),{correlationId:h.id}),u?(B.internal=He(fe({},B.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,B)):this.client.core.relayer.publish(r,p,B).catch($=>this.client.logger.error($));return h.id}),V(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=Mn("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:xt}),a=Mt(JSON.stringify(s)),c=Mt(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:He(fe({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),V(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=va(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:xt}),l=Mn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:xt});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:He(fe({},a),{publishMethod:"wc_approveSession"})})}),V(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=va(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?xr:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let d,h;try{d=await this.client.core.history.get(i,r);const p=d.request;try{h=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=ma(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=Ke[p].res;g.tvf=He(fe({},h),{correlationId:r}),o?(g.internal=He(fe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(u)}),V(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Il(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?xr:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),h}let d;try{d=await this.client.core.history.get(i,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),h}if(f){const h=ma(c,i,l);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Ke[h].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),V(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;cr(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=>{cr(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),V(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pn.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=pn.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pn.idle}),V(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}`)}}),V(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}`)}}),V(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=G("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(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)}),V(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(jn.proposal_listener_not_found)),this.isValidConnect(fe({},i.params));const l=a.expiryTimestamp||Te(Ke.wc_sessionPropose.req.ttl),f=fe({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:s,hash:Mt(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(hn.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ke.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),V(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(ln(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(jt(r)){await this.deleteProposal(s);const o=de("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})}}),V(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:d,proposalRequestsResponses:h}=r.params,p=[...this.pendingSessions.values()].find(B=>B.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),m=He(fe(fe(fe({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(de("session_connect",p.proposalId),{session:m})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;ln(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(de("session_approve",i),{})):jt(r)&&(await this.client.session.delete(n,xe("USER_DISCONNECTED")),this.events.emit(de("session_approve",i),{error:r.error}))}),V(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=$s.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:xe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fe({topic:n},i));try{$s.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw $s.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)}}),V(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=de("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_update",i),{}):jt(r)&&this.events.emit(de("session_update",i),{error:r.error})}),V(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Te(Ci)),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)}}),V(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=de("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_extend",i),{}):jt(r)&&this.events.emit(de("session_extend",i),{error:r.error})}),V(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)}}),V(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=de("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);ln(r)?this.events.emit(de("session_ping",i),{}):jt(r)&&this.events.emit(de("session_ping",i),{error:r.error})},500)}),V(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:xe("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:d}=a;try{await this.isValidRequest(fe({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Mt(JSON.stringify(Mn("wc_sessionRequest",d,f))),encryptedId:u,metadata:h.peer.metadata,transportType:l}),g={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),l===ve.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=h.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),V(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=de("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=$s.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(fe({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),$s.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(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,d=await this.getVerifyContext({attestationId:o,hash:Mt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:i,transportType:c}),c===ve.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:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:Ln,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:h,rpcOpts:Ke.wc_sessionAuthenticate.autoReject,appLink:d})}}),V(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),V(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pn.idle,this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay))}),V(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=>{this.events.emit(de("session_request",s.request.id),{error:r})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pn.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)}}),V(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=pn.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),V(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:Mn("wc_sessionPropose",He(fe({},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})}),V(this,"isValidConnect",async n=>{if(!_t(n)){const{message:u}=G("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(Re(r)||await this.isValidPairingTopic(r),!b9(c,!0)){const{message:u}=G("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(i&&!Re(i)&&As(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(s&&!Re(s)&&As(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(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)}`)}}),V(this,"validateNamespaces",(n,r)=>{const i=y9(n,"connect()",r);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async n=>{if(!_t(n))throw new Error(G("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=bl(i,"approve()");if(u)throw new Error(u.message);const l=D1(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Oe(s,!0)){const{message:f}=G("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),V(this,"isValidReject",async n=>{if(!_t(n)){const{message:s}=G("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!m9(i)){const{message:s}=G("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!B1(r)){const{message:u}=G("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=l9(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=bl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(cr(o)){const{message:u}=G("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),V(this,"isValidUpdate",async n=>{if(!_t(n)){const{message:c}=G("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=bl(i,"update()");if(o)throw new Error(o.message);const a=D1(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),V(this,"isValidRequest",async n=>{if(!_t(n)){const{message:c}=G("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(!A1(a,s)){const{message:c}=G("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!v9(i)){const{message:c}=G("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!_9(a,s,i.method)){const{message:c}=G("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),V(this,"isValidRespond",async n=>{var r;if(!_t(n)){const{message:a}=G("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!E9(s)){const{message:a}=G("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=G("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),V(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(this,"isValidEmit",async n=>{if(!_t(n)){const{message:a}=G("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(!A1(o,s)){const{message:a}=G("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!x9(i)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!I9(o,s,i.name)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(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(!Oe(i,!1))throw new Error("uri is required parameter");if(!Oe(s,!1))throw new Error("domain is required parameter");if(!Oe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Pn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Pn(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Ns,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ve.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}),V(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=G("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),V(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)}}}),V(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,d;return!n||r!==ve.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)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=k0(n,"topic")||"",i=decodeURIComponent(k0(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:ve.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var n;if(Fu()||ar()&&(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)}}}),V(this,"getTVFApproveParams",n=>{try{const r=E1(n.namespaces),i=YS(n.namespaces),s=XS(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),V(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(u,"Error getting TVF params")}return c}),V(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}),V(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=vD[s];if(s==="sui_signTransaction")return[L5(r.transactionBytes)];if(s==="near_signTransaction")return[ag(r)];if(s==="near_signTransactions")return r.map(c=>ag(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[j9({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Pi(r)?r.map(c=>cg(c)):[cg(r)];if(s==="cosmos_signDirect")return[q5(r)];if(s==="wallet_sendCalls")return M5(r);if(typeof r=="string")return[r];const a=r[o.key];if(Pi(a))return s==="solana_signAllTransactions"?a.map(c=>F5(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,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(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Be.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(Oa)?this.client.auth.authKeys.get(Oa):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===ve.link_mode?xr:xt});Sl(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Mt(r)})):Ea(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)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vt.expired,async e=>{const{topic:n,id:r}=L0(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,G("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,G("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(Zr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Zr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Oe(e,!1)){const{message:n}=G("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}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(cr(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=G("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!Oe(e,!1)){const{message:n}=G("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}=G("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(cr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=G("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=G("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Oe(e,!1)){const{message:n}=G("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=G("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!w9(e)){const{message:n}=G("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(cr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=G("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!B9(e,jl)){const{message:n}=G("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${jl.min} and ${jl.max}`);throw new Error(n)}}}class ND extends Jr{constructor(e,n){super(e,n,bD,ql),this.core=e,this.logger=n}}class CD extends Jr{constructor(e,n){super(e,n,wD,ql),this.core=e,this.logger=n}}class UD extends Jr{constructor(e,n){super(e,n,ED,ql,r=>r.id),this.core=e,this.logger=n}}class FD extends Jr{constructor(e,n){super(e,n,SD,Sa,()=>Oa),this.core=e,this.logger=n}}class LD extends Jr{constructor(e,n){super(e,n,OD,Sa),this.core=e,this.logger=n}}class kD extends Jr{constructor(e,n){super(e,n,BD,Sa,r=>r.id),this.core=e,this.logger=n}}var qD=Object.defineProperty,MD=(t,e,n)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vl=(t,e,n)=>MD(t,typeof e!="symbol"?e+"":e,n);class jD{constructor(e,n){this.core=e,this.logger=n,Vl(this,"authKeys"),Vl(this,"pairingTopics"),Vl(this,"requests"),this.authKeys=new FD(this.core,this.logger),this.pairingTopics=new LD(this.core,this.logger),this.requests=new kD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var zD=Object.defineProperty,VD=(t,e,n)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>VD(t,typeof e!="symbol"?e+"":e,n);class Kl extends xm{constructor(e){super(e),oe(this,"protocol",Py),oe(this,"version",Ry),oe(this,"name",Ml.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new rt.exports.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ml.name,this.metadata=T_(e?.metadata),this.signConfig=e?.signConfig;const n=P1({logger:e?.logger||Ml.logger,name:this.name});this.logger=n,this.core=e?.core||new yD(e),this.session=new CD(this.core,this.logger),this.proposal=new ND(this.core,this.logger),this.pendingRequest=new UD(this.core,this.logger),this.engine=new RD(this),this.auth=new jD(this.core,this.logger)}static async init(e){const n=new Kl(e);return await n.initialize(),n}get context(){return dt(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 KD=Kl;class Ly{constructor(e){this.opts=e}}class ky{constructor(e){this.client=e}}const qy=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Ds(r?.chainId))return!1;const{namespace:a}=Pn(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},HD=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!qy({supportedNamespaces:e,token:r}))},My=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};var GD=Object.defineProperty,WD=(t,e,n)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,le=(t,e,n)=>WD(t,typeof e!="symbol"?e+"":e,n);class ZD extends ky{constructor(e){var n;super(e),le(this,"signClient"),le(this,"logger"),le(this,"tokens",[]),le(this,"supportedNamespaces",cf),le(this,"paymentIntents",{}),le(this,"transactions",{}),le(this,"paymentsSendingInProgress",{}),le(this,"manualControl",{}),le(this,"init",async()=>{var r,i;this.signClient=await KD.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)||$a.database},customStoragePrefix:$a.customStoragePrefix,logger:((i=this.client.opts.loggerOptions)==null?void 0:i.signLevel)||Ta}),this.signClient.events.on("session_delete",({topic:s})=>{this.cleanup({sessionTopic:s}),this.emit("disconnected",{sessionTopic:s})});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest({payload:JSON.stringify({id:Pt(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:s.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error(s,"Failed to fetch supported namespaces/networks")}}),le(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug({tokens:i},"Setting tokens"),i.forEach(s=>{if(!qy({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:i},"Tokens set")}),le(this,"createPaymentIntent",async r=>{const{paymentIntents:i,sessionTopic:s,userId:o}=r;this.logger.debug({paymentIntents:i,userId:o},"Creating payment intent");const a=r.manualControl||!1;if(i.length===0)throw new Error("No payment intents provided");for(const d of i)if(!HD({paymentIntent:d,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(d)}`);if(this.logger.debug({paymentIntents:i,userId:o},"Payment intent validation success"),s){this.manualControl[s]=a;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:i,userId:o}),this.validateApprovedNamespacesWithPaymentIntents(s),a||await this.sendPaymentsToWallet({sessionTopic:s,userId:o});return}catch(d){this.logger.error(d),await this.disconnect({sessionTopic:s})}}const c=this.composeNamespacesFromPaymentIntents(i),{uri:u,approval:l}=await this.signClient.connect({optionalNamespaces:c});if(this.logger.debug({uri:u,userId:o},"Connected to the WalletConnect network"),!u)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:o}),new Error("Failed to connect to the WalletConnect network");const f=My(l);if(this.emit("await_approval",{approval:f,paymentIntents:i,userId:o,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:u,userId:o}),this.logger.debug({uri:u,userId:o},"Emitted qr_ready event"),a){const d=await f();this.manualControl[d.topic]=a}}),le(this,"restart",async r=>{this.logger.debug({params:r},"Restarting");const{reinit:i,sessionTopic:s,userId:o}=r||{};if(i){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(s),c=this.manualControl[a],u=this.paymentIntents[a];if(!u||!(u!=null&&u.length))throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:u,manualControl:c,userId:o,sessionTopic:a}),this.logger.debug({paymentIntents:u,userId:o},"Restarted: Created payment intent flow from the beginning")}),le(this,"connect",async r=>{const{userId:i}=r,s=!0,o=this.composeNamespacesFromTokens(),{uri:a,approval:c}=await this.signClient.connect({optionalNamespaces:o});if(this.logger.debug({uri:a},"Connected to the WalletConnect network"),!a)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=My(c);this.emit("await_approval",{approval:u,manualControl:s,paymentIntents:[],userId:i}),this.logger.debug({userId:i},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:i}),this.logger.debug({uri:a,userId:i},"Emitted qr_ready event");const l=await u();return this.manualControl[l.topic]=s,l}),le(this,"emit",(r,i)=>(this.logger.debug({event:r,args:i},"Emit"),this.client.events.emit(r,i))),le(this,"on",(r,i)=>(this.logger.debug({event:r,listener:i},"On"),this.client.events.on(r,i))),le(this,"once",(r,i)=>(this.logger.debug({event:r,listener:i},"Once"),this.client.events.once(r,i))),le(this,"off",(r,i)=>(this.logger.debug({event:r,listener:i},"Off"),this.client.events.off(r,i))),le(this,"removeListener",(r,i)=>(this.logger.debug({event:r,listener:i},"Remove listener"),this.client.events.removeListener(r,i))),le(this,"prepareTransactionsFromPaymentIntents",async r=>{var i,s,o,a,c,u;const{sessionTopic:l,userId:f}=r,d=this.getSessionTopic(l),h=this.paymentIntents[d];if(!h)throw new Error("No payment intents found for session topic: "+d);const p=this.signClient.session.get(d);this.logger.debug({sessionTopic:d,userId:f},"Preparing transactions from payment intents");const g=[];for(const $ of h){const{token:x,amount:_,recipient:T}=$,{namespace:P}=Pn(x.network.chainId),C=(o=(s=(i=p.namespaces)==null?void 0:i[P])==null?void 0:s.accounts)==null?void 0:o.find(U=>U.includes(`${x.network.chainId}:`));if(!C)throw new Error(`Address not found in session for chain id: ${x.network.chainId}, approved addresses: ${(u=(c=(a=p.namespaces)==null?void 0:a[P])==null?void 0:c.accounts)==null?void 0:u.join(", ")}`);g.push({asset:`${x.network.chainId}/${x.standard.toLowerCase()}:${x.address}`,recipient:T,amount:_,sender:C})}this.logger.debug({sessionTopic:p.topic,transactions:g,userId:f},"Prepared transactions from payment intents");const m={id:Pt(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:g}};this.logger.debug({payload:m,userId:f},"Fetching wc_pos_buildTransactions");const B=await this.fetchRpcRequest({payload:JSON.stringify(m),userId:f});this.logger.debug({response:B,userId:f},"Received wc_pos_buildTransactions"),this.transactions[p.topic]=B.result.transactions,this.logger.debug({transactions:this.transactions[p.topic],userId:f},"Payment intent to transactions map set")}),le(this,"sendPaymentsToWallet",async(r={})=>{const{sessionTopic:i,userId:s}=r,o=this.getSessionTopic(i);if(!o)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[o])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[o]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:o,userId:s}),await this.sendTransactionsToWallet({sessionTopic:o,userId:s})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[o]=!1,a}this.paymentsSendingInProgress[o]=!1}),le(this,"sendTransactionsToWallet",async r=>{const{sessionTopic:i,userId:s}=r,o=this.transactions[i],a=this.paymentIntents[i];if(!o||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(o.length!==a.length)throw new Error(`Mismatch between transactions (${o.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:o,sessionTopic:i,userId:s},"Sending transactions to wallet");for(let c=0;c<o.length;c++){const u=o[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_requested event");let f;try{f=await this.signClient.request({topic:i,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug({transactionId:u.id,result:f,userId:s},"Wallet responded to payment request")}catch(d){throw this.logger.error(d,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:d?.message,code:4001},paymentIntent:l,sessionTopic:i,userId:s}),d}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:f,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:u,result:f,sessionTopic:i,userId:s}),await new Promise(d=>setTimeout(d,1e3))}catch(f){this.logger.error(f,"Error while awaiting payment confirmed")}}this.manualControl[i]!==!0&&await this.disconnect({sessionTopic:i})}),le(this,"awaitPaymentConfirmed",async r=>{const{transaction:i,result:s,sessionTopic:o,userId:a}=r;try{this.logger.debug({transactionId:i.id,result:s},"Awaiting payment confirmed");const c={id:Pt(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let u=0,l;for(;!l;){if(u>=af)throw new Error(`Transaction status not found for id: ${i.id}`);u++;const f=await this.fetchRpcRequest({payload:JSON.stringify(c),userId:a});if(this.logger.debug({transactionId:i.id,response:f},"Received wc_pos_checkTransaction"),f.result.status==="CONFIRMED"){this.logger.debug({response:f,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:i,result:s,sessionTopic:o,userId:a}),l=f.result;break}else if(f.result.status==="FAILED"){this.logger.debug({response:f},"Transaction failed"),this.emit("payment_failed",{error:{message:f.result.error,code:4001},transaction:s,sessionTopic:o,userId:a}),l=f.result;break}else f.result.status==="PENDING"&&(this.logger.debug({response:f,userId:a},"Transaction pending"),await new Promise(d=>setTimeout(d,f.result.checkIn||1e3)))}}catch(c){this.logger.error(c,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:c?.message,code:4001},transaction:i,sessionTopic:o,userId:a})}}),le(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,paymentIntents:i,userId:s,manualControl:o})=>{try{this.logger.debug("On await_approval");const a=await r();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:i}),await this.onSessionConnected({session:a,userId:s,manualControl:o})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:s})}})}),le(this,"onSessionConnected",async r=>{const{session:i,userId:s,manualControl:o}=r;this.logger.debug({sessionTopic:i.topic,userId:s},"On session connected"),this.emit("connected",{session:i,userId:s}),await this.signClient.session.update(i.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:i.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:i.topic,userId:s},"Emitted connected event"),o!==!0&&await this.sendPaymentsToWallet({sessionTopic:i.topic,userId:s})}),le(this,"disconnect",async(r={})=>{try{const{sessionTopic:i}=r,s=this.getSessionTopic(i);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(i){this.logger.error(i,"Error while disconnecting")}}),le(this,"fetchRpcRequest",async r=>{var i,s,o,a,c,u;const{payload:l,userId:f}=r;this.logger.debug({url:this.getRpcUrl(),payload:l,userId:f},"Fetching RPC request");const d=await fetch(this.getRpcUrl(),{method:"POST",body:l});let h;try{h=await d.json()}catch(p){this.logger.error(p,"Error while getting json data from RPC response")}if(this.logger.debug({data:h},"Received RPC request response"),!d.ok||!h||h!=null&&h.error){const p=((i=h?.error)==null?void 0:i.code)||-18900,g=(s=Pa)!=null&&s[p]?`${(o=Pa)==null?void 0:o[p]}: ${(a=h?.error)==null?void 0:a.message}`:((c=h?.error)==null?void 0:c.message)||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:g,code:p},transaction:"",sessionTopic:((u=this.client.session)==null?void 0:u.topic)||"",userId:f}),new Error(g)}return h}),le(this,"validateApprovedNamespacesWithPaymentIntents",r=>{var i,s,o,a,c,u,l;this.validateSessionTopic(r);const f=this.signClient.session.get(r),d=(i=this.paymentIntents)==null?void 0:i[r];if(!f||!d)throw new Error("No session or payment intents found");for(const h of d){const{token:p}=h,{namespace:g}=Pn(p.network.chainId);if(!((a=(o=(s=f.namespaces)==null?void 0:s[g])==null?void 0:o.accounts)!=null&&a.find(m=>m.includes(`${p.network.chainId}:`))))throw new Error(`Address not found in session for chain id: ${p.network.chainId}, approved addresses: ${(l=(u=(c=f.namespaces)==null?void 0:c[g])==null?void 0:u.accounts)==null?void 0:l.join(", ")}`)}}),le(this,"setPaymentIntents",r=>{const{sessionTopic:i,paymentIntents:s,userId:o}=r;this.paymentIntents[i]=s,this.logger.debug({paymentIntents:s,userId:o},"Payment intents set")}),le(this,"cleanup",(r={})=>{const{sessionTopic:i}=r;i&&(delete this.paymentIntents[i],delete this.transactions[i],delete this.manualControl[i],delete this.paymentsSendingInProgress[i],this.logger.debug({sessionTopic:i},"Cleaned up payment intents and transactions"))}),le(this,"getRpcUrl",()=>uf({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId})),le(this,"validateSessionTopic",r=>{if(r)try{this.signClient.session.get(r)}catch(i){throw this.logger.error(i,`No session found for topic: ${r}`),new Error(`No session found for topic: ${r}`)}}),le(this,"getSessionTopic",r=>{var i;if(!r&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const s=r||((i=this.client.session)==null?void 0:i.topic);if(!s)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(s),s}),this.signClient={},this.logger=Pw({name:this.client.name,level:((n=this.client.opts.loggerOptions)==null?void 0:n.posLevel)||Ta}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{var i;const{network:s}=r,{namespace:o}=Pn(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({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=Pn(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({namespaces:n},"Composed namespaces"),n}}var YD=Object.defineProperty,XD=(t,e,n)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,St=(t,e,n)=>XD(t,typeof e!="symbol"?e+"":e,n);class Ba extends Ly{constructor(e){super(e),St(this,"name"),St(this,"events",new rt.exports),St(this,"engine"),St(this,"metadata"),St(this,"on",(n,r)=>this.engine.on(n,r)),St(this,"once",(n,r)=>this.engine.once(n,r)),St(this,"off",(n,r)=>this.engine.off(n,r)),St(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),St(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"sendPaymentsToWallet",async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=Da,this.engine=new ZD(this)}static async init(e){const n=new Ba(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}}const JD=Ba;Se.CLIENT_CONTEXT=Da,Se.CLIENT_STORAGE_OPTIONS=$a,Se.CLIENT_STORAGE_PREFIX=nb,Se.DEFAULT_LOGGER_LEVEL=Ta,Se.DEFAULT_NAMESPACES=cf,Se.IPOSClient=Ly,Se.IPOSClientEngine=ky,Se.MAX_TRANSACTION_STATUS_CHECKS=af,Se.POSClient=JD,Se.POS_CLIENT_VERSION=of,Se.PROTOCOL=sf,Se.PROTOCOL_VERSION=tb,Se.RPC_ERROR_CODES=Pa,Se.RPC_URL=uf,Se.default=Ba,Object.defineProperty(Se,"__esModule",{value:!0})});
|
|
40
|
+
***************************************************************************** */var El=function(t,e){return El=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])},El(t,e)};function X9(t,e){El(t,e);function n(){this.constructor=t}t.prototype=e===null?Object.create(e):(n.prototype=e.prototype,new n)}var xl=function(){return xl=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},xl.apply(this,arguments)};function J9(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 Q9(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 e7(t,e){return function(n,r){e(n,r,t)}}function t7(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function n7(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 r7(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 i7(t,e,n,r){r===void 0&&(r=n),t[r]=e[n]}function s7(t,e){for(var n in t)n!=="default"&&!e.hasOwnProperty(n)&&(e[n]=t[n])}function _l(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 F1(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 o7(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(F1(arguments[e]));return t}function a7(){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 Ns(t){return this instanceof Ns?(this.v=t,this):new Ns(t)}function c7(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(d){r[d]&&(i[d]=function(h){return new Promise(function(p,g){s.push([d,h,p,g])>1||a(d,h)})})}function a(d,h){try{c(r[d](h))}catch(p){f(s[0][3],p)}}function c(d){d.value instanceof Ns?Promise.resolve(d.value.v).then(u,l):f(s[0][2],d)}function u(d){a("next",d)}function l(d){a("throw",d)}function f(d,h){d(h),s.shift(),s.length&&a(s[0][0],s[0][1])}}function u7(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:Ns(t[i](o)),done:i==="return"}:s?s(o):o}:s}}function l7(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 _l=="function"?_l(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 f7(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function h7(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 d7(t){return t&&t.__esModule?t:{default:t}}function p7(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function g7(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 y7=Object.freeze({__proto__:null,__extends:X9,get __assign(){return xl},__rest:J9,__decorate:Q9,__param:e7,__metadata:t7,__awaiter:n7,__generator:r7,__createBinding:i7,__exportStar:s7,__values:_l,__read:F1,__spread:o7,__spreadArrays:a7,__await:Ns,__asyncGenerator:c7,__asyncDelegator:u7,__asyncValues:l7,__makeTemplateObject:f7,__importStar:h7,__importDefault:d7,__classPrivateFieldGet:p7,__classPrivateFieldSet:g7}),b7=Gl(y7),Ln={},k1;function w7(){if(k1)return Ln;k1=1,Object.defineProperty(Ln,"__esModule",{value:!0}),Ln.isBrowserCryptoAvailable=Ln.getSubtleCrypto=Ln.getBrowerCrypto=void 0;function t(){return nn?.crypto||nn?.msCrypto||{}}Ln.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Ln.getSubtleCrypto=e;function n(){return!!t()&&!!e()}return Ln.isBrowserCryptoAvailable=n,Ln}var qn={},L1;function m7(){if(L1)return qn;L1=1,Object.defineProperty(qn,"__esModule",{value:!0}),qn.isBrowser=qn.isNode=qn.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}qn.isReactNative=t;function e(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}qn.isNode=e;function n(){return!t()&&!e()}return qn.isBrowser=n,qn}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=b7;e.__exportStar(w7(),t),e.__exportStar(m7(),t)})(U1);function Pt(t=3){const e=Date.now()*Math.pow(10,t),n=Math.floor(Math.random()*Math.pow(10,t));return e+n}function Sr(t=6){return BigInt(Pt(t))}function Mn(t,e,n){return{id:n||Pt(),jsonrpc:"2.0",method:t,params:e}}function va(t,e){return{id:t,jsonrpc:"2.0",result:e}}function Il(t,e,n){return{id:t,jsonrpc:"2.0",error:v7(e,n)}}function v7(t,e){return typeof t>"u"?C1(R1):(typeof t=="string"&&(t=Object.assign(Object.assign({},C1(vl)),{message:t})),typeof e<"u"&&(t.data=e),W9(t.code)&&(t=Z9(t.code)),t)}class E7{}class x7 extends E7{constructor(){super()}}class _7 extends x7{constructor(e){super()}}const I7="^wss?:";function S7(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function O7(t,e){const n=S7(t);return typeof n>"u"?!1:new RegExp(e).test(n)}function q1(t){return O7(t,I7)}function B7(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function M1(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Sl(t){return M1(t)&&"method"in t}function Ea(t){return M1(t)&&(ln(t)||jt(t))}function ln(t){return"result"in t}function jt(t){return"error"in t}class A7 extends _7{constructor(e){super(e),this.events=new rt.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(Mn(e.method,e.params||[],e.id||Sr().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=>{jt(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),Ea(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 D7=()=>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"),$7=()=>typeof WebSocket<"u"||typeof global<"u"&&typeof global.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",j1=t=>t.split("?")[0],z1=10,T7=D7();class P7{constructor(e){if(this.url=e,this.events=new rt.exports.EventEmitter,this.registering=!1,!q1(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(ji(e))}catch(n){this.onError(e.id,n)}}register(e=this.url){if(!q1(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=U1.isReactNative()?void 0:{rejectUnauthorized:!B7(e)},s=new T7(e,[],i);$7()?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"?ri(e.data):e.data;this.events.emit("payload",n)}onError(e,n){const r=this.parseError(n),i=r.message||r.toString(),s=Il(e,i);this.events.emit("payload",s)}parseError(e,n=this.url){return Y9(e,j1(n),"WS")}resetMaxListeners(){this.events.getMaxListeners()>z1&&this.events.setMaxListeners(z1)}emitError(e){const n=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${j1(this.url)}`));return this.events.emit("register_error",n),n}}var R7=Object.defineProperty,V1=Object.getOwnPropertySymbols,N7=Object.prototype.hasOwnProperty,C7=Object.prototype.propertyIsEnumerable,K1=(t,e,n)=>e in t?R7(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ft=(t,e)=>{for(var n in e||(e={}))N7.call(e,n)&&K1(t,n,e[n]);if(V1)for(var n of V1(e))C7.call(e,n)&&K1(t,n,e[n]);return t};const H1="wc",G1=2,xa="core",fn=`${H1}@2:${xa}:`,U7={name:xa,logger:"error"},F7={database:":memory:"},k7="crypto",W1="client_ed25519_seed",L7=H.ONE_DAY,q7="keychain",M7="0.3",j7="messages",z7="0.3",V7=H.SIX_HOURS,K7="publisher",Z1="irn",H7="error",Y1="wss://relay.walletconnect.org",G7="relayer",Be={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"},W7="_subscription",zt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},Z7=.1,Ol="2.23.3",ve={link_mode:"link_mode",relay:"relay"},_a={inbound:"inbound",outbound:"outbound"},Y7="0.3",X7="WALLETCONNECT_CLIENT_ID",X1="WALLETCONNECT_LINK_MODE_APPS",Rt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},J7="subscription",Q7="0.3",eO="pairing",tO="0.3",Cs={wc_pairingDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:H.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:H.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:H.ONE_DAY,prompt:!1,tag:0},res:{ttl:H.ONE_DAY,prompt:!1,tag:0}}},Xr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},en={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},nO="history",rO="0.3",iO="expirer",Vt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},sO="0.3",oO="verify-api",aO="https://verify.walletconnect.com",J1="https://verify.walletconnect.org",Us=J1,cO=`${Us}/v3`,uO=[aO,J1],lO="echo",fO="https://echo.walletconnect.com",hn={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"},jn={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"},tn={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},Jr={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",proposal_expired:"proposal_expired",subscribe_session_topic_failure:"subscribe_session_topic_failure",session_approve_publish_failure:"session_approve_publish_failure",session_settle_publish_failure:"session_settle_publish_failure",session_approve_namespace_validation_failure:"session_approve_namespace_validation_failure",proposal_not_found:"proposal_not_found",session_request_response_validation_failure:"session_request_response_validation_failure",session_request_response_publish_failure:"session_request_response_publish_failure"},Qr={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"},Fs={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"},hO=.1,dO="event-client",pO=86400,gO="https://pulse.walletconnect.org/batch";function yO(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,m=0,B=0,$=p.length;B!==$&&p[B]===0;)B++,g++;for(var x=($-B)*l+1>>>0,_=new Uint8Array(x);B!==$;){for(var T=p[B],P=0,C=x-1;(T!==0||P<m)&&C!==-1;C--,P++)T+=256*_[C]>>>0,_[C]=T%a>>>0,T=T/a>>>0;if(T!==0)throw new Error("Non-zero carry");m=P,B++}for(var U=x-m;U!==x&&_[U]===0;)U++;for(var D=c.repeat(g);U<x;++U)D+=t.charAt(_[U]);return D}function d(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 m=0,B=0;p[g]===c;)m++,g++;for(var $=(p.length-g)*u+1>>>0,x=new Uint8Array($);p[g];){var _=n[p.charCodeAt(g)];if(_===255)return;for(var T=0,P=$-1;(_!==0||T<B)&&P!==-1;P--,T++)_+=a*x[P]>>>0,x[P]=_%256>>>0,_=_/256>>>0;if(_!==0)throw new Error("Non-zero carry");B=T,g++}if(p[g]!==" "){for(var C=$-B;C!==$&&x[C]===0;)C++;for(var U=new Uint8Array(m+($-C)),D=m;C!==$;)U[D++]=x[C++];return U}}}function h(p){var g=d(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:f,decodeUnsafe:d,decode:h}}var bO=yO,wO=bO;const Q1=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")},mO=t=>new TextEncoder().encode(t),vO=t=>new TextDecoder().decode(t);class EO{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 xO{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 ey(this,e)}}class _O{constructor(e){this.decoders=e}or(e){return ey(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 ey=(t,e)=>new _O(ft(ft({},t.decoders||{[t.prefix]:t}),e.decoders||{[e.prefix]:e}));class IO{constructor(e,n,r,i){this.name=e,this.prefix=n,this.baseEncode=r,this.baseDecode=i,this.encoder=new EO(e,n,r),this.decoder=new xO(e,n,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ia=({name:t,prefix:e,encode:n,decode:r})=>new IO(t,e,n,r),ks=({prefix:t,name:e,alphabet:n})=>{const{encode:r,decode:i}=wO(n,e);return Ia({prefix:t,name:e,encode:r,decode:s=>Q1(i(s))})},SO=(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},OO=(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},ze=({name:t,prefix:e,bitsPerChar:n,alphabet:r})=>Ia({prefix:e,name:t,encode(i){return OO(i,r,n)},decode(i){return SO(i,r,n,t)}}),BO=Ia({prefix:"\0",name:"identity",encode:t=>vO(t),decode:t=>mO(t)});var AO=Object.freeze({__proto__:null,identity:BO});const DO=ze({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var $O=Object.freeze({__proto__:null,base2:DO});const TO=ze({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var PO=Object.freeze({__proto__:null,base8:TO});const RO=ks({prefix:"9",name:"base10",alphabet:"0123456789"});var NO=Object.freeze({__proto__:null,base10:RO});const CO=ze({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),UO=ze({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var FO=Object.freeze({__proto__:null,base16:CO,base16upper:UO});const kO=ze({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),LO=ze({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qO=ze({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),MO=ze({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),jO=ze({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),zO=ze({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),VO=ze({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),KO=ze({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),HO=ze({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var GO=Object.freeze({__proto__:null,base32:kO,base32upper:LO,base32pad:qO,base32padupper:MO,base32hex:jO,base32hexupper:zO,base32hexpad:VO,base32hexpadupper:KO,base32z:HO});const WO=ks({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),ZO=ks({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var YO=Object.freeze({__proto__:null,base36:WO,base36upper:ZO});const XO=ks({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),JO=ks({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var QO=Object.freeze({__proto__:null,base58btc:XO,base58flickr:JO});const eB=ze({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tB=ze({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),nB=ze({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),rB=ze({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var iB=Object.freeze({__proto__:null,base64:eB,base64pad:tB,base64url:nB,base64urlpad:rB});const ty=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}"),sB=ty.reduce((t,e,n)=>(t[n]=e,t),[]),oB=ty.reduce((t,e,n)=>(t[e.codePointAt(0)]=n,t),[]);function aB(t){return t.reduce((e,n)=>(e+=sB[n],e),"")}function cB(t){const e=[];for(const n of t){const r=oB[n.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${n}`);e.push(r)}return new Uint8Array(e)}const uB=Ia({prefix:"\u{1F680}",name:"base256emoji",encode:aB,decode:cB});var lB=Object.freeze({__proto__:null,base256emoji:uB}),fB=ry,ny=128,hB=127,dB=~hB,pB=Math.pow(2,31);function ry(t,e,n){e=e||[],n=n||0;for(var r=n;t>=pB;)e[n++]=t&255|ny,t/=128;for(;t&dB;)e[n++]=t&255|ny,t>>>=7;return e[n]=t|0,ry.bytes=n-r+1,e}var gB=Bl,yB=128,iy=127;function Bl(t,r){var n=0,r=r||0,i=0,s=r,o,a=t.length;do{if(s>=a)throw Bl.bytes=0,new RangeError("Could not decode varint");o=t[s++],n+=i<28?(o&iy)<<i:(o&iy)*Math.pow(2,i),i+=7}while(o>=yB);return Bl.bytes=s-r,n}var bB=Math.pow(2,7),wB=Math.pow(2,14),mB=Math.pow(2,21),vB=Math.pow(2,28),EB=Math.pow(2,35),xB=Math.pow(2,42),_B=Math.pow(2,49),IB=Math.pow(2,56),SB=Math.pow(2,63),OB=function(t){return t<bB?1:t<wB?2:t<mB?3:t<vB?4:t<EB?5:t<xB?6:t<_B?7:t<IB?8:t<SB?9:10},BB={encode:fB,decode:gB,encodingLength:OB},sy=BB;const oy=(t,e,n=0)=>(sy.encode(t,e,n),e),ay=t=>sy.encodingLength(t),Al=(t,e)=>{const n=e.byteLength,r=ay(t),i=r+ay(n),s=new Uint8Array(i+n);return oy(t,s,0),oy(n,s,r),s.set(e,i),new AB(t,n,e,s)};class AB{constructor(e,n,r,i){this.code=e,this.size=n,this.digest=r,this.bytes=i}}const cy=({name:t,code:e,encode:n})=>new DB(t,e,n);class DB{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?Al(this.code,n):n.then(r=>Al(this.code,r))}else throw Error("Unknown type, must be binary type")}}const uy=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),$B=cy({name:"sha2-256",code:18,encode:uy("SHA-256")}),TB=cy({name:"sha2-512",code:19,encode:uy("SHA-512")});var PB=Object.freeze({__proto__:null,sha256:$B,sha512:TB});const ly=0,RB="identity",fy=Q1;var NB=Object.freeze({__proto__:null,identity:{code:ly,name:RB,encode:fy,digest:t=>Al(ly,fy(t))}});new TextEncoder,new TextDecoder;const hy=ft(ft(ft(ft(ft(ft(ft(ft(ft(ft({},AO),$O),PO),NO),FO),GO),YO),QO),iB),lB);ft(ft({},PB),NB);function dy(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function CB(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?dy(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function py(t,e,n,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:n},decoder:{decode:r}}}const gy=py("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Dl=py("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=CB(t.length);for(let n=0;n<t.length;n++)e[n]=t.charCodeAt(n);return e}),UB=ft({utf8:gy,"utf-8":gy,hex:hy.base16,latin1:Dl,ascii:Dl,binary:Dl},hy);function FB(t,e="utf8"){const n=UB[e];if(!n)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?dy(globalThis.Buffer.from(t,"utf-8")):n.decoder.decode(`${n.prefix}${t}`)}var kB=Object.defineProperty,LB=(t,e,n)=>e in t?kB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,dn=(t,e,n)=>LB(t,typeof e!="symbol"?e+"":e,n);class qB{constructor(e,n){this.core=e,this.logger=n,dn(this,"keychain",new Map),dn(this,"name",q7),dn(this,"version",M7),dn(this,"initialized",!1),dn(this,"storagePrefix",fn),dn(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),dn(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),dn(this,"set",async(r,i)=>{this.isInitialized(),this.keychain.set(r,i),await this.persist()}),dn(this,"get",r=>{this.isInitialized();const i=this.keychain.get(r);if(typeof i>"u"){const{message:s}=G("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return i}),dn(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=Ot(n,this.name)}get context(){return dt(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Cu(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var MB=Object.defineProperty,jB=(t,e,n)=>e in t?MB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Fe=(t,e,n)=>jB(t,typeof e!="symbol"?e+"":e,n);class zB{constructor(e,n,r){this.core=e,this.logger=n,Fe(this,"name",k7),Fe(this,"keychain"),Fe(this,"randomSessionIdentifier",pl()),Fe(this,"initialized",!1),Fe(this,"clientId"),Fe(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Fe(this,"hasKeys",i=>(this.isInitialized(),this.keychain.has(i))),Fe(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const i=await this.getClientSeed(),s=Rh(i),o=Ph(s.publicKey);return this.clientId=o,o}),Fe(this,"generateKeyPair",()=>{this.isInitialized();const i=IS();return this.setPrivateKey(i.publicKey,i.privateKey)}),Fe(this,"signJWT",async i=>{this.isInitialized();const s=await this.getClientSeed(),o=Rh(s),a=this.randomSessionIdentifier;return await hE(a,i,L7,o)}),Fe(this,"generateSharedKey",(i,s,o)=>{this.isInitialized();const a=this.getPrivateKey(i),c=SS(a,s);return this.setSymKey(c,o)}),Fe(this,"setSymKey",async(i,s)=>{this.isInitialized();const o=s||ba(i);return await this.keychain.set(o,i),o}),Fe(this,"deleteKeyPair",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"deleteSymKey",async i=>{this.isInitialized(),await this.keychain.del(i)}),Fe(this,"encode",async(i,s,o)=>{this.isInitialized();const a=h1(o),c=ji(s);if(p1(a))return AS(c,o?.encoding);if(d1(a)){const d=a.senderPublicKey,h=a.receiverPublicKey;i=await this.generateSharedKey(d,h)}const u=this.getSymKey(i),{type:l,senderPublicKey:f}=a;return OS({type:l,symKey:u,message:c,senderPublicKey:f,encoding:o?.encoding})}),Fe(this,"decode",async(i,s,o)=>{this.isInitialized();const a=$S(s,o);if(p1(a)){const c=DS(s,o?.encoding);return ri(c)}if(d1(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;i=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(i),u=BS({symKey:c,encoded:s,encoding:o?.encoding});return ri(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${i}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Fe(this,"getPayloadType",(i,s=xt)=>{const o=Ds({encoded:i,encoding:s});return Yr(o.type)}),Fe(this,"getPayloadSenderPublicKey",(i,s=xt)=>{const o=Ds({encoded:i,encoding:s});return o.senderPublicKey?mt(o.senderPublicKey,lt):void 0}),this.core=e,this.logger=Ot(n,this.name),this.keychain=r||new qB(this.core,this.logger)}get context(){return dt(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(W1)}catch{e=pl(),await this.keychain.set(W1,e)}return FB(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var VB=Object.defineProperty,KB=Object.defineProperties,HB=Object.getOwnPropertyDescriptors,yy=Object.getOwnPropertySymbols,GB=Object.prototype.hasOwnProperty,WB=Object.prototype.propertyIsEnumerable,$l=(t,e,n)=>e in t?VB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,ZB=(t,e)=>{for(var n in e||(e={}))GB.call(e,n)&&$l(t,n,e[n]);if(yy)for(var n of yy(e))WB.call(e,n)&&$l(t,n,e[n]);return t},YB=(t,e)=>KB(t,HB(e)),Nt=(t,e,n)=>$l(t,typeof e!="symbol"?e+"":e,n);class XB extends fm{constructor(e,n){super(e,n),this.logger=e,this.core=n,Nt(this,"messages",new Map),Nt(this,"messagesWithoutClientAck",new Map),Nt(this,"name",j7),Nt(this,"version",z7),Nt(this,"initialized",!1),Nt(this,"storagePrefix",fn),Nt(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}}}),Nt(this,"set",async(r,i,s)=>{this.isInitialized();const o=Mt(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===_a.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,YB(ZB({},c),{[o]:i}))}return await this.persist(),o}),Nt(this,"get",r=>{this.isInitialized();let i=this.messages.get(r);return typeof i>"u"&&(i={}),i}),Nt(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}),Nt(this,"has",(r,i)=>{this.isInitialized();const s=this.get(r),o=Mt(i);return typeof s[o]<"u"}),Nt(this,"ack",async(r,i)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=Mt(i);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),Nt(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=Ot(e,this.name),this.core=n}get context(){return dt(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,Cu(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Cu(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Uu(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Uu(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JB=Object.defineProperty,QB=Object.defineProperties,eA=Object.getOwnPropertyDescriptors,by=Object.getOwnPropertySymbols,tA=Object.prototype.hasOwnProperty,nA=Object.prototype.propertyIsEnumerable,Tl=(t,e,n)=>e in t?JB(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ci=(t,e)=>{for(var n in e||(e={}))tA.call(e,n)&&Tl(t,n,e[n]);if(by)for(var n of by(e))nA.call(e,n)&&Tl(t,n,e[n]);return t},wy=(t,e)=>QB(t,eA(e)),Kt=(t,e,n)=>Tl(t,typeof e!="symbol"?e+"":e,n);class rA extends hm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,Kt(this,"events",new rt.exports.EventEmitter),Kt(this,"name",K7),Kt(this,"queue",new Map),Kt(this,"publishTimeout",H.toMiliseconds(H.ONE_MINUTE)),Kt(this,"initialPublishTimeout",H.toMiliseconds(H.ONE_SECOND*15)),Kt(this,"needsTransportRestart",!1),Kt(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||V7,d=s?.prompt||!1,h=s?.tag||0,p=s?.id||Sr().toString(),g=Pi(wa().protocol),m={id:p,method:s?.publishMethod||g.publish,params:Ci({topic:r,message:i,ttl:f,prompt:d,tag:h,attestation:s?.attestation},s?.tvf)},B=`Failed to publish payload, please try again. id:${p} tag:${h}`;try{Re((o=m.params)==null?void 0:o.prompt)&&((a=m.params)==null||delete a.prompt),Re((c=m.params)==null?void 0:c.tag)&&((u=m.params)==null||delete u.tag);const $=new Promise(async x=>{const _=({id:P})=>{var C;((C=m.id)==null?void 0:C.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(Be.publish,_),x())};this.relayer.events.on(Be.publish,_);const T=cn(new Promise((P,C)=>{this.rpcPublish(m,s).then(P).catch(U=>{this.logger.warn(U,U?.message),C(U)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${h}`);try{await T,this.events.removeListener(Be.publish,_)}catch(P){this.queue.set(p,{request:m,opts:s,attempt:1}),this.logger.warn(P,P?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:i,opts:s}}),await cn($,this.publishTimeout,B)}catch($){if(this.logger.debug("Failed to Publish Payload"),this.logger.error($),(l=s?.internal)!=null&&l.throwOnFailedPublish)throw $}finally{this.queue.delete(p)}}),Kt(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:d,publishMethod:h,prompt:p,tag:g,ttl:m=H.FIVE_MINUTES}=l,B=l.id||Sr().toString(),$=Pi(wa().protocol),x=h||$.publish,_={id:B,method:x,params:Ci(wy(Ci({},u),{ttl:m,prompt:p,tag:g,attestation:f}),d)},T=`Failed to publish custom payload, please try again. id:${B} tag:${g}`;try{Re((i=_.params)==null?void 0:i.prompt)&&((s=_.params)==null||delete s.prompt),Re((o=_.params)==null?void 0:o.tag)&&((a=_.params)==null||delete a.tag);const P=new Promise(async C=>{const U=({id:j})=>{var M;((M=_.id)==null?void 0:M.toString())===j.toString()&&(this.removeRequestFromQueue(j),this.relayer.events.removeListener(Be.publish,U),C())};this.relayer.events.on(Be.publish,U);const D=cn(new Promise((j,M)=>{this.rpcPublish(_,l).then(j).catch(E=>{this.logger.warn(E,E?.message),M(E)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${x} id:${B} tag:${g}`);try{await D,this.events.removeListener(Be.publish,U)}catch(j){this.queue.set(B,{request:_,opts:l,attempt:1}),this.logger.warn(j,j?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:B,payload:u,opts:l}}),await cn(P,this.publishTimeout,T)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(B)}}),Kt(this,"on",(r,i)=>{this.events.on(r,i)}),Kt(this,"once",(r,i)=>{this.events.once(r,i)}),Kt(this,"off",(r,i)=>{this.events.off(r,i)}),Kt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.relayer=e,this.logger=Ot(n,this.name),this.registerEventListeners()}get context(){return dt(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(Be.publish,Ci(Ci({},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,wy(Ci({},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(Dr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(Be.connection_stalled);return}this.checkQueue()}),this.relayer.on(Be.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var iA=Object.defineProperty,sA=(t,e,n)=>e in t?iA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ui=(t,e,n)=>sA(t,typeof e!="symbol"?e+"":e,n);class oA{constructor(){Ui(this,"map",new Map),Ui(this,"set",(e,n)=>{const r=this.get(e);this.exists(e,n)||this.map.set(e,[...r,n])}),Ui(this,"get",e=>this.map.get(e)||[]),Ui(this,"exists",(e,n)=>this.get(e).includes(n)),Ui(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)}),Ui(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var aA=Object.defineProperty,cA=Object.defineProperties,uA=Object.getOwnPropertyDescriptors,my=Object.getOwnPropertySymbols,lA=Object.prototype.hasOwnProperty,fA=Object.prototype.propertyIsEnumerable,Pl=(t,e,n)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ls=(t,e)=>{for(var n in e||(e={}))lA.call(e,n)&&Pl(t,n,e[n]);if(my)for(var n of my(e))fA.call(e,n)&&Pl(t,n,e[n]);return t},Rl=(t,e)=>cA(t,uA(e)),be=(t,e,n)=>Pl(t,typeof e!="symbol"?e+"":e,n);class hA extends gm{constructor(e,n){super(e,n),this.relayer=e,this.logger=n,be(this,"subscriptions",new Map),be(this,"topicMap",new oA),be(this,"events",new rt.exports.EventEmitter),be(this,"name",J7),be(this,"version",Q7),be(this,"pending",new Map),be(this,"cached",[]),be(this,"initialized",!1),be(this,"storagePrefix",fn),be(this,"subscribeTimeout",H.toMiliseconds(H.ONE_MINUTE)),be(this,"initialSubscribeTimeout",H.toMiliseconds(H.ONE_SECOND*15)),be(this,"clientId"),be(this,"batchSubscribeTopicsLimit",500),be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),be(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=wa(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}}),be(this,"unsubscribe",async(r,i)=>{this.isInitialized(),typeof i?.id<"u"?await this.unsubscribeById(r,i.id,i):await this.unsubscribeByTopic(r,i)}),be(this,"isSubscribed",r=>new Promise(i=>{i(this.topicMap.topics.includes(r))})),be(this,"isKnownTopic",r=>new Promise(i=>{i(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),be(this,"on",(r,i)=>{this.events.on(r,i)}),be(this,"once",(r,i)=>{this.events.once(r,i)}),be(this,"off",(r,i)=>{this.events.off(r,i)}),be(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),be(this,"start",async()=>{await this.onConnect()}),be(this,"stop",async()=>{await this.onDisconnect()}),be(this,"restart",async()=>{await this.restore(),await this.onRestart()}),be(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)}),be(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Dr.pulse,async()=>{await this.checkPending()}),this.events.on(Rt.created,async r=>{const i=Rt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()}),this.events.on(Rt.deleted,async r=>{const i=Rt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:r}),await this.persist()})}),this.relayer=e,this.logger=Ot(n,this.name),this.clientId=""}get context(){return dt(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=wa(r);await this.restartToComplete({topic:e,id:n,relay:i}),await this.rpcUnsubscribe(e,n,i);const s=xe("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===ve.relay)&&await this.restartToComplete({topic:e,id:e,relay:n});const a={method:Pi(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===ve.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(f=>this.logger.warn(f))},H.toMiliseconds(H.ONE_SECOND)),o;const u=new Promise(async f=>{const d=h=>{h.topic===e&&(this.events.removeListener(Rt.created,d),f(h.id))};this.events.on(Rt.created,d);try{const h=await cn(new Promise((p,g)=>{this.relayer.request(a).catch(m=>{this.logger.warn(m,m?.message),g(m)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Rt.created,d),f(h)}catch{}}),l=await cn(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(Be.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return;const n=e[0].relay,r={method:Pi(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 cn(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(Be.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const n=e[0].relay,r={method:Pi(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 cn(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(Be.connection_stalled)}return i}rpcUnsubscribe(e,n,r){const i={method:Pi(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,Rl(Ls({},n),{id:e})),this.pending.delete(n.topic)}onBatchSubscribe(e){e.length&&e.forEach(n=>{this.setSubscription(n.id,Ls({},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,Ls({},n)),this.topicMap.set(n.topic,e),this.events.emit(Rt.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}=G("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(Rt.deleted,Rl(Ls({},r),{reason:n}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Rt.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(Rt.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}=G("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=>Rl(Ls({},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 V_(H.toMiliseconds(H.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}=G("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 Mt(e+await this.getClientId())}}var dA=Object.defineProperty,vy=Object.getOwnPropertySymbols,pA=Object.prototype.hasOwnProperty,gA=Object.prototype.propertyIsEnumerable,Nl=(t,e,n)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ey=(t,e)=>{for(var n in e||(e={}))pA.call(e,n)&&Nl(t,n,e[n]);if(vy)for(var n of vy(e))gA.call(e,n)&&Nl(t,n,e[n]);return t},ue=(t,e,n)=>Nl(t,typeof e!="symbol"?e+"":e,n);class yA extends dm{constructor(e){var n;super(e),ue(this,"protocol","wc"),ue(this,"version",2),ue(this,"core"),ue(this,"logger"),ue(this,"events",new rt.exports.EventEmitter),ue(this,"provider"),ue(this,"messages"),ue(this,"subscriber"),ue(this,"publisher"),ue(this,"name",G7),ue(this,"transportExplicitlyClosed",!1),ue(this,"initialized",!1),ue(this,"connectionAttemptInProgress",!1),ue(this,"relayUrl"),ue(this,"projectId"),ue(this,"packageName"),ue(this,"bundleId"),ue(this,"hasExperiencedNetworkDisruption",!1),ue(this,"pingTimeout"),ue(this,"heartBeatTimeout",H.toMiliseconds(H.THIRTY_SECONDS+H.FIVE_SECONDS)),ue(this,"reconnectTimeout"),ue(this,"connectPromise"),ue(this,"reconnectInProgress",!1),ue(this,"requestsInFlight",[]),ue(this,"connectTimeout",H.toMiliseconds(H.ONE_SECOND*15)),ue(this,"request",async r=>{var i,s;this.logger.debug("Publishing Request Payload");const o=r.id||Sr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(i=r.params)==null?void 0:i.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ue(this,"resetPingTimeout",()=>{Yo()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,i,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(i=(r=this.provider)==null?void 0:r.connection)==null?void 0:i.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),ue(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ue(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected \u{1F6DC}"),this.startPingTimeout(),this.events.emit(Be.connect)}),ue(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected \u{1F6D1}"),this.requestsInFlight=[],this.onProviderDisconnect()}),ue(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(Be.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,this.transportClose().catch(i=>this.logger.warn(i))}),ue(this,"registerProviderListeners",()=>{this.provider.on(zt.payload,this.onPayloadHandler),this.provider.on(zt.connect,this.onConnectHandler),this.provider.on(zt.disconnect,this.onDisconnectHandler),this.provider.on(zt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=P1({logger:(n=e.logger)!=null?n:H7,name:this.name}),this.messages=new XB(this.logger,e.core),this.subscriber=new hA(this,this.logger),this.publisher=new rA(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Y1,A_()?this.packageName=N0():D_()&&(this.bundleId=N0()),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 dt(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:ve.relay},_a.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(Rt.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Rt.created,u)}),new Promise(async(l,f)=>{a=await this.subscriber.subscribe(e,Ey({internal:{throwOnFailedPublish:o}},n)).catch(d=>{o&&f(d)})||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 cn(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,this.reconnectInProgress=!1,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 T1())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=Te(H.FIVE_MINUTES),s={topic:r,expiry:i,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(Be.message,e),await this.recordMessageEvent(e,_a.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(zt.disconnect,s),await cn(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(zt.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(zt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(zt.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,H.toMiliseconds(n*1))),n++}}startPingTimeout(){var e,n,r,i,s;if(Yo())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 A7(new P7(N_({sdkVersion:Ol,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}),Sl(e)){if(!e.method.endsWith(W7))return;const n=e.params,{topic:r,message:i,publishedAt:s,attestation:o}=n.data,a={topic:r,message:i,publishedAt:s,transportType:ve.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Ey({type:"event",event:n.id},a)),this.events.emit(n.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else Ea(e)&&this.events.emit(Be.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,_a.inbound),this.events.emit(Be.message,e))}async acknowledgePayload(e){const n=va(e.id,!0);await this.provider.connection.send(n)}unregisterProviderListeners(){this.provider.off(zt.payload,this.onPayloadHandler),this.provider.off(zt.connect,this.onConnectHandler),this.provider.off(zt.disconnect,this.onDisconnectHandler),this.provider.off(zt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await T1();T9(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(Dr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&N9())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(n){this.logger.warn(n,n?.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(Be.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},H.toMiliseconds(Z7)))))}isInitialized(){if(!this.initialized){const{message:e}=G("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 bA(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function xy(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function _y(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const wA="[object RegExp]",mA="[object String]",vA="[object Number]",EA="[object Boolean]",Iy="[object Arguments]",xA="[object Symbol]",_A="[object Date]",IA="[object Map]",SA="[object Set]",OA="[object Array]",BA="[object Function]",AA="[object ArrayBuffer]",Cl="[object Object]",DA="[object Error]",$A="[object DataView]",TA="[object Uint8Array]",PA="[object Uint8ClampedArray]",RA="[object Uint16Array]",NA="[object Uint32Array]",CA="[object BigUint64Array]",UA="[object Int8Array]",FA="[object Int16Array]",kA="[object Int32Array]",LA="[object BigInt64Array]",qA="[object Float32Array]",MA="[object Float64Array]";function jA(){}function Sy(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 zA(t,e,n){return qs(t,e,void 0,void 0,void 0,void 0,n)}function qs(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 Ms(t,e,s,o)}return Ms(t,e,s,o)}function Ms(t,e,n,r){if(Object.is(t,e))return!0;let i=_y(t),s=_y(e);if(i===Iy&&(i=Cl),s===Iy&&(s=Cl),i!==s)return!1;switch(i){case mA:return t.toString()===e.toString();case vA:{const c=t.valueOf(),u=e.valueOf();return bA(c,u)}case EA:case _A:case xA:return Object.is(t.valueOf(),e.valueOf());case wA:return t.source===e.source&&t.flags===e.flags;case BA: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 IA:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!qs(u,e.get(c),c,t,e,n,r))return!1;return!0}case SA:{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],d=u.findIndex(h=>qs(f,h,void 0,t,e,n,r));if(d===-1)return!1;u.splice(d,1)}return!0}case OA:case TA:case PA:case RA:case NA:case CA:case UA:case FA:case kA:case LA:case qA:case MA:{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(!qs(t[c],e[c],c,t,e,n,r))return!1;return!0}case AA:return t.byteLength!==e.byteLength?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case $A:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:Ms(new Uint8Array(t),new Uint8Array(e),n,r);case DA:return t.name===e.name&&t.message===e.message;case Cl:{if(!(Ms(t.constructor,e.constructor,n,r)||Sy(t)&&Sy(e)))return!1;const c=[...Object.keys(t),...xy(t)],u=[...Object.keys(e),...xy(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const f=c[l],d=t[f];if(!Object.hasOwn(e,f))return!1;const h=e[f];if(!qs(d,h,f,t,e,n,r))return!1}return!0}default:return!1}}finally{n.delete(t),n.delete(e)}}function VA(t,e){return zA(t,e,jA)}var KA=Object.defineProperty,Oy=Object.getOwnPropertySymbols,HA=Object.prototype.hasOwnProperty,GA=Object.prototype.propertyIsEnumerable,Ul=(t,e,n)=>e in t?KA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,By=(t,e)=>{for(var n in e||(e={}))HA.call(e,n)&&Ul(t,n,e[n]);if(Oy)for(var n of Oy(e))GA.call(e,n)&&Ul(t,n,e[n]);return t},It=(t,e,n)=>Ul(t,typeof e!="symbol"?e+"":e,n);class ei extends pm{constructor(e,n,r,i=fn,s=void 0){super(e,n,r,i),this.core=e,this.logger=n,this.name=r,It(this,"map",new Map),It(this,"version",Y7),It(this,"cached",[]),It(this,"initialized",!1),It(this,"getKey"),It(this,"storagePrefix",fn),It(this,"recentlyDeleted",[]),It(this,"recentlyDeletedLimit",200),It(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Re(o)?this.map.set(this.getKey(o),o):c9(o)?this.map.set(o.id,o):u9(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),It(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())}),It(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),It(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>VA(a[c],o[c]))):this.values)),It(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=By(By({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),It(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=Ot(n,this.name),this.storagePrefix=i,this.getKey=s}get context(){return dt(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}=G("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}const{message:r}=G("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}=G("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}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var WA=Object.defineProperty,ZA=(t,e,n)=>e in t?WA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,se=(t,e,n)=>ZA(t,typeof e!="symbol"?e+"":e,n);class YA{constructor(e,n){this.core=e,this.logger=n,se(this,"name",eO),se(this,"version",tO),se(this,"events",new rt.exports),se(this,"pairings"),se(this,"initialized",!1),se(this,"storagePrefix",fn),se(this,"ignoredPayloadTypes",[kn]),se(this,"registeredMethods",[]),se(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),se(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),se(this,"create",async r=>{this.isInitialized();const i=pl(),s=await this.core.crypto.setSymKey(i),o=Te(H.FIVE_MINUTES),a={protocol:Z1},c={topic:s,expiry:o,relay:a,active:!1,methods:r?.methods},u=w1({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:i,relay:a,expiryTimestamp:o,methods:r?.methods});return this.events.emit(Xr.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}}),se(this,"pair",async r=>{this.isInitialized();const i=this.core.eventClient.createEvent({properties:{topic:r?.uri,trace:[hn.pairing_started]}});this.isValidPair(r,i);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:u}=b1(r.uri);i.props.properties.topic=s,i.addTrace(hn.pairing_uri_validation_success),i.addTrace(hn.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(s)){if(l=this.pairings.get(s),i.addTrace(hn.existing_pairing),l.active)throw i.setError(jn.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);i.addTrace(hn.pairing_not_expired)}const f=c||Te(H.FIVE_MINUTES),d={topic:s,relay:a,expiry:f,active:!1,methods:u};this.core.expirer.set(s,f),await this.pairings.set(s,d),i.addTrace(hn.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Xr.create,d),i.addTrace(hn.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),i.addTrace(hn.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{i.setError(jn.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(h){throw i.setError(jn.subscribe_pairing_topic_failure),h}return i.addTrace(hn.subscribe_pairing_topic_success),d}),se(this,"activate",async({topic:r})=>{this.isInitialized();const i=Te(H.FIVE_MINUTES);this.core.expirer.set(r,i),await this.pairings.update(r,{active:!0,expiry:i})}),se(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}=zr();this.events.once(de("pairing_ping",s),({error:u})=>{u?c(u):a()}),await o()}}),se(this,"updateExpiry",async({topic:r,expiry:i})=>{this.isInitialized(),await this.pairings.update(r,{expiry:i})}),se(this,"updateMetadata",async({topic:r,metadata:i})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:i})}),se(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),se(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",xe("USER_DISCONNECTED")),await this.deletePairing(i))}),se(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:i,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(i);return w1({protocol:this.core.protocol,version:this.core.version,topic:i,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),se(this,"sendRequest",async(r,i,s)=>{const o=Mn(i,s),a=await this.core.crypto.encode(r,o),c=Cs[i].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),se(this,"sendResult",async(r,i,s)=>{const o=va(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c].res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"sendError",async(r,i,s)=>{const o=Il(r,s),a=await this.core.crypto.encode(i,o),c=(await this.core.history.get(i,r)).request.method,u=Cs[c]?Cs[c].res:Cs.unregistered_method.res;await this.core.relayer.publish(i,a,u),await this.core.history.resolve(o)}),se(this,"deletePairing",async(r,i)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,xe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),i?Promise.resolve():this.core.expirer.del(r)])}),se(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(i=>lr(i.expiry));await Promise.all(r.map(i=>this.deletePairing(i.topic)))}),se(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)}}),se(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)}}),se(this,"onPairingPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Xr.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onPairingPingResponse",(r,i)=>{const{id:s}=i;setTimeout(()=>{ln(i)?this.events.emit(de("pairing_ping",s),{}):jt(i)&&this.events.emit(de("pairing_ping",s),{error:i.error})},500)}),se(this,"onPairingDeleteRequest",async(r,i)=>{const{id:s}=i;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Xr.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),se(this,"onUnknownRpcMethodRequest",async(r,i)=>{const{id:s,method:o}=i;try{if(this.registeredMethods.includes(o))return;const a=xe("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)}}),se(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(xe("WC_METHOD_UNSUPPORTED",r))}),se(this,"isValidPair",(r,i)=>{var s;if(!_t(r)){const{message:a}=G("MISSING_OR_INVALID",`pair() params: ${r}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!a9(r.uri)){const{message:a}=G("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw i.setError(jn.malformed_pairing_uri),new Error(a)}const o=b1(r?.uri);if(!((s=o?.relay)!=null&&s.protocol)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#relay-protocol");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=G("MISSING_OR_INVALID","pair() uri#symKey");throw i.setError(jn.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&H.toMiliseconds(o?.expiryTimestamp)<Date.now()){i.setError(jn.pairing_expired);const{message:a}=G("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),se(this,"isValidPing",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidDisconnect",async r=>{if(!_t(r)){const{message:s}=G("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidPairingTopic(i)}),se(this,"isValidPairingTopic",async r=>{if(!Oe(r,!1)){const{message:i}=G("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(i)}if(!this.pairings.keys.includes(r)){const{message:i}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(i)}if(lr(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:i}=G("EXPIRED",`pairing topic: ${r}`);throw new Error(i)}}),this.core=e,this.logger=Ot(n,this.name),this.pairings=new ei(this.core,this.logger,this.name,this.storagePrefix)}get context(){return dt(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(Be.message,async e=>{const{topic:n,message:r,transportType:i}=e;if(this.pairings.keys.includes(n)&&i!==ve.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(n,r);Sl(s)?(this.core.history.set(n,s),await this.onRelayEventRequest({topic:n,payload:s})):Ea(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(Vt.expired,async e=>{const{topic:n}=k0(e.target);n&&this.pairings.keys.includes(n)&&(await this.deletePairing(n,!0),this.events.emit(Xr.expire,{topic:n}))})}}var XA=Object.defineProperty,JA=(t,e,n)=>e in t?XA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ve=(t,e,n)=>JA(t,typeof e!="symbol"?e+"":e,n);class QA extends lm{constructor(e,n){super(e,n),this.core=e,this.logger=n,Ve(this,"records",new Map),Ve(this,"events",new rt.exports.EventEmitter),Ve(this,"name",nO),Ve(this,"version",rO),Ve(this,"cached",[]),Ve(this,"initialized",!1),Ve(this,"storagePrefix",fn),Ve(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)}),Ve(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:Te(H.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(en.created,o)}),Ve(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=jt(r)?{error:r.error}:{result:r.result},this.records.set(i.id,i),this.persist(),this.events.emit(en.updated,i))}),Ve(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))),Ve(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(en.deleted,s)}}),this.persist()}),Ve(this,"exists",async(r,i)=>(this.isInitialized(),this.records.has(i)?(await this.getRecord(i)).topic===r:!1)),Ve(this,"on",(r,i)=>{this.events.on(r,i)}),Ve(this,"once",(r,i)=>{this.events.once(r,i)}),Ve(this,"off",(r,i)=>{this.events.off(r,i)}),Ve(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(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:Mn(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}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return n}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(en.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:n}=G("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(en.created,e=>{const n=en.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.updated,e=>{const n=en.updated;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.events.on(en.deleted,e=>{const n=en.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,record:e})}),this.core.heartbeat.on(Dr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(n=>{H.toMiliseconds(n.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${n.id}`),this.records.delete(n.id),this.events.emit(en.deleted,n,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var eD=Object.defineProperty,tD=(t,e,n)=>e in t?eD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,nt=(t,e,n)=>tD(t,typeof e!="symbol"?e+"":e,n);class nD extends ym{constructor(e,n){super(e,n),this.core=e,this.logger=n,nt(this,"expirations",new Map),nt(this,"events",new rt.exports.EventEmitter),nt(this,"name",iO),nt(this,"version",sO),nt(this,"cached",[]),nt(this,"initialized",!1),nt(this,"storagePrefix",fn),nt(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)}),nt(this,"has",r=>{try{const i=this.formatTarget(r);return typeof this.getExpiration(i)<"u"}catch{return!1}}),nt(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(Vt.created,{target:s,expiration:o})}),nt(this,"get",r=>{this.isInitialized();const i=this.formatTarget(r);return this.getExpiration(i)}),nt(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(Vt.deleted,{target:i,expiration:s})}}),nt(this,"on",(r,i)=>{this.events.on(r,i)}),nt(this,"once",(r,i)=>{this.events.once(r,i)}),nt(this,"off",(r,i)=>{this.events.off(r,i)}),nt(this,"removeListener",(r,i)=>{this.events.removeListener(r,i)}),this.logger=Ot(n,this.name)}get context(){return dt(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 C_(e);if(typeof e=="number")return U_(e);const{message:n}=G("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(Vt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:n}=G("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}=G("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return n}checkExpiry(e,n){const{expiry:r}=n;H.toMiliseconds(r)-Date.now()<=0&&this.expire(e,n)}expire(e,n){this.expirations.delete(e),this.events.emit(Vt.expired,{target:e,expiration:n})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,n)=>this.checkExpiry(n,e))}registerEventListeners(){this.core.heartbeat.on(Dr.pulse,()=>this.checkExpirations()),this.events.on(Vt.created,e=>{const n=Vt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.expired,e=>{const n=Vt.expired;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()}),this.events.on(Vt.deleted,e=>{const n=Vt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}}var rD=Object.defineProperty,iD=(t,e,n)=>e in t?rD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ae=(t,e,n)=>iD(t,typeof e!="symbol"?e+"":e,n);class sD extends bm{constructor(e,n,r){super(e,n,r),this.core=e,this.logger=n,this.store=r,Ae(this,"name",oO),Ae(this,"abortController"),Ae(this,"isDevEnv"),Ae(this,"verifyUrlV3",cO),Ae(this,"storagePrefix",fn),Ae(this,"version",G1),Ae(this,"publicKey"),Ae(this,"fetchPromise"),Ae(this,"init",async()=>{var i;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&H.toMiliseconds((i=this.publicKey)==null?void 0:i.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),Ae(this,"register",async i=>{if(!Ii()||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=Nr(),l=this.startAbortTimer(H.ONE_SECOND*5),f=await new Promise((d,h)=>{const p=()=>{window.removeEventListener("message",m),u.body.removeChild(g),h("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 m=B=>{if(B.data&&typeof B.data=="string")try{const $=JSON.parse(B.data);if($.type==="verify_attestation"){if(yc($.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",m),d($.attestation===null?"":$.attestation)}}catch($){this.logger.warn($)}};u.body.appendChild(g),window.addEventListener("message",m,{signal:this.abortController.signal})});return this.logger.debug(f,"jwt attestation"),f}catch(u){this.logger.warn(u)}return""}),Ae(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(yc(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)}),Ae(this,"fetchAttestation",async(i,s)=>{this.logger.debug(`resolving attestation: ${i} from url: ${s}`);const o=this.startAbortTimer(H.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}),Ae(this,"getVerifyUrl",i=>{let s=i||Us;return uO.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${Us}`),s=Us),s}),Ae(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const i=this.startAbortTimer(H.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)}}),Ae(this,"persistPublicKey",async i=>{this.logger.debug(i,"persisting public key to local storage"),await this.store.setItem(this.storeKey,i),this.publicKey=i}),Ae(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),Ae(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")}}),Ae(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),Ae(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}),Ae(this,"validateAttestation",(i,s)=>{const o=PS(i,s.publicKey),a={hasExpired:H.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=Ot(n,this.name),this.abortController=new AbortController,this.isDevEnv=Fu(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return dt(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),H.toMiliseconds(e))}}var oD=Object.defineProperty,aD=(t,e,n)=>e in t?oD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ay=(t,e,n)=>aD(t,typeof e!="symbol"?e+"":e,n);class cD extends wm{constructor(e,n){super(e,n),this.projectId=e,this.logger=n,Ay(this,"context",lO),Ay(this,"registerDeviceToken",async r=>{const{clientId:i,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${fO}/${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=Ot(n,this.context)}}var uD=Object.defineProperty,Dy=Object.getOwnPropertySymbols,lD=Object.prototype.hasOwnProperty,fD=Object.prototype.propertyIsEnumerable,Fl=(t,e,n)=>e in t?uD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,js=(t,e)=>{for(var n in e||(e={}))lD.call(e,n)&&Fl(t,n,e[n]);if(Dy)for(var n of Dy(e))fD.call(e,n)&&Fl(t,n,e[n]);return t},ke=(t,e,n)=>Fl(t,typeof e!="symbol"?e+"":e,n);class hD extends mm{constructor(e,n,r=!0){super(e,n,r),this.core=e,this.logger=n,ke(this,"context",dO),ke(this,"storagePrefix",fn),ke(this,"storageVersion",hO),ke(this,"events",new Map),ke(this,"shouldPersist",!1),ke(this,"init",async()=>{if(!Fu())try{const i={eventId:q0(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:U0(this.core.relayer.protocol,this.core.relayer.version,Ol)}}};await this.sendEvent([i])}catch(i){this.logger.warn(i)}}),ke(this,"createEvent",i=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=i,u=q0(),l=this.core.projectId||"",f=Date.now(),d=js({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,d),this.shouldPersist=!0),d}),ke(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 js(js({},a),this.setMethods(a.eventId))}),ke(this,"deleteEvent",i=>{const{eventId:s}=i;this.events.delete(s),this.shouldPersist=!0}),ke(this,"setEventListeners",()=>{this.core.heartbeat.on(Dr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(i=>{H.fromMiliseconds(Date.now())-H.fromMiliseconds(i.timestamp)>pO&&(this.events.delete(i.eventId),this.shouldPersist=!0)})})}),ke(this,"setMethods",i=>({addTrace:s=>this.addTrace(i,s),setError:s=>this.setError(i,s)})),ke(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)}),ke(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)}),ke(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),ke(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,js(js({},s),this.setMethods(s.eventId)))})}catch(i){this.logger.warn(i)}}),ke(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)}}),ke(this,"sendEvent",async i=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${gO}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ol}${s}`,{method:"POST",body:JSON.stringify(i)})}),ke(this,"getAppDomain",()=>C0().url),this.logger=Ot(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 dD=Object.defineProperty,$y=Object.getOwnPropertySymbols,pD=Object.prototype.hasOwnProperty,gD=Object.prototype.propertyIsEnumerable,kl=(t,e,n)=>e in t?dD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Ty=(t,e)=>{for(var n in e||(e={}))pD.call(e,n)&&kl(t,n,e[n]);if($y)for(var n of $y(e))gD.call(e,n)&&kl(t,n,e[n]);return t},me=(t,e,n)=>kl(t,typeof e!="symbol"?e+"":e,n);class Ll extends om{constructor(e){var n;super(e),me(this,"protocol",H1),me(this,"version",G1),me(this,"name",xa),me(this,"relayUrl"),me(this,"projectId"),me(this,"customStoragePrefix"),me(this,"events",new rt.exports.EventEmitter),me(this,"logger"),me(this,"heartbeat"),me(this,"relayer"),me(this,"crypto"),me(this,"storage"),me(this,"history"),me(this,"expirer"),me(this,"pairing"),me(this,"verify"),me(this,"echoClient"),me(this,"linkModeSupportedApps"),me(this,"eventClient"),me(this,"initialized",!1),me(this,"logChunkController"),me(this,"on",(a,c)=>this.events.on(a,c)),me(this,"once",(a,c)=>this.events.once(a,c)),me(this,"off",(a,c)=>this.events.off(a,c)),me(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),me(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ve.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||Y1,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const i=Qw({level:typeof e?.logger=="string"&&e.logger?e.logger:U7.logger,name:xa}),{logger:s,chunkLoggerController:o}=Ff({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=Ot(s,this.name),this.heartbeat=new qa,this.crypto=new zB(this,this.logger,e?.keychain),this.history=new QA(this,this.logger),this.expirer=new nD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new dw(Ty(Ty({},F7),e?.storageOptions)),this.relayer=new yA({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new YA(this,this.logger),this.verify=new sD(this,this.logger,this.storage),this.echoClient=new cD(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new hD(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const n=new Ll(e);await n.initialize();const r=await n.crypto.getClientId();return await n.storage.setItem(X7,r),n}get context(){return dt(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(X1,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(X1)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const n=`_walletConnectCore_${e}`,r=`${n}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[n]}catch(n){console.warn("Failed to get global WalletConnect core",n);return}}setGlobalCore(e){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 yD=Ll,Py="wc",Ry=2,Ny="client",ql=`${Py}@${Ry}:${Ny}:`,Ml={name:Ny,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},Cy="WALLETCONNECT_DEEPLINK_CHOICE",bD="proposal",Uy="Proposal expired",wD="session",Fi=H.SEVEN_DAYS,mD="engine",Ke={wc_sessionPropose:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1104},res:{ttl:H.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1106},res:{ttl:H.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:H.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1112},res:{ttl:H.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:H.ONE_DAY,prompt:!1,tag:1114},res:{ttl:H.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:H.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:H.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:H.FIVE_MINUTES,prompt:!1,tag:1119}}},jl={min:H.FIVE_MINUTES,max:H.SEVEN_DAYS},pn={idle:"IDLE",active:"ACTIVE"},vD={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:""}},ED="request",xD=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],_D="wc",ID="auth",SD="authKeys",OD="pairingTopics",BD="requests",Sa=`${_D}@${1.5}:${ID}:`,Oa=`${Sa}:PUB_KEY`;var AD=Object.defineProperty,DD=Object.defineProperties,$D=Object.getOwnPropertyDescriptors,Fy=Object.getOwnPropertySymbols,TD=Object.prototype.hasOwnProperty,PD=Object.prototype.propertyIsEnumerable,zl=(t,e,n)=>e in t?AD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,fe=(t,e)=>{for(var n in e||(e={}))TD.call(e,n)&&zl(t,n,e[n]);if(Fy)for(var n of Fy(e))PD.call(e,n)&&zl(t,n,e[n]);return t},He=(t,e)=>DD(t,$D(e)),V=(t,e,n)=>zl(t,typeof e!="symbol"?e+"":e,n);class RD extends _m{constructor(e){super(e),V(this,"name",mD),V(this,"events",new rt.exports),V(this,"initialized",!1),V(this,"requestQueue",{state:pn.idle,queue:[]}),V(this,"sessionRequestQueue",{state:pn.idle,queue:[]}),V(this,"emittedSessionRequests",new K_({limit:500})),V(this,"requestQueueDelay",H.ONE_SECOND),V(this,"expectedPairingMethodMap",new Map),V(this,"recentlyDeletedMap",new Map),V(this,"recentlyDeletedLimit",200),V(this,"relayMessageCache",[]),V(this,"pendingSessions",new Map),V(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(Ke)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay)))}),V(this,"connect",async n=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const i=He(fe({},n),{requiredNamespaces:n.requiredNamespaces||{},optionalNamespaces:n.optionalNamespaces||{}});await this.isValidConnect(i),i.optionalNamespaces=n9(i.requiredNamespaces,i.optionalNamespaces),i.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:f,walletPay:d}=i,h=((r=f?.[0])==null?void 0:r.ttl)||Ke.wc_sessionPropose.req.ttl||H.FIVE_MINUTES;this.validateRequestExpiry(h);let p=s,g,m=!1;try{if(p){const D=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),m=D.active}}catch(D){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),D}if(!p||!m){const{topic:D,uri:j}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=D,g=j}if(!p){const{message:D}=G("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(D)}const B=await this.client.core.crypto.generateKeyPair(),$=Te(h),x=fe(He(fe(fe({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Z1}],proposer:{publicKey:B,metadata:this.client.metadata},expiryTimestamp:$,pairingTopic:p},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:Pt()}),(f||d)&&{requests:{authentication:f?.map(D=>{const{domain:j,chains:M,nonce:E,uri:b,exp:v,nbf:y,type:w,statement:I,requestId:O,resources:S,signatureTypes:A}=D;return{domain:j,chains:M,nonce:E,type:w??"caip122",aud:b,version:"1",iat:new Date().toISOString(),exp:v,nbf:y,statement:I,requestId:O,resources:S,signatureTypes:A}}),walletPay:d}}),_=de("session_connect",x.id),{reject:T,resolve:P,done:C}=zr(h,Uy),U=({id:D})=>{D===x.id&&(this.client.events.off("proposal_expire",U),this.pendingSessions.delete(x.id),this.events.emit(_,{error:{message:Uy,code:0}}))};return this.client.events.on("proposal_expire",U),this.events.once(_,({error:D,session:j})=>{this.client.events.off("proposal_expire",U),D?T(D):j&&P(j)}),await this.setProposal(x.id,x),await this.sendProposeSession({proposal:x,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:x.id}}}).catch(D=>{throw this.deleteProposal(x.id),D}),{uri:g,approval:C}}),V(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}}),V(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:[tn.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(j){throw o.setError(Jr.no_internet_connection),j}try{await this.isValidProposalId(n?.id)}catch(j){throw this.client.logger.error(`approve() -> proposal.get(${n?.id}) failed`),o.setError(Jr.proposal_not_found),j}try{await this.isValidApprove(n)}catch(j){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(Jr.session_approve_namespace_validation_failure),j}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:f,sessionConfig:d,proposalRequestsResponses:h}=n,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:m,requiredNamespaces:B,optionalNamespaces:$}=p;let x=(i=this.client.core.eventClient)==null?void 0:i.getEvent({topic:g});x||(x=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:tn.session_approve_started,properties:{topic:g,trace:[tn.session_approve_started,tn.session_namespaces_validation_success]}}));const _=await this.client.core.crypto.generateKeyPair(),T=m.publicKey,P=await this.client.core.crypto.generateSharedKey(_,T),C=He(fe(fe(fe({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:_,metadata:this.client.metadata},expiry:Te(Fi)},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{proposalRequestsResponses:h}),U=ve.relay;x.addTrace(tn.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:U,internal:{skipSubscribe:!0}})}catch(j){throw x.setError(Jr.subscribe_session_topic_failure),j}x.addTrace(tn.subscribe_session_topic_success);const D=He(fe({},C),{topic:P,requiredNamespaces:B,optionalNamespaces:$,pairingTopic:g,acknowledged:!1,self:C.controller,peer:{publicKey:m.publicKey,metadata:m.metadata},controller:_,transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(P,D),x.addTrace(tn.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:_},sessionSettleRequest:C,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:fe({correlationId:a},this.getTVFApproveParams(D))}}),x.addTrace(tn.session_approve_publish_success)}catch(j){throw this.client.logger.error(j),this.client.session.delete(P,xe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),j}return this.client.core.eventClient.deleteEvent({eventId:x.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:m.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,Te(Fi)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),V(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:Ke.wc_sessionPropose.reject}),await this.deleteProposal(r)}),V(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}=zr(H.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Pt(),u=Sr().toString(),l=this.client.session.get(r).namespaces;return this.events.once(de("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}}),V(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=Pt(),{done:s,resolve:o,reject:a}=zr(H.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(de("session_extend",i),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,Te(Fi)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:i,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),V(this,"request",async n=>{this.isInitialized();try{await this.isValidRequest(n)}catch(m){throw this.client.logger.error("request() -> isValidRequest() failed"),m}const{chainId:r,request:i,topic:s,expiry:o=Ke.wc_sessionRequest.req.ttl}=n,a=this.client.session.get(s);a?.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const c=Pt(),u=Sr().toString(),{done:l,resolve:f,reject:d}=zr(o,"Request expired. Please try again.");this.events.once(de("session_request",c),({error:m,result:B})=>{m?d(m):f(B)});const h="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:{request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(m=>d(m)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),await l();const g={request:He(fe({},i),{expiryTimestamp:Te(o)}),chainId:r};return await Promise.all([new Promise(async m=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:s,method:h,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(B=>d(B)),this.client.events.emit("session_request_sent",{topic:s,request:i,chainId:r,id:c}),m()}),new Promise(async m=>{var B;if(!((B=a.sessionConfig)!=null&&B.disableDeepLink)){const $=await q_(this.client.core.storage,Cy);await F_({id:c,topic:s,wcDeepLink:$})}m()}),l()]).then(m=>m[2])}),V(this,"respond",async n=>{var r,i;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:n?.topic||((i=(r=n?.response)==null?void 0:r.id)==null?void 0:i.toString()),trace:[tn.session_request_response_started]}});try{await this.isValidRespond(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_validation_failure),f}s.addTrace(tn.session_request_response_validation_success);const{topic:o,response:a}=n,{id:c}=a,u=this.client.session.get(o);u.transportType===ve.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{s.addTrace(tn.session_request_response_publish_started),ln(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):jt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(n)}catch(f){throw s.addTrace(f?.message),s.setError(Jr.session_request_response_publish_failure),f}}),V(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=Pt(),s=Sr().toString(),{done:o,resolve:a,reject:c}=zr(H.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(de("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}))}),V(this,"emit",async n=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(n);const{topic:r,event:i,chainId:s}=n,o=Sr().toString(),a=Pt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:i,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),V(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:xe("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}=G("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(i)}}),V(this,"find",n=>(this.isInitialized(),this.client.session.getAll().filter(r=>s9(r,n)))),V(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),V(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?ve.link_mode:ve.relay;o===ve.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:f,type:d,exp:h,nbf:p,methods:g=[],expiry:m}=n,B=[...n.resources||[]],{topic:$,uri:x}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:$,uri:x}});const _=await this.client.core.crypto.generateKeyPair(),T=ba(_);if(await Promise.all([this.client.auth.authKeys.set(Oa,{responseTopic:T,publicKey:_}),this.client.auth.pairingTopics.set(T,{topic:T,pairingTopic:$})]),await this.client.core.relayer.subscribe(T,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${$}`),g.length>0){const{namespace:S}=Pn(a[0]);let A=rI(S,"request",g);sa(B)&&(A=sI(A,B.pop())),B.push(A)}const P=m&&m>Ke.wc_sessionAuthenticate.req.ttl?m:Ke.wc_sessionAuthenticate.req.ttl,C={authPayload:{type:d??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:f,iat:new Date().toISOString(),exp:h,nbf:p,resources:B},requester:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(P)},U={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},D={requiredNamespaces:{},optionalNamespaces:U,relays:[{protocol:"irn"}],pairingTopic:$,proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:Te(Ke.wc_sessionPropose.req.ttl),id:Pt()},{done:j,resolve:M,reject:E}=zr(P,"Request expired"),b=Pt(),v=de("session_connect",D.id),y=de("session_request",b),w=async({error:S,session:A})=>{this.events.off(y,I),S?E(S):A&&M({session:A})},I=async S=>{var A,R,k;if(await this.deletePendingAuthRequest(b,{message:"fulfilled",code:0}),S.error){const K=xe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return S.error.code===K.code?void 0:(this.events.off(v,w),E(S.error.message))}await this.deleteProposal(D.id),this.events.off(v,w);const{cacaos:F,responder:L}=S.result,N=[],q=[];for(const K of F){await hg({cacao:K,projectId:this.client.core.projectId})||(this.client.logger.error(K,"Signature verification failed"),E(xe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Z}=K,Q=sa(Z.resources),ee=[Ku(Z.iss)],ie=ia(Z.iss);if(Q){const he=gg(Q),Ee=yg(Q);N.push(...he),ee.push(...Ee)}for(const he of ee)q.push(`${he}:${ie}`)}const z=await this.client.core.crypto.generateSharedKey(_,L.publicKey);let W;N.length>0&&(W={topic:z,acknowledged:!0,self:{publicKey:_,metadata:this.client.metadata},peer:L,controller:L.publicKey,expiry:Te(Fi),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:$,namespaces:I1([...new Set(N)],[...new Set(q)]),transportType:o},await this.client.core.relayer.subscribe(z,{transportType:o}),await this.client.session.set(z,W),$&&await this.client.core.pairing.updateMetadata({topic:$,metadata:L.metadata}),W=this.client.session.get(z)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(R=L.metadata.redirect)!=null&&R.linkMode&&(k=L.metadata.redirect)!=null&&k.universal&&r&&(this.client.core.addLinkModeSupportedApp(L.metadata.redirect.universal),this.client.session.update(z,{transportType:ve.link_mode})),M({auths:F,session:W})};this.events.once(v,w),this.events.once(y,I);let O;try{if(s){const S=Mn("wc_sessionAuthenticate",C,b);this.client.core.history.set($,S);const A=await this.client.core.crypto.encode("",S,{type:Bs,encoding:Ir});O=ma(r,$,A)}else await Promise.all([this.sendRequest({topic:$,method:"wc_sessionAuthenticate",params:C,expiry:n.expiry,throwOnFailedPublish:!0,clientRpcId:b}),this.sendRequest({topic:$,method:"wc_sessionPropose",params:D,expiry:Ke.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:D.id})])}catch(S){throw this.events.off(v,w),this.events.off(y,I),S}return await this.setProposal(D.id,D),await this.setAuthRequest(b,{request:He(fe({},C),{verifyContext:{}}),pairingTopic:$,transportType:o}),{uri:O??x,response:j}}),V(this,"approveSessionAuthenticate",async n=>{const{id:r,auths:i}=n,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Qr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(m){throw s.setError(Fs.no_internet_connection),m}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(Fs.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||ve.relay;a===ve.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=ba(c),f={type:kn,receiverPublicKey:c,senderPublicKey:u},d=[],h=[];for(const m of i){if(!await hg({cacao:m,projectId:this.client.core.projectId})){s.setError(Fs.invalid_cacao);const T=xe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:l,error:T,encodeOpts:f}),new Error(T.message)}s.addTrace(Qr.cacaos_verified);const{p:B}=m,$=sa(B.resources),x=[Ku(B.iss)],_=ia(B.iss);if($){const T=gg($),P=yg($);d.push(...T),x.push(...P)}for(const T of x)h.push(`${T}:${_}`)}const p=await this.client.core.crypto.generateSharedKey(u,c);s.addTrace(Qr.create_authenticated_session_topic);let g;if(d?.length>0){g={topic:p,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:Te(Fi),authentication:i,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:I1([...new Set(d)],[...new Set(h)]),transportType:a},s.addTrace(Qr.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(m){throw s.setError(Fs.subscribe_authenticated_session_topic_failure),m}s.addTrace(Qr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Qr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Qr.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(m){throw s.setError(Fs.authenticated_session_approve_publish_failure),m}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}}),V(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===ve.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ba(o),u={type:kn,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:i,encodeOpts:u,rpcOpts:Ke.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)}),V(this,"formatAuthMessage",n=>{this.isInitialized();const{request:r,iss:i}=n;return dg(r,i)}),V(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)}),V(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)}}),V(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,xe("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(Cy).catch(u=>this.client.logger.warn(u)),i===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=pn.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===i).map(u=>this.deletePendingSessionRequest(u.id,xe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:i})}),V(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(Jr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(n,xe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(n)]),this.addToRecentlyDeleted(n,"proposal")}),V(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=pn.idle,this.client.events.emit("session_request_expire",{id:n}))}),V(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)])}),V(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}))}),V(this,"setProposal",async(n,r)=>{this.client.core.expirer.set(n,Te(Ke.wc_sessionPropose.req.ttl)),await this.client.proposal.set(n,r)}),V(this,"setAuthRequest",async(n,r)=>{const{request:i,pairingTopic:s,transportType:o=ve.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})}),V(this,"setPendingSessionRequest",async n=>{const{id:r,topic:i,params:s,verifyContext:o}=n,a=s.request.expiryTimestamp||Te(Ke.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})}),V(this,"sendRequest",async n=>{const{topic:r,method:i,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:f,publishOpts:d={}}=n,h=Mn(i,s,c);let p;const g=!!l;try{const $=g?Ir:xt;p=await this.client.core.crypto.encode(r,h,{encoding:$})}catch($){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),$}let m;if(xD.includes(i)){const $=Mt(JSON.stringify(h)),x=Mt(p);m=await this.client.core.verify.register({id:x,decryptedId:$})}const B=fe(fe({},Ke[i].req),d);if(B.attestation=m,o&&(B.ttl=o),a&&(B.id=a),this.client.core.history.set(r,h),g){const $=ma(l,r,p);await global.Linking.openURL($,this.client.name)}else B.tvf=He(fe({},f),{correlationId:h.id}),u?(B.internal=He(fe({},B.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,B)):this.client.core.relayer.publish(r,p,B).catch($=>this.client.logger.error($));return h.id}),V(this,"sendProposeSession",async n=>{const{proposal:r,publishOpts:i}=n,s=Mn("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:xt}),a=Mt(JSON.stringify(s)),c=Mt(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:He(fe({},i),{publishMethod:"wc_proposeSession",attestation:u})})}),V(this,"sendApproveSession",async n=>{const{sessionTopic:r,pairingProposalResponse:i,proposal:s,sessionSettleRequest:o,publishOpts:a}=n,c=va(s.id,i),u=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:xt}),l=Mn("wc_sessionSettle",o,a?.id),f=await this.client.core.crypto.encode(r,l,{encoding:xt});this.client.core.history.set(r,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:f},opts:He(fe({},a),{publishMethod:"wc_approveSession"})})}),V(this,"sendResult",async n=>{const{id:r,topic:i,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=n,u=va(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const p=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${i} failed`),p}let d,h;try{d=await this.client.core.history.get(i,r);const p=d.request;try{h=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=ma(c,i,l);await global.Linking.openURL(p,this.client.name)}else{const p=d.request.method,g=Ke[p].res;g.tvf=He(fe({},h),{correlationId:r}),o?(g.internal=He(fe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,l,g)):this.client.core.relayer.publish(i,l,g).catch(m=>this.client.logger.error(m))}await this.client.core.history.resolve(u)}),V(this,"sendError",async n=>{const{id:r,topic:i,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=n,u=Il(r,s);let l;const f=c&&typeof(global==null?void 0:global.Linking)<"u";try{const h=f?Ir:xt;l=await this.client.core.crypto.encode(i,u,He(fe({},o||{}),{encoding:h}))}catch(h){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${i} failed`),h}let d;try{d=await this.client.core.history.get(i,r)}catch(h){throw this.client.logger.error(`sendError() -> history.get(${i}, ${r}) failed`),h}if(f){const h=ma(c,i,l);await global.Linking.openURL(h,this.client.name)}else{const h=d.request.method,p=a||Ke[h].res;this.client.core.relayer.publish(i,l,p)}await this.client.core.history.resolve(u)}),V(this,"cleanup",async()=>{const n=[],r=[];this.client.session.getAll().forEach(i=>{let s=!1;lr(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=>{lr(i.expiryTimestamp)&&r.push(i.id)}),await Promise.all([...n.map(i=>this.deleteSession({topic:i})),...r.map(i=>this.deleteProposal(i))])}),V(this,"onProviderMessageEvent",async n=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(n):await this.onRelayMessage(n)}),V(this,"onRelayEventRequest",async n=>{this.requestQueue.queue.push(n),await this.processRequestsQueue()}),V(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===pn.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=pn.active;const n=this.requestQueue.queue.shift();if(n)try{await this.processRequest(n)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=pn.idle}),V(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}`)}}),V(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}`)}}),V(this,"onRelayEventUnknownPayload",n=>{const{topic:r}=n,{message:i}=G("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(i)}),V(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)}),V(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(jn.proposal_listener_not_found)),this.isValidConnect(fe({},i.params));const l=a.expiryTimestamp||Te(Ke.wc_sessionPropose.req.ttl),f=fe({id:c,pairingTopic:r,expiryTimestamp:l,attestation:s,encryptedId:o},a);await this.setProposal(c,f);const d=await this.getVerifyContext({attestationId:s,hash:Mt(JSON.stringify(i)),encryptedId:o,metadata:f.proposer.metadata});u?.addTrace(hn.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:f,verifyContext:d})}catch(u){await this.sendError({id:c,topic:r,error:u,rpcOpts:Ke.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),V(this,"onSessionProposeResponse",async(n,r,i)=>{const{id:s}=r;if(ln(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(jt(r)){await this.deleteProposal(s);const o=de("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})}}),V(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:d,proposalRequestsResponses:h}=r.params,p=[...this.pendingSessions.values()].find(B=>B.sessionTopic===n);if(!p)return this.client.logger.error(`Pending session not found for topic ${n}`);const g=this.client.proposal.get(p.proposalId),m=He(fe(fe(fe({topic:n,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),f&&{scopedProperties:f}),d&&{sessionConfig:d}),{transportType:ve.relay,authentication:h?.authentication,walletPayResult:h?.walletPay});await this.client.session.set(m.topic,m),await this.setExpiry(m.topic,m.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:m.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(m),await this.sendResult({id:r.id,topic:n,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:m}),this.events.emit(de("session_connect",p.proposalId),{session:m})}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionSettleResponse",async(n,r)=>{const{id:i}=r;ln(r)?(await this.client.session.update(n,{acknowledged:!0}),this.events.emit(de("session_approve",i),{})):jt(r)&&(await this.client.session.delete(n,xe("USER_DISCONNECTED")),this.events.emit(de("session_approve",i),{error:r.error}))}),V(this,"onSessionUpdateRequest",async(n,r)=>{const{params:i,id:s}=r;try{const o=`${n}_session_update`,a=Ps.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:xe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(fe({topic:n},i));try{Ps.set(o,s),await this.client.session.update(n,{namespaces:i.namespaces}),await this.sendResult({id:s,topic:n,result:!0})}catch(c){throw Ps.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)}}),V(this,"isRequestOutOfSync",(n,r)=>r.toString().slice(0,-3)<n.toString().slice(0,-3)),V(this,"onSessionUpdateResponse",(n,r)=>{const{id:i}=r,s=de("session_update",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_update",i),{}):jt(r)&&this.events.emit(de("session_update",i),{error:r.error})}),V(this,"onSessionExtendRequest",async(n,r)=>{const{id:i}=r;try{this.isValidExtend({topic:n}),await this.setExpiry(n,Te(Fi)),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)}}),V(this,"onSessionExtendResponse",(n,r)=>{const{id:i}=r,s=de("session_extend",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_extend",i),{}):jt(r)&&this.events.emit(de("session_extend",i),{error:r.error})}),V(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)}}),V(this,"onSessionPingResponse",(n,r)=>{const{id:i}=r,s=de("session_ping",i);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);ln(r)?this.events.emit(de("session_ping",i),{}):jt(r)&&this.events.emit(de("session_ping",i),{error:r.error})},500)}),V(this,"onSessionDeleteRequest",async(n,r)=>{const{id:i}=r;try{await this.isValidDisconnect({topic:n,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:n,error:xe("USER_DISCONNECTED")}),await this.deleteSession({topic:n,id:i})}catch(s){this.client.logger.error(s)}}),V(this,"onSessionRequest",async n=>{var r,i,s;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=n,{id:f,params:d}=a;try{await this.isValidRequest(fe({topic:o},d));const h=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:Mt(JSON.stringify(Mn("wc_sessionRequest",d,f))),encryptedId:u,metadata:h.peer.metadata,transportType:l}),g={id:f,topic:o,params:d,verifyContext:p};await this.setPendingSessionRequest(g),l===ve.link_mode&&(r=h.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((i=h.peer.metadata.redirect)==null?void 0:i.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(h){await this.sendError({id:f,topic:o,error:h}),this.client.logger.error(h)}}),V(this,"onSessionRequestResponse",(n,r)=>{const{id:i}=r,s=de("session_request",i);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(this,"onSessionEventRequest",async(n,r)=>{const{id:i,params:s}=r;try{const o=`${n}_session_event_${s.event.name}`,a=Ps.get(o);if(a&&this.isRequestOutOfSync(a,i)){this.client.logger.info(`Discarding out of sync request - ${i}`);return}this.isValidEmit(fe({topic:n},s)),this.client.events.emit("session_event",{id:i,topic:n,params:s}),Ps.set(o,i)}catch(o){await this.sendError({id:i,topic:n,error:o}),this.client.logger.error(o)}}),V(this,"onSessionAuthenticateResponse",(n,r)=>{const{id:i}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:n,payload:r}),ln(r)?this.events.emit(de("session_request",i),{result:r.result}):jt(r)&&this.events.emit(de("session_request",i),{error:r.error})}),V(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,d=await this.getVerifyContext({attestationId:o,hash:Mt(JSON.stringify(s)),encryptedId:a,metadata:u.metadata,transportType:c}),h={requester:u,pairingTopic:i,id:s.id,authPayload:l,verifyContext:d,expiryTimestamp:f};await this.setAuthRequest(s.id,{request:h,pairingTopic:i,transportType:c}),c===ve.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:d})}catch(u){this.client.logger.error(u);const l=s.params.requester.publicKey,f=await this.client.core.crypto.generateKeyPair(),d=this.getAppLinkIfEnabled(s.params.requester.metadata,c),h={type:kn,receiverPublicKey:l,senderPublicKey:f};await this.sendError({id:s.id,topic:i,error:u,encodeOpts:h,rpcOpts:Ke.wc_sessionAuthenticate.autoReject,appLink:d})}}),V(this,"addSessionRequestToSessionRequestQueue",n=>{this.sessionRequestQueue.queue.push(n)}),V(this,"cleanupAfterResponse",n=>{this.deletePendingSessionRequest(n.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=pn.idle,this.processSessionRequestQueue()},H.toMiliseconds(this.requestQueueDelay))}),V(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=>{this.events.emit(de("session_request",s.request.id),{error:r})})}),V(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===pn.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)}}),V(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=pn.active,this.emittedSessionRequests.add(n.id),this.client.events.emit("session_request",n)}),V(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:Mn("wc_sessionPropose",He(fe({},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})}),V(this,"isValidConnect",async n=>{if(!_t(n)){const{message:u}=G("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(Re(r)||await this.isValidPairingTopic(r),!b9(c,!0)){const{message:u}=G("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(i&&!Re(i)&&$s(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(s&&!Re(s)&&$s(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(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)}`)}}),V(this,"validateNamespaces",(n,r)=>{const i=y9(n,"connect()",r);if(i)throw new Error(i.message)}),V(this,"isValidApprove",async n=>{if(!_t(n))throw new Error(G("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=bl(i,"approve()");if(u)throw new Error(u.message);const l=D1(c.requiredNamespaces,i,"approve()");if(l)throw new Error(l.message);if(!Oe(s,!0)){const{message:f}=G("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(f)}if(o&&!Re(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Re(a)){this.validateSessionProps(a,"scopedProperties");const f=new Set(Object.keys(i));if(!Object.keys(a).every(d=>f.has(d.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(f).join(", ")}`)}}),V(this,"isValidReject",async n=>{if(!_t(n)){const{message:s}=G("MISSING_OR_INVALID",`reject() params: ${n}`);throw new Error(s)}const{id:r,reason:i}=n;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!m9(i)){const{message:s}=G("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(i)}`);throw new Error(s)}}),V(this,"isValidSessionSettleRequest",n=>{if(!_t(n)){const{message:u}=G("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${n}`);throw new Error(u)}const{relay:r,controller:i,namespaces:s,expiry:o}=n;if(!B1(r)){const{message:u}=G("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=l9(i,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=bl(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(lr(o)){const{message:u}=G("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),V(this,"isValidUpdate",async n=>{if(!_t(n)){const{message:c}=G("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=bl(i,"update()");if(o)throw new Error(o.message);const a=D1(s.requiredNamespaces,i,"update()");if(a)throw new Error(a.message)}),V(this,"isValidExtend",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`extend() params: ${n}`);throw new Error(i)}const{topic:r}=n;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),V(this,"isValidRequest",async n=>{if(!_t(n)){const{message:c}=G("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(!A1(a,s)){const{message:c}=G("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!v9(i)){const{message:c}=G("MISSING_OR_INVALID",`request() ${JSON.stringify(i)}`);throw new Error(c)}if(!_9(a,s,i.method)){const{message:c}=G("MISSING_OR_INVALID",`request() method: ${i.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),V(this,"isValidRespond",async n=>{var r;if(!_t(n)){const{message:a}=G("MISSING_OR_INVALID",`respond() params: ${n}`);throw new Error(a)}const{topic:i,response:s}=n;try{await this.isValidSessionTopic(i)}catch(a){throw(r=n?.response)!=null&&r.id&&this.cleanupAfterResponse(n),a}if(!E9(s)){const{message:a}=G("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==i){const{message:a}=G("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${i}`);throw new Error(a)}}),V(this,"isValidPing",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`ping() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(this,"isValidEmit",async n=>{if(!_t(n)){const{message:a}=G("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(!A1(o,s)){const{message:a}=G("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!x9(i)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}if(!I9(o,s,i.name)){const{message:a}=G("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(i)}`);throw new Error(a)}}),V(this,"isValidDisconnect",async n=>{if(!_t(n)){const{message:i}=G("MISSING_OR_INVALID",`disconnect() params: ${n}`);throw new Error(i)}const{topic:r}=n;await this.isValidSessionOrPairingTopic(r)}),V(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(!Oe(i,!1))throw new Error("uri is required parameter");if(!Oe(s,!1))throw new Error("domain is required parameter");if(!Oe(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>Pn(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=Pn(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),V(this,"getVerifyContext",async n=>{const{attestationId:r,hash:i,encryptedId:s,metadata:o,transportType:a}=n,c={verified:{verifyUrl:o.verifyUrl||Us,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ve.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}),V(this,"validateSessionProps",(n,r)=>{Object.values(n).forEach((i,s)=>{if(i==null){const{message:o}=G("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${i} for key ${Object.keys(n)[s]}`);throw new Error(o)}})}),V(this,"getPendingAuthRequest",n=>{const r=this.client.auth.requests.get(n);return typeof r=="object"?r:void 0}),V(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)}}}),V(this,"checkRecentlyDeleted",n=>{const r=this.recentlyDeletedMap.get(n);if(r){const{message:i}=G("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${n}`);throw new Error(i)}}),V(this,"isLinkModeEnabled",(n,r)=>{var i,s,o,a,c,u,l,f,d;return!n||r!==ve.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)!==""&&((d=n?.redirect)==null?void 0:d.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(n.redirect.universal)&&typeof(global==null?void 0:global.Linking)<"u"}),V(this,"getAppLinkIfEnabled",(n,r)=>{var i;return this.isLinkModeEnabled(n,r)?(i=n?.redirect)==null?void 0:i.universal:void 0}),V(this,"handleLinkModeMessage",({url:n})=>{if(!n||!n.includes("wc_ev")||!n.includes("topic"))return;const r=L0(n,"topic")||"",i=decodeURIComponent(L0(n,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:ve.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:i,sessionExists:s})}),V(this,"registerLinkModeListeners",async()=>{var n;if(Fu()||ur()&&(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)}}}),V(this,"getTVFApproveParams",n=>{try{const r=E1(n.namespaces),i=YS(n.namespaces),s=XS(n.namespaces),o=n.sessionProperties,a=n.scopedProperties;return{approvedChains:r,approvedMethods:i,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),V(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(u,"Error getting TVF params")}return c}),V(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}),V(this,"extractTxHashesFromResult",(n,r)=>{var i;try{if(!r)return[];const s=n.method,o=vD[s];if(s==="sui_signTransaction")return[k5(r.transactionBytes)];if(s==="near_signTransaction")return[ag(r)];if(s==="near_signTransactions")return r.map(c=>ag(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(i=r.tx_json)==null?void 0:i.hash];if(s==="polkadot_signTransaction")return[j9({transaction:n.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return Ni(r)?r.map(c=>cg(c)):[cg(r)];if(s==="cosmos_signDirect")return[q5(r)];if(s==="wallet_sendCalls")return M5(r);if(typeof r=="string")return[r];const a=r[o.key];if(Ni(a))return s==="solana_signAllTransactions"?a.map(c=>F5(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,n=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,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(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=G("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(Be.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(Oa)?this.client.auth.authKeys.get(Oa):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(n,r,{receiverPublicKey:o,encoding:s===ve.link_mode?Ir:xt});Sl(a)?(this.client.core.history.set(n,a),await this.onRelayEventRequest({topic:n,payload:a,attestation:i,transportType:s,encryptedId:Mt(r)})):Ea(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)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:n,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(n,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(Vt.expired,async e=>{const{topic:n,id:r}=k0(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,G("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,G("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(Xr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Xr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!Oe(e,!1)){const{message:n}=G("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}=G("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.core.pairing.pairings.get(e).expiry)){const{message:n}=G("EXPIRED",`pairing topic: ${e}`);throw new Error(n)}}async isValidSessionTopic(e){if(!Oe(e,!1)){const{message:n}=G("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}=G("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:n}=G("EXPIRED",`session topic: ${e}`);throw new Error(n)}if(!this.client.core.crypto.keychain.has(e)){const{message:n}=G("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(n)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(Oe(e,!1)){const{message:n}=G("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(n)}else{const{message:n}=G("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(n)}}async isValidProposalId(e){if(!w9(e)){const{message:n}=G("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(n)}if(!this.client.proposal.keys.includes(e)){const{message:n}=G("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(n)}if(lr(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:n}=G("EXPIRED",`proposal id: ${e}`);throw new Error(n)}}validateRequestExpiry(e){if(e&&!B9(e,jl)){const{message:n}=G("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${jl.min} and ${jl.max}`);throw new Error(n)}}}class ND extends ei{constructor(e,n){super(e,n,bD,ql),this.core=e,this.logger=n}}class CD extends ei{constructor(e,n){super(e,n,wD,ql),this.core=e,this.logger=n}}class UD extends ei{constructor(e,n){super(e,n,ED,ql,r=>r.id),this.core=e,this.logger=n}}class FD extends ei{constructor(e,n){super(e,n,SD,Sa,()=>Oa),this.core=e,this.logger=n}}class kD extends ei{constructor(e,n){super(e,n,OD,Sa),this.core=e,this.logger=n}}class LD extends ei{constructor(e,n){super(e,n,BD,Sa,r=>r.id),this.core=e,this.logger=n}}var qD=Object.defineProperty,MD=(t,e,n)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,Vl=(t,e,n)=>MD(t,typeof e!="symbol"?e+"":e,n);class jD{constructor(e,n){this.core=e,this.logger=n,Vl(this,"authKeys"),Vl(this,"pairingTopics"),Vl(this,"requests"),this.authKeys=new FD(this.core,this.logger),this.pairingTopics=new kD(this.core,this.logger),this.requests=new LD(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var zD=Object.defineProperty,VD=(t,e,n)=>e in t?zD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,oe=(t,e,n)=>VD(t,typeof e!="symbol"?e+"":e,n);class Kl extends xm{constructor(e){super(e),oe(this,"protocol",Py),oe(this,"version",Ry),oe(this,"name",Ml.name),oe(this,"metadata"),oe(this,"core"),oe(this,"logger"),oe(this,"events",new rt.exports.EventEmitter),oe(this,"engine"),oe(this,"session"),oe(this,"proposal"),oe(this,"pendingRequest"),oe(this,"auth"),oe(this,"signConfig"),oe(this,"on",(r,i)=>this.events.on(r,i)),oe(this,"once",(r,i)=>this.events.once(r,i)),oe(this,"off",(r,i)=>this.events.off(r,i)),oe(this,"removeListener",(r,i)=>this.events.removeListener(r,i)),oe(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),oe(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"update",async r=>{try{return await this.engine.update(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"request",async r=>{try{return await this.engine.request(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"find",r=>{try{return this.engine.find(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),oe(this,"authenticate",async(r,i)=>{try{return await this.engine.authenticate(r,i)}catch(s){throw this.logger.error(s.message),s}}),oe(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),oe(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(i){throw this.logger.error(i.message),i}}),this.name=e?.name||Ml.name,this.metadata=T_(e?.metadata),this.signConfig=e?.signConfig;const n=P1({logger:e?.logger||Ml.logger,name:this.name});this.logger=n,this.core=e?.core||new yD(e),this.session=new CD(this.core,this.logger),this.proposal=new ND(this.core,this.logger),this.pendingRequest=new UD(this.core,this.logger),this.engine=new RD(this),this.auth=new jD(this.core,this.logger)}static async init(e){const n=new Kl(e);return await n.initialize(),n}get context(){return dt(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 KD=Kl;class ky{constructor(e){this.opts=e}}class Ly{constructor(e){this.client=e}}const qy=t=>{const{supportedNamespaces:e,token:n}=t,{network:r,symbol:i,standard:s,address:o}=n;if(!r||!i||!s||!o||!Ts(r?.chainId))return!1;const{namespace:a}=Pn(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},HD=t=>{const{supportedNamespaces:e,paymentIntent:n}=t,{token:r,amount:i,recipient:s}=n;return!(!r||!i||!s||!qy({supportedNamespaces:e,token:r}))},My=t=>{let e,n;return async()=>e!==void 0?e:n||(n=t(),e=await n,e)};var GD=Object.defineProperty,WD=(t,e,n)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,le=(t,e,n)=>WD(t,typeof e!="symbol"?e+"":e,n);class ZD extends Ly{constructor(e){var n;super(e),le(this,"signClient"),le(this,"logger"),le(this,"tokens",[]),le(this,"supportedNamespaces",cf),le(this,"paymentIntents",{}),le(this,"transactions",{}),le(this,"paymentsSendingInProgress",{}),le(this,"manualControl",{}),le(this,"init",async()=>{var r,i;this.signClient=await KD.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)||$a.database},customStoragePrefix:$a.customStoragePrefix,logger:((i=this.client.opts.loggerOptions)==null?void 0:i.signLevel)||Ta}),this.signClient.events.on("session_delete",({topic:s})=>{this.cleanup({sessionTopic:s}),this.emit("disconnected",{sessionTopic:s})});try{this.logger.debug("Fetching supported namespaces/networks");const s=await this.fetchRpcRequest({payload:JSON.stringify({id:Pt(),jsonrpc:"2.0",method:"wc_pos_supportedNetworks",params:{}}),userId:""});this.logger.debug({supportedNamespaces:s.result.namespaces},"Received supported namespaces/networks"),this.supportedNamespaces=s.result.namespaces}catch(s){this.logger.error(s,"Failed to fetch supported namespaces/networks")}}),le(this,"setTokens",async r=>{const{tokens:i}=r;this.logger.debug({tokens:i},"Setting tokens"),i.forEach(s=>{if(!qy({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:i},"Tokens set")}),le(this,"createPaymentIntent",async r=>{const{paymentIntents:i,sessionTopic:s,userId:o}=r;this.logger.debug({paymentIntents:i,userId:o},"Creating payment intent");const a=r.manualControl||!1;if(i.length===0)throw new Error("No payment intents provided");for(const d of i)if(!HD({paymentIntent:d,supportedNamespaces:this.supportedNamespaces}))throw new Error(`Invalid payment intent: ${JSON.stringify(d)}`);if(this.logger.debug({paymentIntents:i,userId:o},"Payment intent validation success"),s){this.manualControl[s]=a;try{this.setPaymentIntents({sessionTopic:s,paymentIntents:i,userId:o}),this.validateApprovedNamespacesWithPaymentIntents(s),a||await this.sendPaymentsToWallet({sessionTopic:s,userId:o});return}catch(d){this.logger.error(d),await this.disconnect({sessionTopic:s})}}const c=this.composeNamespacesFromPaymentIntents(i),{uri:u,approval:l}=await this.signClient.connect({optionalNamespaces:c});if(this.logger.debug({uri:u,userId:o},"Connected to the WalletConnect network"),!u)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:o}),new Error("Failed to connect to the WalletConnect network");const f=My(l);if(this.emit("await_approval",{approval:f,paymentIntents:i,userId:o,manualControl:a}),this.logger.debug("Emitted await_approval event"),this.emit("qr_ready",{uri:u,userId:o}),this.logger.debug({uri:u,userId:o},"Emitted qr_ready event"),a){const d=await f();this.manualControl[d.topic]=a}}),le(this,"restart",async r=>{this.logger.debug({params:r},"Restarting");const{reinit:i,sessionTopic:s,userId:o}=r||{};if(i){this.tokens=[],await this.disconnect({sessionTopic:s}),this.logger.debug("Restarted: Cleared payment intents, transactions and disconnected");return}const a=this.getSessionTopic(s),c=this.manualControl[a],u=this.paymentIntents[a];if(!u||!(u!=null&&u.length))throw new Error("No payment intents found for session topic: "+a);await this.createPaymentIntent({paymentIntents:u,manualControl:c,userId:o,sessionTopic:a}),this.logger.debug({paymentIntents:u,userId:o},"Restarted: Created payment intent flow from the beginning")}),le(this,"connect",async r=>{const{userId:i}=r,s=!0,o=this.composeNamespacesFromTokens(),{uri:a,approval:c}=await this.signClient.connect({optionalNamespaces:o});if(this.logger.debug({uri:a},"Connected to the WalletConnect network"),!a)throw this.client.events.emit("connection_failed",{error:{message:"Failed to connect to the WalletConnect network",code:4001},userId:i}),new Error("Failed to connect to the WalletConnect network");const u=My(c);this.emit("await_approval",{approval:u,manualControl:s,paymentIntents:[],userId:i}),this.logger.debug({userId:i},"Emitted await_approval event"),this.emit("qr_ready",{uri:a,userId:i}),this.logger.debug({uri:a,userId:i},"Emitted qr_ready event");const l=await u();return this.manualControl[l.topic]=s,l}),le(this,"emit",(r,i)=>(this.logger.debug({event:r,args:i},"Emit"),this.client.events.emit(r,i))),le(this,"on",(r,i)=>(this.logger.debug({event:r,listener:i},"On"),this.client.events.on(r,i))),le(this,"once",(r,i)=>(this.logger.debug({event:r,listener:i},"Once"),this.client.events.once(r,i))),le(this,"off",(r,i)=>(this.logger.debug({event:r,listener:i},"Off"),this.client.events.off(r,i))),le(this,"removeListener",(r,i)=>(this.logger.debug({event:r,listener:i},"Remove listener"),this.client.events.removeListener(r,i))),le(this,"prepareTransactionsFromPaymentIntents",async r=>{var i,s,o,a,c,u;const{sessionTopic:l,userId:f}=r,d=this.getSessionTopic(l),h=this.paymentIntents[d];if(!h)throw new Error("No payment intents found for session topic: "+d);const p=this.signClient.session.get(d);this.logger.debug({sessionTopic:d,userId:f},"Preparing transactions from payment intents");const g=[];for(const $ of h){const{token:x,amount:_,recipient:T}=$,{namespace:P}=Pn(x.network.chainId),C=(o=(s=(i=p.namespaces)==null?void 0:i[P])==null?void 0:s.accounts)==null?void 0:o.find(U=>U.includes(`${x.network.chainId}:`));if(!C)throw new Error(`Address not found in session for chain id: ${x.network.chainId}, approved addresses: ${(u=(c=(a=p.namespaces)==null?void 0:a[P])==null?void 0:c.accounts)==null?void 0:u.join(", ")}`);g.push({asset:`${x.network.chainId}/${x.standard.toLowerCase()}:${x.address}`,recipient:T,amount:_,sender:C})}this.logger.debug({sessionTopic:p.topic,transactions:g,userId:f},"Prepared transactions from payment intents");const m={id:Pt(),jsonrpc:"2.0",method:"wc_pos_buildTransactions",params:{paymentIntents:g}};this.logger.debug({payload:m,userId:f},"Fetching wc_pos_buildTransactions");const B=await this.fetchRpcRequest({payload:JSON.stringify(m),userId:f});this.logger.debug({response:B,userId:f},"Received wc_pos_buildTransactions"),this.transactions[p.topic]=B.result.transactions,this.logger.debug({transactions:this.transactions[p.topic],userId:f},"Payment intent to transactions map set")}),le(this,"sendPaymentsToWallet",async(r={})=>{const{sessionTopic:i,userId:s}=r,o=this.getSessionTopic(i);if(!o)throw new Error("No session topic found, call createPaymentIntent() first");if(this.paymentsSendingInProgress[o])throw new Error("Payments are already being sent, please wait for them to complete");this.paymentsSendingInProgress[o]=!0;try{await this.prepareTransactionsFromPaymentIntents({sessionTopic:o,userId:s}),await this.sendTransactionsToWallet({sessionTopic:o,userId:s})}catch(a){throw this.logger.error(a,"Error while sending payments to wallet"),this.paymentsSendingInProgress[o]=!1,a}this.paymentsSendingInProgress[o]=!1}),le(this,"sendTransactionsToWallet",async r=>{const{sessionTopic:i,userId:s}=r,o=this.transactions[i],a=this.paymentIntents[i];if(!o||!a)throw new Error("No transactions or payment intents to send, call createPaymentIntent() first");if(o.length!==a.length)throw new Error(`Mismatch between transactions (${o.length}) and payment intents (${a.length}). The RPC response returned an unexpected number of transactions.`);this.logger.debug({transactions:o,sessionTopic:i,userId:s},"Sending transactions to wallet");for(let c=0;c<o.length;c++){const u=o[c],l=a[c];try{this.emit("payment_requested",{paymentIntent:l,transaction:u,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_requested event");let f;try{f=await this.signClient.request({topic:i,request:{method:u.method,params:u.params},chainId:u.chainId}),this.logger.debug({transactionId:u.id,result:f,userId:s},"Wallet responded to payment request")}catch(d){throw this.logger.error(d,"Error while sending payment request"),this.emit("payment_rejected",{error:{message:d?.message,code:4001},paymentIntent:l,sessionTopic:i,userId:s}),d}this.emit("payment_broadcasted",{paymentIntent:l,transaction:u,result:f,sessionTopic:i,userId:s}),this.logger.debug({transactionId:u.id,userId:s},"Emitted payment_broadcasted event"),await this.awaitPaymentConfirmed({transaction:u,result:f,sessionTopic:i,userId:s}),await new Promise(d=>setTimeout(d,1e3))}catch(f){this.logger.error(f,"Error while awaiting payment confirmed")}}this.manualControl[i]!==!0&&await this.disconnect({sessionTopic:i})}),le(this,"awaitPaymentConfirmed",async r=>{const{transaction:i,result:s,sessionTopic:o,userId:a}=r;try{this.logger.debug({transactionId:i.id,result:s},"Awaiting payment confirmed");const c={id:Pt(),jsonrpc:"2.0",method:"wc_pos_checkTransaction",params:{id:i.id,sendResult:typeof s=="string"?s:JSON.stringify(s)}};let u=0,l;for(;!l;){if(u>=af)throw new Error(`Transaction status not found for id: ${i.id}`);u++;const f=await this.fetchRpcRequest({payload:JSON.stringify(c),userId:a});if(this.logger.debug({transactionId:i.id,response:f},"Received wc_pos_checkTransaction"),f.result.status==="CONFIRMED"){this.logger.debug({response:f,userId:a},"Transaction status confirmed"),this.emit("payment_successful",{transaction:i,result:s,sessionTopic:o,userId:a}),l=f.result;break}else if(f.result.status==="FAILED"){this.logger.debug({response:f},"Transaction failed"),this.emit("payment_failed",{error:{message:f.result.error,code:4001},transaction:s,sessionTopic:o,userId:a}),l=f.result;break}else f.result.status==="PENDING"&&(this.logger.debug({response:f,userId:a},"Transaction pending"),await new Promise(d=>setTimeout(d,f.result.checkIn||1e3)))}}catch(c){this.logger.error(c,"Error while awaiting payment confirmations"),this.emit("payment_failed",{error:{message:c?.message,code:4001},transaction:i,sessionTopic:o,userId:a})}}),le(this,"setupEventHandlers",()=>{this.on("await_approval",async({approval:r,paymentIntents:i,userId:s,manualControl:o})=>{try{this.logger.debug("On await_approval");const a=await r();this.setPaymentIntents({sessionTopic:a.topic,paymentIntents:i}),await this.onSessionConnected({session:a,userId:s,manualControl:o})}catch(a){this.logger.error(a,"Error while awaiting approval"),this.emit("connection_rejected",{error:{message:a?.message,code:4001},userId:s})}})}),le(this,"onSessionConnected",async r=>{const{session:i,userId:s,manualControl:o}=r;this.logger.debug({sessionTopic:i.topic,userId:s},"On session connected"),this.emit("connected",{session:i,userId:s}),await this.signClient.session.update(i.topic,{sessionConfig:{disableDeepLink:!0}}),this.logger.debug({sessionTopic:i.topic,userId:s},"Disabled deep links for session"),this.logger.debug({sessionTopic:i.topic,userId:s},"Emitted connected event"),o!==!0&&await this.sendPaymentsToWallet({sessionTopic:i.topic,userId:s})}),le(this,"disconnect",async(r={})=>{try{const{sessionTopic:i}=r,s=this.getSessionTopic(i);if(!s)return;this.cleanup({sessionTopic:s}),await this.signClient.disconnect({topic:s,reason:{code:4001,message:"User disconnected"}})}catch(i){this.logger.error(i,"Error while disconnecting")}}),le(this,"fetchRpcRequest",async r=>{var i,s,o,a,c,u;const{payload:l,userId:f}=r;this.logger.debug({url:this.getRpcUrl(),payload:l,userId:f},"Fetching RPC request");const d=await fetch(this.getRpcUrl(),{method:"POST",body:l});let h;try{h=await d.json()}catch(p){this.logger.error(p,"Error while getting json data from RPC response")}if(this.logger.debug({data:h},"Received RPC request response"),!d.ok||!h||h!=null&&h.error){const p=((i=h?.error)==null?void 0:i.code)||-18900,g=(s=Pa)!=null&&s[p]?`${(o=Pa)==null?void 0:o[p]}: ${(a=h?.error)==null?void 0:a.message}`:((c=h?.error)==null?void 0:c.message)||"Failed to parse RPC response";throw this.emit("payment_failed",{error:{message:g,code:p},transaction:"",sessionTopic:((u=this.client.session)==null?void 0:u.topic)||"",userId:f}),new Error(g)}return h}),le(this,"validateApprovedNamespacesWithPaymentIntents",r=>{var i,s,o,a,c,u,l;this.validateSessionTopic(r);const f=this.signClient.session.get(r),d=(i=this.paymentIntents)==null?void 0:i[r];if(!f||!d)throw new Error("No session or payment intents found");for(const h of d){const{token:p}=h,{namespace:g}=Pn(p.network.chainId);if(!((a=(o=(s=f.namespaces)==null?void 0:s[g])==null?void 0:o.accounts)!=null&&a.find(m=>m.includes(`${p.network.chainId}:`))))throw new Error(`Address not found in session for chain id: ${p.network.chainId}, approved addresses: ${(l=(u=(c=f.namespaces)==null?void 0:c[g])==null?void 0:u.accounts)==null?void 0:l.join(", ")}`)}}),le(this,"setPaymentIntents",r=>{const{sessionTopic:i,paymentIntents:s,userId:o}=r;this.paymentIntents[i]=s,this.logger.debug({paymentIntents:s,userId:o},"Payment intents set")}),le(this,"cleanup",(r={})=>{const{sessionTopic:i}=r;i&&(delete this.paymentIntents[i],delete this.transactions[i],delete this.manualControl[i],delete this.paymentsSendingInProgress[i],this.logger.debug({sessionTopic:i},"Cleaned up payment intents and transactions"))}),le(this,"getRpcUrl",()=>uf({projectId:this.client.opts.projectId,deviceId:this.client.opts.deviceId})),le(this,"validateSessionTopic",r=>{if(r)try{this.signClient.session.get(r)}catch(i){throw this.logger.error(i,`No session found for topic: ${r}`),new Error(`No session found for topic: ${r}`)}}),le(this,"getSessionTopic",r=>{var i;if(!r&&this.client.sessions.length>1)throw new Error("Multiple sessions found, please specify the session topic in the params: { sessionTopic: '...' }");const s=r||((i=this.client.session)==null?void 0:i.topic);if(!s)throw new Error("No session topic found. Please provide a sessionTopic or establish a session first.");return this.validateSessionTopic(s),s}),this.signClient={},this.logger=Pw({name:this.client.name,level:((n=this.client.opts.loggerOptions)==null?void 0:n.posLevel)||Ta}),this.setupEventHandlers()}composeNamespacesFromTokens(){const e=this.tokens;if(this.logger.debug({tokens:e},"Composing namespaces from tokens"),e.length===0)throw new Error("No set tokens to compose namespaces from, call setTokens() first");const n={};return e.forEach(r=>{var i;const{network:s}=r,{namespace:o}=Pn(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({namespaces:n},"Composed namespaces"),n}composeNamespacesFromPaymentIntents(e){this.logger.debug({paymentIntents:e},"Composing namespaces");const n={};return e.forEach(r=>{var i;const{token:{network:s}}=r,{namespace:o}=Pn(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({namespaces:n},"Composed namespaces"),n}}var YD=Object.defineProperty,XD=(t,e,n)=>e in t?YD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,St=(t,e,n)=>XD(t,typeof e!="symbol"?e+"":e,n);class Ba extends ky{constructor(e){super(e),St(this,"name"),St(this,"events",new rt.exports),St(this,"engine"),St(this,"metadata"),St(this,"on",(n,r)=>this.engine.on(n,r)),St(this,"once",(n,r)=>this.engine.once(n,r)),St(this,"off",(n,r)=>this.engine.off(n,r)),St(this,"removeListener",(n,r)=>this.engine.removeListener(n,r)),St(this,"setTokens",async n=>{try{return await this.engine.setTokens(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"createPaymentIntent",async n=>{try{return await this.engine.createPaymentIntent(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"restart",async n=>{try{return await this.engine.restart(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"sendPaymentsToWallet",async n=>{try{return await this.engine.sendPaymentsToWallet(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"disconnect",async n=>{try{return await this.engine.disconnect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),St(this,"connect",async n=>{try{return await this.engine.connect(n)}catch(r){throw this.engine.logger.error(r.message),r}}),this.metadata=e.metadata,this.name=Da,this.engine=new ZD(this)}static async init(e){const n=new Ba(e);return await n.initialize(),n}get sessions(){return this.engine.signClient.session.getAll()}get session(){return this.sessions[0]}async initialize(){try{await this.engine.init(),this.engine.logger.info("POSClient Initialization Success")}catch(e){throw this.engine.logger.info("POSClient Initialization Failure"),this.engine.logger.error(e.message),e}}}const JD=Ba;Se.CLIENT_CONTEXT=Da,Se.CLIENT_STORAGE_OPTIONS=$a,Se.CLIENT_STORAGE_PREFIX=nb,Se.DEFAULT_LOGGER_LEVEL=Ta,Se.DEFAULT_NAMESPACES=cf,Se.IPOSClient=ky,Se.IPOSClientEngine=Ly,Se.MAX_TRANSACTION_STATUS_CHECKS=af,Se.POSClient=JD,Se.POS_CLIENT_VERSION=of,Se.PROTOCOL=sf,Se.PROTOCOL_VERSION=tb,Se.RPC_ERROR_CODES=Pa,Se.RPC_URL=uf,Se.default=Ba,Object.defineProperty(Se,"__esModule",{value:!0})});
|
|
41
41
|
//# sourceMappingURL=index.umd.js.map
|