import{b as ed,a as G,p as at,g as td,c as Ur}from"./react-framework-CvIcIHJY.js";import{e as Ot,B as ie,P as Qu}from"./polyfills-IGlxSZmi.js";import{k as rd,s as id}from"./ethers-CF3RP-Qj.js";var Gs={};/*! *****************************************************************************
Copyright (c) Microsoft Corporation.

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */var jn=function(t,e){return jn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var s in i)i.hasOwnProperty(s)&&(r[s]=i[s])},jn(t,e)};function sd(t,e){jn(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var qn=function(){return qn=Object.assign||function(e){for(var r,i=1,s=arguments.length;i<s;i++){r=arguments[i];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},qn.apply(this,arguments)};function nd(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,i=Object.getOwnPropertySymbols(t);s<i.length;s++)e.indexOf(i[s])<0&&Object.prototype.propertyIsEnumerable.call(t,i[s])&&(r[i[s]]=t[i[s]]);return r}function od(t,e,r,i){var s=arguments.length,n=s<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(n=(s<3?o(n):s>3?o(e,r,n):o(e,r))||n);return s>3&&n&&Object.defineProperty(e,r,n),n}function ad(t,e){return function(r,i){e(r,i,t)}}function cd(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function ud(t,e,r,i){function s(n){return n instanceof r?n:new r(function(o){o(n)})}return new(r||(r=Promise))(function(n,o){function a(l){try{u(i.next(l))}catch(h){o(h)}}function c(l){try{u(i.throw(l))}catch(h){o(h)}}function u(l){l.done?n(l.value):s(l.value).then(a,c)}u((i=i.apply(t,e||[])).next())})}function ld(t,e){var r={label:0,sent:function(){if(n[0]&1)throw n[1];return n[1]},trys:[],ops:[]},i,s,n,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(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=1,s&&(n=u[0]&2?s.return:u[0]?s.throw||((n=s.return)&&n.call(s),0):s.next)&&!(n=n.call(s,u[1])).done)return n;switch(s=0,n&&(u=[u[0]&2,n.value]),u[0]){case 0:case 1:n=u;break;case 4:return r.label++,{value:u[1],done:!1};case 5:r.label++,s=u[1],u=[0];continue;case 7:u=r.ops.pop(),r.trys.pop();continue;default:if(n=r.trys,!(n=n.length>0&&n[n.length-1])&&(u[0]===6||u[0]===2)){r=0;continue}if(u[0]===3&&(!n||u[1]>n[0]&&u[1]<n[3])){r.label=u[1];break}if(u[0]===6&&r.label<n[1]){r.label=n[1],n=u;break}if(n&&r.label<n[2]){r.label=n[2],r.ops.push(u);break}n[2]&&r.ops.pop(),r.trys.pop();continue}u=e.call(t,r)}catch(l){u=[6,l],s=0}finally{i=n=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function hd(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function fd(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function zn(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function el(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),s,n=[],o;try{for(;(e===void 0||e-- >0)&&!(s=i.next()).done;)n.push(s.value)}catch(a){o={error:a}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return n}function dd(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(el(arguments[e]));return t}function pd(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),s=0,e=0;e<r;e++)for(var n=arguments[e],o=0,a=n.length;o<a;o++,s++)i[s]=n[o];return i}function _i(t){return this instanceof _i?(this.v=t,this):new _i(t)}function gd(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){i[f]&&(s[f]=function(p){return new Promise(function(d,y){n.push([f,p,d,y])>1||a(f,p)})})}function a(f,p){try{c(i[f](p))}catch(d){h(n[0][3],d)}}function c(f){f.value instanceof _i?Promise.resolve(f.value.v).then(u,l):h(n[0][2],f)}function u(f){a("next",f)}function l(f){a("throw",f)}function h(f,p){f(p),n.shift(),n.length&&a(n[0][0],n[0][1])}}function yd(t){var e,r;return e={},i("next"),i("throw",function(s){throw s}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(s,n){e[s]=t[s]?function(o){return(r=!r)?{value:_i(t[s](o)),done:s==="return"}:n?n(o):o}:n}}function wd(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof zn=="function"?zn(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(n){r[n]=t[n]&&function(o){return new Promise(function(a,c){o=t[n](o),s(a,c,o.done,o.value)})}}function s(n,o,a,c){Promise.resolve(c).then(function(u){n({value:u,done:a})},o)}}function bd(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function md(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function vd(t){return t&&t.__esModule?t:{default:t}}function Ed(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function xd(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const _d=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return qn},__asyncDelegator:yd,__asyncGenerator:gd,__asyncValues:wd,__await:_i,__awaiter:ud,__classPrivateFieldGet:Ed,__classPrivateFieldSet:xd,__createBinding:hd,__decorate:od,__exportStar:fd,__extends:sd,__generator:ld,__importDefault:vd,__importStar:md,__makeTemplateObject:bd,__metadata:cd,__param:ad,__read:el,__rest:nd,__spread:dd,__spreadArrays:pd,__values:zn},Symbol.toStringTag,{value:"Module"})),Ai=ed(_d);var Ys={},ti={},ya;function Id(){if(ya)return ti;ya=1,Object.defineProperty(ti,"__esModule",{value:!0}),ti.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return ti.delay=t,ti}var wr={},Zs={},br={},wa;function Sd(){return wa||(wa=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 Js={},ba;function Dd(){return ba||(ba=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})(Js)),Js}var ma;function tl(){return ma||(ma=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ai;e.__exportStar(Sd(),t),e.__exportStar(Dd(),t)})(Zs)),Zs}var va;function $d(){if(va)return wr;va=1,Object.defineProperty(wr,"__esModule",{value:!0}),wr.fromMiliseconds=wr.toMiliseconds=void 0;const t=tl();function e(i){return i*t.ONE_THOUSAND}wr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return wr.fromMiliseconds=r,wr}var Ea;function Od(){return Ea||(Ea=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ai;e.__exportStar(Id(),t),e.__exportStar($d(),t)})(Ys)),Ys}var Nr={},xa;function Ad(){if(xa)return Nr;xa=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const s=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:s})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return Nr.Watch=t,Nr.default=t,Nr}var Xs={},ri={},_a;function Pd(){if(_a)return ri;_a=1,Object.defineProperty(ri,"__esModule",{value:!0}),ri.IWatch=void 0;class t{}return ri.IWatch=t,ri}var Ia;function Td(){return Ia||(Ia=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),Ai.__exportStar(Pd(),t)})(Xs)),Xs}var Sa;function Rd(){return Sa||(Sa=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ai;e.__exportStar(Od(),t),e.__exportStar(Ad(),t),e.__exportStar(Td(),t),e.__exportStar(tl(),t)})(Gs)),Gs}var F=Rd();class Tr{}let Bd=class extends Tr{constructor(e){super()}};const Da=F.FIVE_SECONDS,Rr={pulse:"heartbeat_pulse"};let Cd=class rl extends Bd{constructor(e){super(e),this.events=new Ot.EventEmitter,this.interval=Da,this.interval=e?.interval||Da}static async init(e){const r=new rl(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),F.toMiliseconds(this.interval))}pulse(){this.events.emit(Rr.pulse)}};const Ud=/"(?:_|\\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*:/,Nd=/"(?: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*:/,kd=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function Fd(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){Ld(t);return}return e}function Ld(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function qi(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.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(!kd.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(Ud.test(t)||Nd.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,Fd)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function Md(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function xe(t,...e){try{return Md(t(...e))}catch(r){return Promise.reject(r)}}function jd(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function qd(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function is(t){if(jd(t))return String(t);if(qd(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return is(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Vn="base64:";function zd(t){return typeof t=="string"?t:Vn+Hd(t)}function Vd(t){return typeof t!="string"||!t.startsWith(Vn)?t:Kd(t.slice(Vn.length))}function Kd(t){return globalThis.Buffer?ie.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Hd(t){return globalThis.Buffer?ie.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function je(t){return t&&t.split("?")[0]?.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,"")||""}function Wd(...t){return je(t.join(":"))}function zi(t){return t=je(t),t?t+":":""}function Gd(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function Yd(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const Zd="memory",Jd=()=>{const t=new Map;return{name:Zd,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Xd(t={}){const e={mounts:{"":t.driver||Jd()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=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[""]}},i=(u,l)=>e.mountpoints.filter(h=>h.startsWith(u)||l&&u.startsWith(h)).map(h=>({relativeBase:u.length>h.length?u.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),s=(u,l)=>{if(e.watching){l=je(l);for(const h of e.watchListeners)h(u,l)}},n=async()=>{if(!e.watching){e.watching=!0;for(const u in e.mounts)e.unwatch[u]=await $a(e.mounts[u],s,u)}},o=async()=>{if(e.watching){for(const u in e.unwatch)await e.unwatch[u]();e.unwatch={},e.watching=!1}},a=(u,l,h)=>{const f=new Map,p=d=>{let y=f.get(d.base);return y||(y={driver:d.driver,base:d.base,items:[]},f.set(d.base,y)),y};for(const d of u){const y=typeof d=="string",g=je(y?d:d.key),b=y?void 0:d.value,m=y||!d.options?l:{...l,...d.options},w=r(g);p(w).items.push({key:g,value:b,relativeKey:w.relativeKey,options:m})}return Promise.all([...f.values()].map(d=>h(d))).then(d=>d.flat())},c={hasItem(u,l={}){u=je(u);const{relativeKey:h,driver:f}=r(u);return xe(f.hasItem,h,l)},getItem(u,l={}){u=je(u);const{relativeKey:h,driver:f}=r(u);return xe(f.getItem,h,l).then(p=>qi(p))},getItems(u,l={}){return a(u,l,h=>h.driver.getItems?xe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),l).then(f=>f.map(p=>({key:Wd(h.base,p.key),value:qi(p.value)}))):Promise.all(h.items.map(f=>xe(h.driver.getItem,f.relativeKey,f.options).then(p=>({key:f.key,value:qi(p)})))))},getItemRaw(u,l={}){u=je(u);const{relativeKey:h,driver:f}=r(u);return f.getItemRaw?xe(f.getItemRaw,h,l):xe(f.getItem,h,l).then(p=>Vd(p))},async setItem(u,l,h={}){if(l===void 0)return c.removeItem(u);u=je(u);const{relativeKey:f,driver:p}=r(u);p.setItem&&(await xe(p.setItem,f,is(l),h),p.watch||s("update",u))},async setItems(u,l){await a(u,l,async h=>{if(h.driver.setItems)return xe(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:is(f.value),options:f.options})),l);h.driver.setItem&&await Promise.all(h.items.map(f=>xe(h.driver.setItem,f.relativeKey,is(f.value),f.options)))})},async setItemRaw(u,l,h={}){if(l===void 0)return c.removeItem(u,h);u=je(u);const{relativeKey:f,driver:p}=r(u);if(p.setItemRaw)await xe(p.setItemRaw,f,l,h);else if(p.setItem)await xe(p.setItem,f,zd(l),h);else return;p.watch||s("update",u)},async removeItem(u,l={}){typeof l=="boolean"&&(l={removeMeta:l}),u=je(u);const{relativeKey:h,driver:f}=r(u);f.removeItem&&(await xe(f.removeItem,h,l),(l.removeMeta||l.removeMata)&&await xe(f.removeItem,h+"$",l),f.watch||s("remove",u))},async getMeta(u,l={}){typeof l=="boolean"&&(l={nativeOnly:l}),u=je(u);const{relativeKey:h,driver:f}=r(u),p=Object.create(null);if(f.getMeta&&Object.assign(p,await xe(f.getMeta,h,l)),!l.nativeOnly){const d=await xe(f.getItem,h+"$",l).then(y=>qi(y));d&&typeof d=="object"&&(typeof d.atime=="string"&&(d.atime=new Date(d.atime)),typeof d.mtime=="string"&&(d.mtime=new Date(d.mtime)),Object.assign(p,d))}return p},setMeta(u,l,h={}){return this.setItem(u+"$",l,h)},removeMeta(u,l={}){return this.removeItem(u+"$",l)},async getKeys(u,l={}){u=zi(u);const h=i(u,!0);let f=[];const p=[];let d=!0;for(const g of h){g.driver.flags?.maxDepth||(d=!1);const b=await xe(g.driver.getKeys,g.relativeBase,l);for(const m of b){const w=g.mountpoint+je(m);f.some(I=>w.startsWith(I))||p.push(w)}f=[g.mountpoint,...f.filter(m=>!m.startsWith(g.mountpoint))]}const y=l.maxDepth!==void 0&&!d;return p.filter(g=>(!y||Gd(g,l.maxDepth))&&Yd(g,u))},async clear(u,l={}){u=zi(u),await Promise.all(i(u,!1).map(async h=>{if(h.driver.clear)return xe(h.driver.clear,h.relativeBase,l);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",l);return Promise.all(f.map(p=>h.driver.removeItem(p,l)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(u=>Oa(u)))},async watch(u){return await n(),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=zi(u),u&&e.mounts[u])throw new Error(`already mounted at ${u}`);return u&&(e.mountpoints.push(u),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[u]=l,e.watching&&Promise.resolve($a(l,s,u)).then(h=>{e.unwatch[u]=h}).catch(console.error),c},async unmount(u,l=!0){u=zi(u),!(!u||!e.mounts[u])&&(e.watching&&u in e.unwatch&&(e.unwatch[u]?.(),delete e.unwatch[u]),l&&await Oa(e.mounts[u]),e.mountpoints=e.mountpoints.filter(h=>h!==u),delete e.mounts[u])},getMount(u=""){u=je(u)+":";const l=r(u);return{driver:l.driver,base:l.base}},getMounts(u="",l={}){return u=je(u),i(u,l.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(u,l={})=>c.getKeys(u,l),get:(u,l={})=>c.getItem(u,l),set:(u,l,h={})=>c.setItem(u,l,h),has:(u,l={})=>c.hasItem(u,l),del:(u,l={})=>c.removeItem(u,l),remove:(u,l={})=>c.removeItem(u,l)};return c}function $a(t,e,r){return t.watch?t.watch((i,s)=>e(i,r+s)):()=>{}}async function Oa(t){typeof t.dispose=="function"&&await xe(t.dispose)}function pr(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function To(t,e){let r;const i=()=>{if(r)return r;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),r=pr(s),r.then(n=>{n.onclose=()=>r=void 0},()=>{}),r};return(s,n)=>i().then(o=>n(o.transaction(e,s).objectStore(e)))}let Qs;function Pi(){return Qs||(Qs=To("keyval-store","keyval")),Qs}function Kn(t,e=Pi()){return e("readonly",r=>pr(r.get(t)))}function il(t,e,r=Pi()){return r("readwrite",i=>(i.put(e,t),pr(i.transaction)))}function sl(t,e=Pi()){return e("readwrite",r=>(r.delete(t),pr(r.transaction)))}function nl(t=Pi()){return t("readwrite",e=>(e.clear(),pr(e.transaction)))}function Qd(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},pr(t.transaction)}function ol(t=Pi()){return t("readonly",e=>{if(e.getAllKeys)return pr(e.getAllKeys());const r=[];return Qd(e,i=>r.push(i.key)).then(()=>r)})}const ES=Object.freeze(Object.defineProperty({__proto__:null,clear:nl,createStore:To,del:sl,get:Kn,keys:ol,promisifyRequest:pr,set:il},Symbol.toStringTag,{value:"Module"})),ep=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),tp=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,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,s)=>typeof s=="string"&&s.match(/^\d+n$/)?BigInt(s.substring(0,s.length-1)):s)};function Gr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return tp(t)}catch{return t}}function Ti(t){return typeof t=="string"?t:ep(t)||""}const rp="idb-keyval";var ip=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=s=>e+s;let i;return t.dbName&&t.storeName&&(i=To(t.dbName,t.storeName)),{name:rp,options:t,async hasItem(s){return!(typeof await Kn(r(s),i)>"u")},async getItem(s){return await Kn(r(s),i)??null},setItem(s,n){return il(r(s),n,i)},removeItem(s){return sl(r(s),i)},getKeys(){return ol(i)},clear(){return nl(i)}}};const sp="WALLET_CONNECT_V2_INDEXED_DB",np="keyvaluestorage";let op=class{constructor(){this.indexedDb=Xd({driver:ip({dbName:sp,storeName:np})})}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 r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,Ti(r))}async removeItem(e){await this.indexedDb.removeItem(e)}};var en=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof G<"u"?G:typeof self<"u"?self:{},ss={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof en<"u"&&en.localStorage?ss.exports=en.localStorage:typeof window<"u"&&window.localStorage?ss.exports=window.localStorage:ss.exports=new e})();function ap(t){var e;return[t[0],Gr((e=t[1])!=null?e:"")]}let cp=class{constructor(){this.localStorage=ss.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(ap)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return Gr(r)}async setItem(e,r){this.localStorage.setItem(e,Ti(r))}async removeItem(e){this.localStorage.removeItem(e)}};const up="wc_storage_version",Aa=1,lp=async(t,e,r)=>{const i=up,s=await e.getItem(i);if(s&&s>=Aa){r(e);return}const n=await t.getKeys();if(!n.length){r(e);return}const o=[];for(;n.length;){const a=n.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(i,Aa),r(e),hp(t,o)},hp=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let fp=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new cp;this.storage=e;try{const r=new op;lp(e,r,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,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var St={exports:{}};function dp(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var pp=gp;function gp(t,e,r){var i=r&&r.stringify||dp,s=1;if(typeof t=="object"&&t!==null){var n=e.length+s;if(n===1)return t;var o=new Array(n);o[0]=i(t);for(var a=1;a<n;a++)o[a]=i(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-s,h=-1,f=t&&t.length||0,p=0;p<f;){if(t.charCodeAt(p)===37&&p+1<f){switch(h=h>-1?h:0,t.charCodeAt(p+1)){case 100:case 102:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Number(e[l]),h=p+2,p++;break;case 105:if(l>=c||e[l]==null)break;h<p&&(u+=t.slice(h,p)),u+=Math.floor(Number(e[l])),h=p+2,p++;break;case 79:case 111:case 106:if(l>=c||e[l]===void 0)break;h<p&&(u+=t.slice(h,p));var d=typeof e[l];if(d==="string"){u+="'"+e[l]+"'",h=p+2,p++;break}if(d==="function"){u+=e[l].name||"<anonymous>",h=p+2,p++;break}u+=i(e[l]),h=p+2,p++;break;case 115:if(l>=c)break;h<p&&(u+=t.slice(h,p)),u+=String(e[l]),h=p+2,p++;break;case 37:h<p&&(u+=t.slice(h,p)),u+="%",h=p+2,p++,l--;break}++l}++p}return h===-1?t:(h<f&&(u+=t.slice(h)),u)}const Pa=pp;St.exports=qt;const Ii=Pp().console||{},yp={mapHttpRequest:Vi,mapHttpResponse:Vi,wrapRequestSerializer:tn,wrapResponseSerializer:tn,wrapErrorSerializer:tn,req:Vi,res:Vi,err:Ra,errWithCause:Ra};function ar(t,e){return t==="silent"?1/0:e.levels.values[t]}const Ro=Symbol("pino.logFuncs"),Hn=Symbol("pino.hierarchy"),wp={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function Ta(t,e){const r={logger:e,parent:t[Hn]};e[Hn]=r}function bp(t,e,r){const i={};e.forEach(s=>{i[s]=r[s]?r[s]:Ii[s]||Ii[wp[s]||"log"]||Kr}),t[Ro]=i}function mp(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function qt(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 r=t.browser.write||Ii;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},s=mp(t.browser.serialize,i);let n=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(n=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof r=="function"&&a.forEach(function(y){r[y]=r}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",u=Object.create(r);u.log||(u.log=Kr),bp(u,a,r),Ta({},u),Object.defineProperty(u,"levelVal",{get:h}),Object.defineProperty(u,"level",{get:f,set:p});const l={transmit:e,serialize:s,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:$p(t),messageKey:t.messageKey||"msg",onChild:t.onChild||Kr};u.levels=vp(t),u.level=c,u.isLevelEnabled=function(y){return this.levels.values[y]?this.levels.values[y]>=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=Kr,u.serializers=i,u._serialize=s,u._stdErrSerialize=n,u.child=function(...y){return d.call(this,l,...y)},e&&(u._logEvent=Wn());function h(){return ar(this.level,this)}function f(){return this._level}function p(y){if(y!=="silent"&&!this.levels.values[y])throw Error("unknown level "+y);this._level=y,mr(this,l,u,"error"),mr(this,l,u,"fatal"),mr(this,l,u,"warn"),mr(this,l,u,"info"),mr(this,l,u,"debug"),mr(this,l,u,"trace"),o.forEach(g=>{mr(this,l,u,g)})}function d(y,g,b){if(!g)throw new Error("missing bindings for child Pino");b=b||{},s&&g.serializers&&(b.serializers=g.serializers);const m=b.serializers;if(s&&m){var w=Object.assign({},i,m),I=t.browser.serialize===!0?Object.keys(w):s;delete g.serializers,Bo([g],I,w,this._stdErrSerialize)}function O(B){this._childLevel=(B._childLevel|0)+1,this.bindings=g,w&&(this.serializers=w,this._serialize=I),e&&(this._logEvent=Wn([].concat(B._logEvent.bindings,g)))}O.prototype=this;const T=new O(this);return Ta(this,T),T.child=function(...B){return d.call(this,y,...B)},T.level=b.level||this.level,y.onChild(T),T}return u}function vp(t){const e=t.customLevels||{},r=Object.assign({},qt.levels.values,e),i=Object.assign({},qt.levels.labels,Ep(e));return{values:r,labels:i}}function Ep(t){const e={};return Object.keys(t).forEach(function(r){e[t[r]]=r}),e}qt.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"}},qt.stdSerializers=yp,qt.stdTimeFunctions=Object.assign({},{nullTime:al,epochTime:cl,unixTime:Op,isoTime:Ap});function xp(t){const e=[];t.bindings&&e.push(t.bindings);let r=t[Hn];for(;r.parent;)r=r.parent,r.logger.bindings&&e.push(r.logger.bindings);return e.reverse()}function mr(t,e,r,i){if(Object.defineProperty(t,i,{value:ar(t.level,r)>ar(i,r)?Kr:r[Ro][i],writable:!0,enumerable:!0,configurable:!0}),t[i]===Kr){if(!e.transmit)return;const n=e.transmit.level||t.level,o=ar(n,r);if(ar(i,r)<o)return}t[i]=Ip(t,e,r,i);const s=xp(t);s.length!==0&&(t[i]=_p(s,t[i]))}function _p(t,e){return function(){return e.apply(this,[...t,...arguments])}}function Ip(t,e,r,i){return(function(s){return function(){const n=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===Ii?Ii:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var u=!1;if(e.serialize&&(Bo(o,this._serialize,this.serializers,this._stdErrSerialize),u=!0),e.asObject||e.formatters?s.call(a,...Sp(this,i,o,n,e)):s.apply(a,o),e.transmit){const l=e.transmit.level||t._level,h=ar(l,r),f=ar(i,r);if(f<h)return;Dp(this,{ts:n,methodLevel:i,methodValue:f,transmitValue:r.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:ar(t._level,r)},o,u)}}})(t[Ro][i])}function Sp(t,e,r,i,s){const{level:n,log:o=h=>h}=s.formatters||{},a=r.slice();let c=a[0];const u={};let l=(t._childLevel|0)+1;if(l<1&&(l=1),i&&(u.time=i),n){const h=n(e,t.levels.values[e]);Object.assign(u,h)}else u.level=t.levels.values[e];if(s.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?Pa(a.shift(),a):void 0}else typeof c=="string"&&(c=Pa(a.shift(),a));return c!==void 0&&(u[s.messageKey]=c),[o(u)]}}function Bo(t,e,r,i){for(const s in t)if(i&&t[s]instanceof Error)t[s]=qt.stdSerializers.err(t[s]);else if(typeof t[s]=="object"&&!Array.isArray(t[s])&&e)for(const n in t[s])e.indexOf(n)>-1&&n in r&&(t[s][n]=r[n](t[s][n]))}function Dp(t,e,r,i=!1){const s=e.send,n=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,u=t._logEvent.bindings;i||Bo(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=n,t._logEvent.messages=r.filter(function(l){return u.indexOf(l)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,s(o,t._logEvent,c),t._logEvent=Wn(u)}function Wn(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function Ra(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function $p(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?al:cl}function Vi(){return{}}function tn(t){return t}function Kr(){}function al(){return!1}function cl(){return Date.now()}function Op(){return Math.round(Date.now()/1e3)}function Ap(){return new Date(Date.now()).toISOString()}function Pp(){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)||{}}}St.exports.default=qt;St.exports.pino=qt;const Tp={level:"info"},Os="custom_context",Co=1e3*1024;var Rp=Object.defineProperty,Bp=(t,e,r)=>e in t?Rp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sr=(t,e,r)=>Bp(t,typeof e!="symbol"?e+"":e,r);let Cp=class{constructor(e){sr(this,"nodeValue"),sr(this,"sizeInBytes"),sr(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}},Ba=class{constructor(e){sr(this,"lengthInNodes"),sr(this,"sizeInBytes"),sr(this,"head"),sr(this,"tail"),sr(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new Cp(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.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 r=this.head;for(;r!==null;)e.push(r.value),r=r.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 r=e.value;return e=e.next,{done:!1,value:r}}}}};const Up=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r);function Ca(t){return typeof t=="string"?t:Up(t)||""}var Np=Object.defineProperty,kp=(t,e,r)=>e in t?Np(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ki=(t,e,r)=>kp(t,typeof e!="symbol"?e+"":e,r);let ul=class{constructor(e,r=Co){Ki(this,"logs"),Ki(this,"level"),Ki(this,"levelValue"),Ki(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=St.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new Ba(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===St.exports.levels.values.error?console.error(e):r===St.exports.levels.values.warn?console.warn(e):r===St.exports.levels.values.debug?console.debug(e):r===St.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Ca({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new Ba(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Ca({extraMetadata:e})),new Blob(r,{type:"application/json"})}};var Fp=Object.defineProperty,Lp=(t,e,r)=>e in t?Fp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mp=(t,e,r)=>Lp(t,e+"",r);let jp=class{constructor(e,r=Co){Mp(this,"baseChunkLogger"),this.baseChunkLogger=new ul(e,r)}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 r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}};var qp=Object.defineProperty,zp=(t,e,r)=>e in t?qp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Vp=(t,e,r)=>zp(t,e+"",r);let Kp=class{constructor(e,r=Co){Vp(this,"baseChunkLogger"),this.baseChunkLogger=new ul(e,r)}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 Hp=Object.defineProperty,Wp=Object.defineProperties,Gp=Object.getOwnPropertyDescriptors,Ua=Object.getOwnPropertySymbols,Yp=Object.prototype.hasOwnProperty,Zp=Object.prototype.propertyIsEnumerable,Na=(t,e,r)=>e in t?Hp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ur=(t,e)=>{for(var r in e||(e={}))Yp.call(e,r)&&Na(t,r,e[r]);if(Ua)for(var r of Ua(e))Zp.call(e,r)&&Na(t,r,e[r]);return t},lr=(t,e)=>Wp(t,Gp(e));function Jp(t){return lr(ur({},t),{level:t?.level||Tp.level})}function Xp(t,e,r=Os){return t[r]=e,t}function We(t,e=Os){return t[e]||""}function Qp(t,e,r=Os){const i=We(t,r);return i.trim()?`${i}/${e}`:e}function et(t,e,r=Os){const i=Qp(t,e,r),s=t.child({context:i});return Xp(s,i,r)}function eg(t){var e,r;const i=new jp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:St.exports(lr(ur({},t.opts),{level:"trace",browser:lr(ur({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})})),chunkLoggerController:i}}function tg(t){var e,r;const i=new Kp((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:St.exports(lr(ur({},t.opts),{level:"trace",browser:lr(ur({},(r=t.opts)==null?void 0:r.browser),{write:s=>i.write(s)})}),i),chunkLoggerController:i}}function ll(t){var e;if(typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string")return{logger:t.loggerOverride,chunkLoggerController:null};const r=lr(ur({},t.opts),{level:typeof t.loggerOverride=="string"?t.loggerOverride:(e=t.opts)==null?void 0:e.level});return typeof window<"u"?eg(lr(ur({},t),{opts:r})):tg(lr(ur({},t),{opts:r}))}var rg=Object.defineProperty,ig=(t,e,r)=>e in t?rg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ka=(t,e,r)=>ig(t,typeof e!="symbol"?e+"":e,r);let sg=class extends Tr{constructor(e){super(),this.opts=e,ka(this,"protocol","wc"),ka(this,"version",2)}};var ng=Object.defineProperty,og=(t,e,r)=>e in t?ng(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ag=(t,e,r)=>og(t,e+"",r);class cg extends Tr{constructor(e,r){super(),this.core=e,this.logger=r,ag(this,"records",new Map)}}class ug{constructor(e,r){this.logger=e,this.core=r}}class lg extends Tr{constructor(e,r){super(),this.relayer=e,this.logger=r}}let hg=class extends Tr{constructor(e){super()}},fg=class{constructor(e,r,i,s){this.core=e,this.logger=r,this.name=i}},dg=class extends Tr{constructor(e,r){super(),this.relayer=e,this.logger=r}},pg=class extends Tr{constructor(e,r){super(),this.core=e,this.logger=r}},gg=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}};class yg{constructor(e,r){this.projectId=e,this.logger=r}}class wg{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}}var bg=Object.defineProperty,mg=(t,e,r)=>e in t?bg(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Fa=(t,e,r)=>mg(t,typeof e!="symbol"?e+"":e,r);let vg=class{constructor(e){this.opts=e,Fa(this,"protocol","wc"),Fa(this,"version",2)}},Eg=class{constructor(e){this.client=e}};function xg(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function hl(t,...e){if(!xg(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 La(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 _g(t,e){hl(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const kr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rn=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function Ig(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function fl(t){return typeof t=="string"&&(t=Ig(t)),hl(t),t}let Sg=class{clone(){return this._cloneInto()}};function Dg(t){const e=i=>t().update(fl(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function dl(t=32){if(kr&&typeof kr.getRandomValues=="function")return kr.getRandomValues(new Uint8Array(t));if(kr&&typeof kr.randomBytes=="function")return kr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function $g(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}let Og=class extends Sg{constructor(e,r,i,s){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=rn(this.buffer)}update(e){La(this);const{view:r,buffer:i,blockLen:s}=this;e=fl(e);const n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=rn(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){La(this),_g(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;$g(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=rn(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.length=s,e.pos=a,e.finished=n,e.destroyed=o,s%r&&e.buffer.set(i),e}};const Hi=BigInt(2**32-1),Gn=BigInt(32);function pl(t,e=!1){return e?{h:Number(t&Hi),l:Number(t>>Gn&Hi)}:{h:Number(t>>Gn&Hi)|0,l:Number(t&Hi)|0}}function Ag(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let s=0;s<t.length;s++){const{h:n,l:o}=pl(t[s],e);[r[s],i[s]]=[n,o]}return[r,i]}const Pg=(t,e)=>BigInt(t>>>0)<<Gn|BigInt(e>>>0),Tg=(t,e,r)=>t>>>r,Rg=(t,e,r)=>t<<32-r|e>>>r,Bg=(t,e,r)=>t>>>r|e<<32-r,Cg=(t,e,r)=>t<<32-r|e>>>r,Ug=(t,e,r)=>t<<64-r|e>>>r-32,Ng=(t,e,r)=>t>>>r-32|e<<64-r,kg=(t,e)=>e,Fg=(t,e)=>t,Lg=(t,e,r)=>t<<r|e>>>32-r,Mg=(t,e,r)=>e<<r|t>>>32-r,jg=(t,e,r)=>e<<r-32|t>>>64-r,qg=(t,e,r)=>t<<r-32|e>>>64-r;function zg(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Vg=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Kg=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,Hg=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Wg=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,Gg=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Yg=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,Z={fromBig:pl,split:Ag,toBig:Pg,shrSH:Tg,shrSL:Rg,rotrSH:Bg,rotrSL:Cg,rotrBH:Ug,rotrBL:Ng,rotr32H:kg,rotr32L:Fg,rotlSH:Lg,rotlSL:Mg,rotlBH:jg,rotlBL:qg,add:zg,add3L:Vg,add3H:Kg,add4L:Hg,add4H:Wg,add5H:Yg,add5L:Gg},[Zg,Jg]=Z.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))),Ht=new Uint32Array(80),Wt=new Uint32Array(80);let Xg=class extends Og{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:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:g}=this;return[e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g]}set(e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=g|0}process(e,r){for(let w=0;w<16;w++,r+=4)Ht[w]=e.getUint32(r),Wt[w]=e.getUint32(r+=4);for(let w=16;w<80;w++){const I=Ht[w-15]|0,O=Wt[w-15]|0,T=Z.rotrSH(I,O,1)^Z.rotrSH(I,O,8)^Z.shrSH(I,O,7),B=Z.rotrSL(I,O,1)^Z.rotrSL(I,O,8)^Z.shrSL(I,O,7),N=Ht[w-2]|0,$=Wt[w-2]|0,M=Z.rotrSH(N,$,19)^Z.rotrBH(N,$,61)^Z.shrSH(N,$,6),q=Z.rotrSL(N,$,19)^Z.rotrBL(N,$,61)^Z.shrSL(N,$,6),R=Z.add4L(B,q,Wt[w-7],Wt[w-16]),_=Z.add4H(R,T,M,Ht[w-7],Ht[w-16]);Ht[w]=_|0,Wt[w]=R|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:g,Hh:b,Hl:m}=this;for(let w=0;w<80;w++){const I=Z.rotrSH(h,f,14)^Z.rotrSH(h,f,18)^Z.rotrBH(h,f,41),O=Z.rotrSL(h,f,14)^Z.rotrSL(h,f,18)^Z.rotrBL(h,f,41),T=h&p^~h&y,B=f&d^~f&g,N=Z.add5L(m,O,B,Jg[w],Wt[w]),$=Z.add5H(N,b,I,T,Zg[w],Ht[w]),M=N|0,q=Z.rotrSH(i,s,28)^Z.rotrBH(i,s,34)^Z.rotrBH(i,s,39),R=Z.rotrSL(i,s,28)^Z.rotrBL(i,s,34)^Z.rotrBL(i,s,39),_=i&n^i&a^n&a,S=s&o^s&c^o&c;b=y|0,m=g|0,y=p|0,g=d|0,p=h|0,d=f|0,{h,l:f}=Z.add(u|0,l|0,$|0,M|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const E=Z.add3L(M,R,S);i=Z.add3H(E,$,q,_),s=E|0}({h:i,l:s}=Z.add(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=Z.add(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=Z.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=Z.add(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=Z.add(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=Z.add(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:g}=Z.add(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:m}=Z.add(this.Hh|0,this.Hl|0,b|0,m|0),this.set(i,s,n,o,a,c,u,l,h,f,p,d,y,g,b,m)}roundClean(){Ht.fill(0),Wt.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 Qg=Dg(()=>new Xg);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Uo=BigInt(0),gl=BigInt(1),ey=BigInt(2);function No(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function ko(t){if(!No(t))throw new Error("Uint8Array expected")}function sn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const ty=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Fo(t){ko(t);let e="";for(let r=0;r<t.length;r++)e+=ty[t[r]];return e}function yl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Uo:BigInt("0x"+t)}const Pt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ma(t){if(t>=Pt._0&&t<=Pt._9)return t-Pt._0;if(t>=Pt.A&&t<=Pt.F)return t-(Pt.A-10);if(t>=Pt.a&&t<=Pt.f)return t-(Pt.a-10)}function wl(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Ma(t.charCodeAt(n)),a=Ma(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function ry(t){return yl(Fo(t))}function ns(t){return ko(t),yl(Fo(Uint8Array.from(t).reverse()))}function bl(t,e){return wl(t.toString(16).padStart(e*2,"0"))}function Yn(t,e){return bl(t,e).reverse()}function Tt(t,e,r){let i;if(typeof e=="string")try{i=wl(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(No(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}function ja(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];ko(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}const nn=t=>typeof t=="bigint"&&Uo<=t;function iy(t,e,r){return nn(t)&&nn(e)&&nn(r)&&e<=t&&t<r}function ii(t,e,r,i){if(!iy(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function sy(t){let e;for(e=0;t>Uo;t>>=gl,e+=1);return e}const ny=t=>(ey<<BigInt(t-1))-gl,oy={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"||No(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 Lo(t,e,r={}){const i=(s,n,o)=>{const a=oy[n];if(typeof a!="function")throw new Error("invalid validator function");const c=t[s];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(s)+" is invalid. Expected "+n+", got "+c)};for(const[s,n]of Object.entries(e))i(s,n,!1);for(const[s,n]of Object.entries(r))i(s,n,!0);return t}function qa(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const Ie=BigInt(0),de=BigInt(1),_r=BigInt(2),ay=BigInt(3),Zn=BigInt(4),za=BigInt(5),Va=BigInt(8);function me(t,e){const r=t%e;return r>=Ie?r:e+r}function cy(t,e,r){if(e<Ie)throw new Error("invalid exponent, negatives unsupported");if(r<=Ie)throw new Error("invalid modulus");if(r===de)return Ie;let i=de;for(;e>Ie;)e&de&&(i=i*t%r),t=t*t%r,e>>=de;return i}function bt(t,e,r){let i=t;for(;e-- >Ie;)i*=i,i%=r;return i}function Ka(t,e){if(t===Ie)throw new Error("invert: expected non-zero number");if(e<=Ie)throw new Error("invert: expected positive modulus, got "+e);let r=me(t,e),i=e,s=Ie,n=de;for(;r!==Ie;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==de)throw new Error("invert: does not exist");return me(s,e)}function uy(t){const e=(t-de)/_r;let r,i,s;for(r=t-de,i=0;r%_r===Ie;r/=_r,i++);for(s=_r;s<t&&cy(s,e,t)!==t-de;s++)if(s>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+de)/Zn;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 n=(r+de)/_r;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,u=o.pow(o.mul(o.ONE,s),r),l=o.pow(a,n),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let d=o.sqr(h);f<c&&!o.eql(d,o.ONE);f++)d=o.sqr(d);const p=o.pow(u,de<<BigInt(c-f-1));u=o.sqr(p),l=o.mul(l,p),h=o.mul(h,u),c=f}return l}}function ly(t){if(t%Zn===ay){const e=(t+de)/Zn;return function(r,i){const s=r.pow(i,e);if(!r.eql(r.sqr(s),i))throw new Error("Cannot find square root");return s}}if(t%Va===za){const e=(t-za)/Va;return function(r,i){const s=r.mul(i,_r),n=r.pow(s,e),o=r.mul(i,n),a=r.mul(r.mul(o,_r),n),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return uy(t)}const hy=(t,e)=>(me(t,e)&de)===de,fy=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function dy(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=fy.reduce((i,s)=>(i[s]="function",i),e);return Lo(t,r)}function py(t,e,r){if(r<Ie)throw new Error("invalid exponent, negatives unsupported");if(r===Ie)return t.ONE;if(r===de)return e;let i=t.ONE,s=e;for(;r>Ie;)r&de&&(i=t.mul(i,s)),s=t.sqr(s),r>>=de;return i}function gy(t,e){const r=new Array(e.length),i=e.reduce((n,o,a)=>t.is0(o)?n:(r[a]=n,t.mul(n,o)),t.ONE),s=t.inv(i);return e.reduceRight((n,o,a)=>t.is0(o)?n:(r[a]=t.mul(n,r[a]),t.mul(n,o)),s),r}function ml(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function vl(t,e,r=!1,i={}){if(t<=Ie)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:s,nByteLength:n}=ml(t,e);if(n>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:s,BYTES:n,MASK:ny(s),ZERO:Ie,ONE:de,create:c=>me(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ie<=c&&c<t},is0:c=>c===Ie,isOdd:c=>(c&de)===de,neg:c=>me(-c,t),eql:(c,u)=>c===u,sqr:c=>me(c*c,t),add:(c,u)=>me(c+u,t),sub:(c,u)=>me(c-u,t),mul:(c,u)=>me(c*u,t),pow:(c,u)=>py(a,c,u),div:(c,u)=>me(c*Ka(u,t),t),sqrN:c=>c*c,addN:(c,u)=>c+u,subN:(c,u)=>c-u,mulN:(c,u)=>c*u,inv:c=>Ka(c,t),sqrt:i.sqrt||(c=>(o||(o=ly(t)),o(a,c))),invertBatch:c=>gy(a,c),cmov:(c,u,l)=>l?u:c,toBytes:c=>r?Yn(c,n):bl(c,n),fromBytes:c=>{if(c.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+c.length);return r?ns(c):ry(c)}});return Object.freeze(a)}const Ha=BigInt(0),Wi=BigInt(1);function on(t,e){const r=e.negate();return t?r:e}function El(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function an(t,e){El(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function yy(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function wy(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const cn=new WeakMap,xl=new WeakMap;function un(t){return xl.get(t)||1}function by(t,e){return{constTimeNegate:on,hasPrecomputes(r){return un(r)!==1},unsafeLadder(r,i,s=t.ZERO){let n=r;for(;i>Ha;)i&Wi&&(s=s.add(n)),n=n.double(),i>>=Wi;return s},precomputeWindow(r,i){const{windows:s,windowSize:n}=an(i,e),o=[];let a=r,c=a;for(let u=0;u<s;u++){c=a,o.push(c);for(let l=1;l<n;l++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(r,i,s){const{windows:n,windowSize:o}=an(r,e);let a=t.ZERO,c=t.BASE;const u=BigInt(2**r-1),l=2**r,h=BigInt(r);for(let f=0;f<n;f++){const p=f*o;let d=Number(s&u);s>>=h,d>o&&(d-=l,s+=Wi);const y=p,g=p+Math.abs(d)-1,b=f%2!==0,m=d<0;d===0?c=c.add(on(b,i[y])):a=a.add(on(m,i[g]))}return{p:a,f:c}},wNAFUnsafe(r,i,s,n=t.ZERO){const{windows:o,windowSize:a}=an(r,e),c=BigInt(2**r-1),u=2**r,l=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(s===Ha)break;let p=Number(s&c);if(s>>=l,p>a&&(p-=u,s+=Wi),p===0)continue;let d=i[f+Math.abs(p)-1];p<0&&(d=d.negate()),n=n.add(d)}return n},getPrecomputes(r,i,s){let n=cn.get(i);return n||(n=this.precomputeWindow(i,r),r!==1&&cn.set(i,s(n))),n},wNAFCached(r,i,s){const n=un(r);return this.wNAF(n,this.getPrecomputes(n,r,s),i)},wNAFCachedUnsafe(r,i,s,n){const o=un(r);return o===1?this.unsafeLadder(r,i,n):this.wNAFUnsafe(o,this.getPrecomputes(o,r,s),i,n)},setWindowSize(r,i){El(i,e),xl.set(r,i),cn.delete(r)}}}function my(t,e,r,i){if(yy(r,t),wy(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const s=t.ZERO,n=sy(BigInt(r.length)),o=n>12?n-3:n>4?n-2:n?2:1,a=(1<<o)-1,c=new Array(a+1).fill(s),u=Math.floor((e.BITS-1)/o)*o;let l=s;for(let h=u;h>=0;h-=o){c.fill(s);for(let p=0;p<i.length;p++){const d=i[p],y=Number(d>>BigInt(h)&BigInt(a));c[y]=c[y].add(r[p])}let f=s;for(let p=c.length-1,d=s;p>0;p--)d=d.add(c[p]),f=f.add(d);if(l=l.add(f),h!==0)for(let p=0;p<o;p++)l=l.double()}return l}function vy(t){return dy(t.Fp),Lo(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ml(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const ut=BigInt(0),Le=BigInt(1),Gi=BigInt(2),Ey=BigInt(8),xy={zip215:!0};function _y(t){const e=vy(t);return Lo(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Iy(t){const e=_y(t),{Fp:r,n:i,prehash:s,hash:n,randomBytes:o,nByteLength:a,h:c}=e,u=Gi<<BigInt(a*8)-Le,l=r.create,h=vl(e.n,e.nBitLength),f=e.uvRatio||((E,v)=>{try{return{isValid:!0,value:r.sqrt(E*r.inv(v))}}catch{return{isValid:!1,value:ut}}}),p=e.adjustScalarBytes||(E=>E),d=e.domain||((E,v,D)=>{if(sn("phflag",D),v.length||D)throw new Error("Contexts/pre-hash are not supported");return E});function y(E,v){ii("coordinate "+E,v,ut,u)}function g(E){if(!(E instanceof w))throw new Error("ExtendedPoint expected")}const b=qa((E,v)=>{const{ex:D,ey:P,ez:x}=E,A=E.is0();v==null&&(v=A?Ey:r.inv(x));const U=l(D*v),k=l(P*v),K=l(x*v);if(A)return{x:ut,y:Le};if(K!==Le)throw new Error("invZ was invalid");return{x:U,y:k}}),m=qa(E=>{const{a:v,d:D}=e;if(E.is0())throw new Error("bad point: ZERO");const{ex:P,ey:x,ez:A,et:U}=E,k=l(P*P),K=l(x*x),V=l(A*A),z=l(V*V),H=l(k*v),Y=l(V*l(H+K)),X=l(z+l(D*l(k*K)));if(Y!==X)throw new Error("bad point: equation left != right (1)");const W=l(P*x),se=l(A*U);if(W!==se)throw new Error("bad point: equation left != right (2)");return!0});class w{constructor(v,D,P,x){this.ex=v,this.ey=D,this.ez=P,this.et=x,y("x",v),y("y",D),y("z",P),y("t",x),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(v){if(v instanceof w)throw new Error("extended point not allowed");const{x:D,y:P}=v||{};return y("x",D),y("y",P),new w(D,P,Le,l(D*P))}static normalizeZ(v){const D=r.invertBatch(v.map(P=>P.ez));return v.map((P,x)=>P.toAffine(D[x])).map(w.fromAffine)}static msm(v,D){return my(w,h,v,D)}_setWindowSize(v){T.setWindowSize(this,v)}assertValidity(){m(this)}equals(v){g(v);const{ex:D,ey:P,ez:x}=this,{ex:A,ey:U,ez:k}=v,K=l(D*k),V=l(A*x),z=l(P*k),H=l(U*x);return K===V&&z===H}is0(){return this.equals(w.ZERO)}negate(){return new w(l(-this.ex),this.ey,this.ez,l(-this.et))}double(){const{a:v}=e,{ex:D,ey:P,ez:x}=this,A=l(D*D),U=l(P*P),k=l(Gi*l(x*x)),K=l(v*A),V=D+P,z=l(l(V*V)-A-U),H=K+U,Y=H-k,X=K-U,W=l(z*Y),se=l(H*X),ye=l(z*X),Ge=l(Y*H);return new w(W,se,Ge,ye)}add(v){g(v);const{a:D,d:P}=e,{ex:x,ey:A,ez:U,et:k}=this,{ex:K,ey:V,ez:z,et:H}=v;if(D===BigInt(-1)){const ua=l((A-x)*(V+K)),la=l((A+x)*(V-K)),Ws=l(la-ua);if(Ws===ut)return this.double();const ha=l(U*Gi*H),fa=l(k*Gi*z),da=fa+ha,pa=la+ua,ga=fa-ha,Zf=l(da*Ws),Jf=l(pa*ga),Xf=l(da*ga),Qf=l(Ws*pa);return new w(Zf,Jf,Qf,Xf)}const Y=l(x*K),X=l(A*V),W=l(k*P*H),se=l(U*z),ye=l((x+A)*(K+V)-Y-X),Ge=se-W,wt=se+W,At=l(X-D*Y),Hs=l(ye*Ge),Wf=l(wt*At),Gf=l(ye*At),Yf=l(Ge*wt);return new w(Hs,Wf,Yf,Gf)}subtract(v){return this.add(v.negate())}wNAF(v){return T.wNAFCached(this,v,w.normalizeZ)}multiply(v){const D=v;ii("scalar",D,Le,i);const{p:P,f:x}=this.wNAF(D);return w.normalizeZ([P,x])[0]}multiplyUnsafe(v,D=w.ZERO){const P=v;return ii("scalar",P,ut,i),P===ut?O:this.is0()||P===Le?this:T.wNAFCachedUnsafe(this,P,w.normalizeZ,D)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return T.unsafeLadder(this,i).is0()}toAffine(v){return b(this,v)}clearCofactor(){const{h:v}=e;return v===Le?this:this.multiplyUnsafe(v)}static fromHex(v,D=!1){const{d:P,a:x}=e,A=r.BYTES;v=Tt("pointHex",v,A),sn("zip215",D);const U=v.slice(),k=v[A-1];U[A-1]=k&-129;const K=ns(U),V=D?u:r.ORDER;ii("pointHex.y",K,ut,V);const z=l(K*K),H=l(z-Le),Y=l(P*z-x);let{isValid:X,value:W}=f(H,Y);if(!X)throw new Error("Point.fromHex: invalid y coordinate");const se=(W&Le)===Le,ye=(k&128)!==0;if(!D&&W===ut&&ye)throw new Error("Point.fromHex: x=0 and x_0=1");return ye!==se&&(W=l(-W)),w.fromAffine({x:W,y:K})}static fromPrivateKey(v){return $(v).point}toRawBytes(){const{x:v,y:D}=this.toAffine(),P=Yn(D,r.BYTES);return P[P.length-1]|=v&Le?128:0,P}toHex(){return Fo(this.toRawBytes())}}w.BASE=new w(e.Gx,e.Gy,Le,l(e.Gx*e.Gy)),w.ZERO=new w(ut,Le,Le,ut);const{BASE:I,ZERO:O}=w,T=by(w,a*8);function B(E){return me(E,i)}function N(E){return B(ns(E))}function $(E){const v=r.BYTES;E=Tt("private key",E,v);const D=Tt("hashed private key",n(E),2*v),P=p(D.slice(0,v)),x=D.slice(v,2*v),A=N(P),U=I.multiply(A),k=U.toRawBytes();return{head:P,prefix:x,scalar:A,point:U,pointBytes:k}}function M(E){return $(E).pointBytes}function q(E=new Uint8Array,...v){const D=ja(...v);return N(n(d(D,Tt("context",E),!!s)))}function R(E,v,D={}){E=Tt("message",E),s&&(E=s(E));const{prefix:P,scalar:x,pointBytes:A}=$(v),U=q(D.context,P,E),k=I.multiply(U).toRawBytes(),K=q(D.context,k,A,E),V=B(U+K*x);ii("signature.s",V,ut,i);const z=ja(k,Yn(V,r.BYTES));return Tt("result",z,r.BYTES*2)}const _=xy;function S(E,v,D,P=_){const{context:x,zip215:A}=P,U=r.BYTES;E=Tt("signature",E,2*U),v=Tt("message",v),D=Tt("publicKey",D,U),A!==void 0&&sn("zip215",A),s&&(v=s(v));const k=ns(E.slice(U,2*U));let K,V,z;try{K=w.fromHex(D,A),V=w.fromHex(E.slice(0,U),A),z=I.multiplyUnsafe(k)}catch{return!1}if(!A&&K.isSmallOrder())return!1;const H=q(x,V.toRawBytes(),K.toRawBytes(),v);return V.add(K.multiplyUnsafe(H)).subtract(z).clearCofactor().equals(w.ZERO)}return I._setWindowSize(8),{CURVE:e,getPublicKey:M,sign:R,verify:S,ExtendedPoint:w,utils:{getExtendedPublicKey:$,randomPrivateKey:()=>o(r.BYTES),precompute(E=8,v=w.BASE){return v._setWindowSize(E),v.multiply(BigInt(3)),v}}}}BigInt(0),BigInt(1);const Mo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Wa=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Sy=BigInt(1),Ga=BigInt(2);BigInt(3);const Dy=BigInt(5),$y=BigInt(8);function Oy(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=Mo,o=t*t%n*t%n,a=bt(o,Ga,n)*o%n,c=bt(a,Sy,n)*t%n,u=bt(c,Dy,n)*c%n,l=bt(u,e,n)*u%n,h=bt(l,r,n)*l%n,f=bt(h,i,n)*h%n,p=bt(f,s,n)*f%n,d=bt(p,s,n)*f%n,y=bt(d,e,n)*u%n;return{pow_p_5_8:bt(y,Ga,n)*t%n,b2:o}}function Ay(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Py(t,e){const r=Mo,i=me(e*e*e,r),s=me(i*i*e,r),n=Oy(t*s).pow_p_5_8;let o=me(t*i*n,r);const a=me(e*o*o,r),c=o,u=me(o*Wa,r),l=a===t,h=a===me(-t,r),f=a===me(-t*Wa,r);return l&&(o=c),(h||f)&&(o=u),hy(o,r)&&(o=me(-o,r)),{isValid:l||h,value:o}}const Ty=vl(Mo,void 0,!0),Ry={a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ty,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:$y,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Qg,randomBytes:dl,adjustScalarBytes:Ay,uvRatio:Py},_l=Iy(Ry),By="EdDSA",Cy="JWT",hs=".",As="base64url",Il="utf8",Sl="utf8",Uy=":",Ny="did",ky="key",Ya="base58btc",Fy="z",Ly="K36",My=32;function jo(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Dl(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?jo(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function $l(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=Dl(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return jo(r)}function jy(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,g=0,b=0,m=d.length;b!==m&&d[b]===0;)b++,y++;for(var w=(m-b)*l+1>>>0,I=new Uint8Array(w);b!==m;){for(var O=d[b],T=0,B=w-1;(O!==0||T<g)&&B!==-1;B--,T++)O+=256*I[B]>>>0,I[B]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");g=T,b++}for(var N=w-g;N!==w&&I[N]===0;)N++;for(var $=c.repeat(y);N<w;++N)$+=t.charAt(I[N]);return $}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var g=0,b=0;d[y]===c;)g++,y++;for(var m=(d.length-y)*u+1>>>0,w=new Uint8Array(m);d[y];){var I=r[d.charCodeAt(y)];if(I===255)return;for(var O=0,T=m-1;(I!==0||O<b)&&T!==-1;T--,O++)I+=a*w[T]>>>0,w[T]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");b=O,y++}if(d[y]!==" "){for(var B=m-b;B!==m&&w[B]===0;)B++;for(var N=new Uint8Array(g+(m-B)),$=g;B!==m;)N[$++]=w[B++];return N}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var qy=jy,zy=qy;const Ol=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")},Vy=t=>new TextEncoder().encode(t),Ky=t=>new TextDecoder().decode(t);let Hy=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Wy=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Al(this,e)}},Gy=class{constructor(e){this.decoders=e}or(e){return Al(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Al=(t,e)=>new Gy({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Yy=class{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new Hy(e,r,i),this.decoder=new Wy(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ps=({name:t,prefix:e,encode:r,decode:i})=>new Yy(t,e,r,i),Ri=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=zy(r,e);return Ps({prefix:t,name:e,encode:i,decode:n=>Ol(s(n))})},Zy=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Jy=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Ae=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ps({prefix:e,name:t,encode(s){return Jy(s,i,r)},decode(s){return Zy(s,i,r,t)}}),Xy=Ps({prefix:"\0",name:"identity",encode:t=>Ky(t),decode:t=>Vy(t)});var Qy=Object.freeze({__proto__:null,identity:Xy});const e0=Ae({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var t0=Object.freeze({__proto__:null,base2:e0});const r0=Ae({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var i0=Object.freeze({__proto__:null,base8:r0});const s0=Ri({prefix:"9",name:"base10",alphabet:"0123456789"});var n0=Object.freeze({__proto__:null,base10:s0});const o0=Ae({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),a0=Ae({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var c0=Object.freeze({__proto__:null,base16:o0,base16upper:a0});const u0=Ae({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),l0=Ae({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),h0=Ae({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),f0=Ae({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),d0=Ae({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),p0=Ae({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),g0=Ae({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),y0=Ae({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),w0=Ae({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var b0=Object.freeze({__proto__:null,base32:u0,base32upper:l0,base32pad:h0,base32padupper:f0,base32hex:d0,base32hexupper:p0,base32hexpad:g0,base32hexpadupper:y0,base32z:w0});const m0=Ri({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),v0=Ri({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var E0=Object.freeze({__proto__:null,base36:m0,base36upper:v0});const x0=Ri({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),_0=Ri({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var I0=Object.freeze({__proto__:null,base58btc:x0,base58flickr:_0});const S0=Ae({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),D0=Ae({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$0=Ae({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),O0=Ae({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var A0=Object.freeze({__proto__:null,base64:S0,base64pad:D0,base64url:$0,base64urlpad:O0});const Pl=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),P0=Pl.reduce((t,e,r)=>(t[r]=e,t),[]),T0=Pl.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function R0(t){return t.reduce((e,r)=>(e+=P0[r],e),"")}function B0(t){const e=[];for(const r of t){const i=T0[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const C0=Ps({prefix:"🚀",name:"base256emoji",encode:R0,decode:B0});var U0=Object.freeze({__proto__:null,base256emoji:C0}),N0=Tl,Za=128,k0=-128,F0=Math.pow(2,31);function Tl(t,e,r){e=e||[],r=r||0;for(var i=r;t>=F0;)e[r++]=t&255|Za,t/=128;for(;t&k0;)e[r++]=t&255|Za,t>>>=7;return e[r]=t|0,Tl.bytes=r-i+1,e}var L0=Jn,M0=128,Ja=127;function Jn(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Jn.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Ja)<<s:(o&Ja)*Math.pow(2,s),s+=7}while(o>=M0);return Jn.bytes=n-i,r}var j0=Math.pow(2,7),q0=Math.pow(2,14),z0=Math.pow(2,21),V0=Math.pow(2,28),K0=Math.pow(2,35),H0=Math.pow(2,42),W0=Math.pow(2,49),G0=Math.pow(2,56),Y0=Math.pow(2,63),Z0=function(t){return t<j0?1:t<q0?2:t<z0?3:t<V0?4:t<K0?5:t<H0?6:t<W0?7:t<G0?8:t<Y0?9:10},J0={encode:N0,decode:L0,encodingLength:Z0},Rl=J0;const Xa=(t,e,r=0)=>(Rl.encode(t,e,r),e),Qa=t=>Rl.encodingLength(t),Xn=(t,e)=>{const r=e.byteLength,i=Qa(t),s=i+Qa(r),n=new Uint8Array(s+r);return Xa(t,n,0),Xa(r,n,i),n.set(e,s),new X0(t,r,e,n)};let X0=class{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}};const Bl=({name:t,code:e,encode:r})=>new Q0(t,e,r);let Q0=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Xn(this.code,r):r.then(i=>Xn(this.code,i))}else throw Error("Unknown type, must be binary type")}};const Cl=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),ew=Bl({name:"sha2-256",code:18,encode:Cl("SHA-256")}),tw=Bl({name:"sha2-512",code:19,encode:Cl("SHA-512")});var rw=Object.freeze({__proto__:null,sha256:ew,sha512:tw});const Ul=0,iw="identity",Nl=Ol,sw=t=>Xn(Ul,Nl(t)),nw={code:Ul,name:iw,encode:Nl,digest:sw};var ow=Object.freeze({__proto__:null,identity:nw});new TextEncoder,new TextDecoder;const ec={...Qy,...t0,...i0,...n0,...c0,...b0,...E0,...I0,...A0,...U0};({...rw,...ow});function kl(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const tc=kl("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ln=kl("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Dl(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),Fl={utf8:tc,"utf-8":tc,hex:ec.base16,latin1:ln,ascii:ln,binary:ln,...ec};function Ts(t,e="utf8"){const r=Fl[e];if(!r)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"):r.encoder.encode(t).substring(1)}function Xr(t,e="utf8"){const r=Fl[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?jo(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function rc(t){return Gr(Ts(Xr(t,As),Il))}function fs(t){return Ts(Xr(Ti(t),Il),As)}function Ll(t){const e=Xr(Ly,Ya),r=Fy+Ts($l([e,t]),Ya);return[Ny,ky,r].join(Uy)}function aw(t){return Ts(t,As)}function cw(t){return Xr(t,As)}function uw(t){return Xr([fs(t.header),fs(t.payload)].join(hs),Sl)}function lw(t){return[fs(t.header),fs(t.payload),aw(t.signature)].join(hs)}function Qn(t){const e=t.split(hs),r=rc(e[0]),i=rc(e[1]),s=cw(e[2]),n=Xr(e.slice(0,2).join(hs),Sl);return{header:r,payload:i,signature:s,data:n}}function ic(t=dl(My)){const e=_l.getPublicKey(t);return{secretKey:$l([t,e]),publicKey:e}}async function hw(t,e,r,i,s=F.fromMiliseconds(Date.now())){const n={alg:By,typ:Cy},o=Ll(i.publicKey),a=s+r,c={iss:o,sub:t,aud:e,iat:s,exp:a},u=uw({header:n,payload:c}),l=_l.sign(u,i.secretKey.slice(0,32));return lw({header:n,payload:c,signature:l})}var sc=function(t,e,r){if(r||arguments.length===2)for(var i=0,s=e.length,n;i<s;i++)(n||!(i in e))&&(n||(n=Array.prototype.slice.call(e,0,i)),n[i]=e[i]);return t.concat(n||Array.prototype.slice.call(e))},fw=(function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t})(),dw=(function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=at.platform}return t})(),pw=(function(){function t(e,r,i,s){this.name=e,this.version=r,this.os=i,this.bot=s,this.type="bot-device"}return t})(),gw=(function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t})(),yw=(function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t})(),ww=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,bw=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,nc=3,mw=[["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",ww]],oc=[["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 vw(t){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new yw:typeof navigator<"u"?xw(navigator.userAgent):Iw()}function Ew(t){return t!==""&&mw.reduce(function(e,r){var i=r[0],s=r[1];if(e)return e;var n=s.exec(t);return!!n&&[i,n]},!1)}function xw(t){var e=Ew(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new gw;var s=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);s?s.length<nc&&(s=sc(sc([],s,!0),Sw(nc-s.length),!0)):s=[];var n=s.join("."),o=_w(t),a=bw.exec(t);return a&&a[1]?new pw(r,n,o,a[1]):new fw(r,n,o)}function _w(t){for(var e=0,r=oc.length;e<r;e++){var i=oc[e],s=i[0],n=i[1],o=n.exec(t);if(o)return s}return null}function Iw(){var t=typeof at<"u"&&at.version;return t?new dw(at.version.slice(1)):null}function Sw(t){for(var e=[],r=0;r<t;r++)e.push("0");return e}var oe={},ac;function Ml(){if(ac)return oe;ac=1,Object.defineProperty(oe,"__esModule",{value:!0}),oe.getLocalStorage=oe.getLocalStorageOrThrow=oe.getCrypto=oe.getCryptoOrThrow=oe.getLocation=oe.getLocationOrThrow=oe.getNavigator=oe.getNavigatorOrThrow=oe.getDocument=oe.getDocumentOrThrow=oe.getFromWindowOrThrow=oe.getFromWindow=void 0;function t(f){let p;return typeof window<"u"&&typeof window[f]<"u"&&(p=window[f]),p}oe.getFromWindow=t;function e(f){const p=t(f);if(!p)throw new Error(`${f} is not defined in Window`);return p}oe.getFromWindowOrThrow=e;function r(){return e("document")}oe.getDocumentOrThrow=r;function i(){return t("document")}oe.getDocument=i;function s(){return e("navigator")}oe.getNavigatorOrThrow=s;function n(){return t("navigator")}oe.getNavigator=n;function o(){return e("location")}oe.getLocationOrThrow=o;function a(){return t("location")}oe.getLocation=a;function c(){return e("crypto")}oe.getCryptoOrThrow=c;function u(){return t("crypto")}oe.getCrypto=u;function l(){return e("localStorage")}oe.getLocalStorageOrThrow=l;function h(){return t("localStorage")}return oe.getLocalStorage=h,oe}var Vt=Ml(),si={},cc;function Dw(){if(cc)return si;cc=1,Object.defineProperty(si,"__esModule",{value:!0}),si.getWindowMetadata=void 0;const t=Ml();function e(){let r,i;try{r=t.getDocumentOrThrow(),i=t.getLocationOrThrow()}catch{return null}function s(){const p=r.getElementsByTagName("link"),d=[];for(let y=0;y<p.length;y++){const g=p[y],b=g.getAttribute("rel");if(b&&b.toLowerCase().indexOf("icon")>-1){const m=g.getAttribute("href");if(m)if(m.toLowerCase().indexOf("https:")===-1&&m.toLowerCase().indexOf("http:")===-1&&m.indexOf("//")!==0){let w=i.protocol+"//"+i.host;if(m.indexOf("/")===0)w+=m;else{const I=i.pathname.split("/");I.pop();const O=I.join("/");w+=O+"/"+m}d.push(w)}else if(m.indexOf("//")===0){const w=i.protocol+m;d.push(w)}else d.push(m)}}return d}function n(...p){const d=r.getElementsByTagName("meta");for(let y=0;y<d.length;y++){const g=d[y],b=["itemprop","property","name"].map(m=>g.getAttribute(m)).filter(m=>m?p.includes(m):!1);if(b.length&&b){const m=g.getAttribute("content");if(m)return m}}return""}function o(){let p=n("name","og:site_name","og:title","twitter:title");return p||(p=r.title),p}function a(){return n("description","og:description","twitter:description","keywords")}const c=o(),u=a(),l=i.origin,h=s();return{description:u,url:l,icons:h,name:c}}return si.getWindowMetadata=e,si}var $w=Dw();const Ow="0.1.1";function Aw(){return Ow}class le extends Error{constructor(e,r={}){const i=(()=>{if(r.cause instanceof le){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:r.cause?.message?r.cause.message:r.details})(),s=r.cause instanceof le&&r.cause.docsPath||r.docsPath,o=`https://oxlib.sh${s??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||s?["",i?`Details: ${i}`:void 0,s?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
`);super(a,r.cause?{cause:r.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@${Aw()}`}),this.cause=r.cause,this.details=i,this.docs=o,this.docsPath=s,this.shortMessage=e}walk(e){return jl(this,e)}}function jl(t,e){return e?.(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?jl(t.cause,e):e?null:t}function Pw(t,e){if(fc(t)>e)throw new Jw({givenSize:fc(t),maxSize:e})}const Rt={zero:48,nine:57,A:65,F:70,a:97,f:102};function uc(t){if(t>=Rt.zero&&t<=Rt.nine)return t-Rt.zero;if(t>=Rt.A&&t<=Rt.F)return t-(Rt.A-10);if(t>=Rt.a&&t<=Rt.f)return t-(Rt.a-10)}function Tw(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;if(t.length>i)throw new Xw({size:t.length,targetSize:i,type:"Bytes"});const s=new Uint8Array(i);for(let n=0;n<i;n++){const o=r==="right";s[o?n:i-n-1]=t[o?n:t.length-n-1]}return s}function ql(t,e){if(fr(t)>e)throw new jw({givenSize:fr(t),maxSize:e})}function Rw(t,e){if(typeof e=="number"&&e>0&&e>fr(t)-1)throw new Kl({offset:e,position:"start",size:fr(t)})}function Bw(t,e,r){if(typeof e=="number"&&typeof r=="number"&&fr(t)!==r-e)throw new Kl({offset:r,position:"end",size:fr(t)})}function zl(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;const s=t.replace("0x","");if(s.length>i*2)throw new qw({size:Math.ceil(s.length/2),targetSize:i,type:"Hex"});return`0x${s[r==="right"?"padEnd":"padStart"](i*2,"0")}`}const Cw="#__bigint";function qo(t,e,r){return JSON.stringify(t,(i,s)=>typeof s=="bigint"?s.toString()+Cw:s,r)}const Uw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Nw(t,e={}){const{strict:r=!1}=e;if(!t)throw new lc(t);if(typeof t!="string")throw new lc(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new hc(t);if(!t.startsWith("0x"))throw new hc(t)}function kw(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function zo(t){return t instanceof Uint8Array?ds(t):Array.isArray(t)?ds(new Uint8Array(t)):t}function ds(t,e={}){let r="";for(let s=0;s<t.length;s++)r+=Uw[t[s]];const i=`0x${r}`;return typeof e.size=="number"?(ql(i,e.size),Vl(i,e.size)):i}function hn(t,e={}){const{signed:r,size:i}=e,s=BigInt(t);let n;i?r?n=(1n<<BigInt(i)*8n-1n)-1n:n=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(n=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof n=="bigint"&&r?-n-1n:0;if(n&&s>n||s<o){const u=typeof t=="bigint"?"n":"";throw new Mw({max:n?`${n}${u}`:void 0,min:`${o}${u}`,signed:r,size:i,value:`${t}${u}`})}const c=`0x${(r&&s<0?(1n<<BigInt(i*8))+BigInt(s):s).toString(16)}`;return i?Fw(c,i):c}function Fw(t,e){return zl(t,{dir:"left",size:e})}function Vl(t,e){return zl(t,{dir:"right",size:e})}function Ft(t,e,r,i={}){const{strict:s}=i;Rw(t,e);const n=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return s&&Bw(n,e,r),n}function fr(t){return Math.ceil((t.length-2)/2)}function Lw(t,e={}){const{strict:r=!1}=e;try{return Nw(t,{strict:r}),!0}catch{return!1}}class Mw extends le{constructor({max:e,min:r,signed:i,size:s,value:n}){super(`Number \`${n}\` is not in safe${s?` ${s*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class lc extends le{constructor(e){super(`Value \`${typeof e=="object"?qo(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 hc extends le{constructor(e){super(`Value \`${e}\` is an invalid hex value.`,{metaMessages:['Hex values must start with `"0x"` and contain only hexadecimal characters (0-9, a-f, A-F).']}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.InvalidHexValueError"})}}let jw=class extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class Kl extends le{constructor({offset:e,position:r,size:i}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let qw=class extends le{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const zw=new TextEncoder;function Vw(t){if(!(t instanceof Uint8Array)){if(!t)throw new Yi(t);if(typeof t!="object")throw new Yi(t);if(!("BYTES_PER_ELEMENT"in t))throw new Yi(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Yi(t)}}function Kw(t){return t instanceof Uint8Array?t:typeof t=="string"?Ww(t):Hw(t)}function Hw(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Ww(t,e={}){const{size:r}=e;let i=t;r&&(ql(t,r),i=Vl(t,r));let s=i.slice(2);s.length%2&&(s=`0${s}`);const n=s.length/2,o=new Uint8Array(n);for(let a=0,c=0;a<n;a++){const u=uc(s.charCodeAt(c++)),l=uc(s.charCodeAt(c++));if(u===void 0||l===void 0)throw new le(`Invalid byte sequence ("${s[c-2]}${s[c-1]}" in "${s}").`);o[a]=u*16+l}return o}function Gw(t,e={}){const{size:r}=e,i=zw.encode(t);return typeof r=="number"?(Pw(i,r),Yw(i,r)):i}function Yw(t,e){return Tw(t,{dir:"right",size:e})}function fc(t){return t.length}function Zw(t){try{return Vw(t),!0}catch{return!1}}class Yi extends le{constructor(e){super(`Value \`${typeof e=="object"?qo(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 Jw extends le{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Xw extends le{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Hl(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,i=rd(Kw(t));return r==="Bytes"?i:ds(i)}class Qw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const eb={checksum:new Qw(8192)},fn=eb.checksum;function Wl(t,e={}){const{compressed:r}=e,{prefix:i,x:s,y:n}=t;if(r===!1||typeof s=="bigint"&&typeof n=="bigint"){if(i!==4)throw new dc({prefix:i,cause:new ob});return}if(r===!0||typeof s=="bigint"&&typeof n>"u"){if(i!==3&&i!==2)throw new dc({prefix:i,cause:new nb});return}throw new sb({publicKey:t})}function tb(t){const e=(()=>{if(Lw(t))return Gl(t);if(Zw(t))return rb(t);const{prefix:r,x:i,y:s}=t;return typeof i=="bigint"&&typeof s=="bigint"?{prefix:r??4,x:i,y:s}:{prefix:r,x:i}})();return Wl(e),e}function rb(t){return Gl(ds(t))}function Gl(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new ab({publicKey:t});if(t.length===130){const i=BigInt(Ft(t,0,32)),s=BigInt(Ft(t,32,64));return{prefix:4,x:i,y:s}}if(t.length===132){const i=Number(Ft(t,0,1)),s=BigInt(Ft(t,1,33)),n=BigInt(Ft(t,33,65));return{prefix:i,x:s,y:n}}const e=Number(Ft(t,0,1)),r=BigInt(Ft(t,1,33));return{prefix:e,x:r}}function ib(t,e={}){Wl(t);const{prefix:r,x:i,y:s}=t,{includePrefix:n=!0}=e;return kw(n?hn(r,{size:1}):"0x",hn(i,{size:32}),typeof s=="bigint"?hn(s,{size:32}):"0x")}class sb extends le{constructor({publicKey:e}){super(`Value \`${qo(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 dc extends le{constructor({prefix:e,cause:r}){super(`Prefix "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class nb extends le{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 ob extends le{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let ab=class extends le{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 ${fr(zo(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const cb=/^0x[a-fA-F0-9]{40}$/;function Yl(t,e={}){const{strict:r=!0}=e;if(!cb.test(t))throw new pc({address:t,cause:new hb});if(r){if(t.toLowerCase()===t)return;if(Zl(t)!==t)throw new pc({address:t,cause:new fb})}}function Zl(t){if(fn.has(t))return fn.get(t);Yl(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=Hl(Gw(e),{as:"Bytes"}),i=e.split("");for(let n=0;n<40;n+=2)r[n>>1]>>4>=8&&i[n]&&(i[n]=i[n].toUpperCase()),(r[n>>1]&15)>=8&&i[n+1]&&(i[n+1]=i[n+1].toUpperCase());const s=`0x${i.join("")}`;return fn.set(t,s),s}function ub(t,e={}){const{checksum:r=!1}=e;return Yl(t),r?Zl(t):t}function lb(t,e={}){const r=Hl(`0x${ib(t).slice(4)}`).substring(26);return ub(`0x${r}`,e)}class pc extends le{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class hb extends le{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 fb extends le{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}function db(t){if(t.length!==130&&t.length!==132)throw new gb({signature:t});const e=BigInt(Ft(t,0,32)),r=BigInt(Ft(t,32,64)),i=(()=>{const s=+`0x${t.slice(130)}`;if(!Number.isNaN(s))try{return pb(s)}catch{throw new yb({value:s})}})();return typeof i>"u"?{r:e,s:r}:{r:e,s:r,yParity:i}}function pb(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 wb({value:t})}class gb extends le{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${fr(zo(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class yb extends le{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 wb extends le{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"})}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Jl(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Xl(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function ps(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Bi(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function gs(t){if(!Array.isArray(t))throw new Error("array expected")}function ys(t,e){if(!Xl(!0,e))throw new Error(`${t}: array of strings expected`)}function Ql(t,e){if(!Xl(!1,e))throw new Error(`${t}: array of numbers expected`)}function eh(...t){const e=n=>n,r=(n,o)=>a=>n(o(a)),i=t.map(n=>n.encode).reduceRight(r,e),s=t.map(n=>n.decode).reduce(r,e);return{encode:i,decode:s}}function th(t){const e=typeof t=="string"?t.split(""):t,r=e.length;ys("alphabet",e);const i=new Map(e.map((s,n)=>[s,n]));return{encode:s=>(gs(s),s.map(n=>{if(!Number.isSafeInteger(n)||n<0||n>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${n}". Allowed: ${t}`);return e[n]})),decode:s=>(gs(s),s.map(n=>{ps("alphabet.decode",n);const o=i.get(n);if(o===void 0)throw new Error(`Unknown letter: "${n}". Allowed: ${t}`);return o}))}}function rh(t=""){return ps("join",t),{encode:e=>(ys("join.decode",e),e.join(t)),decode:e=>(ps("join.decode",e),e.split(t))}}function bb(t,e="="){return Bi(t),ps("padding",e),{encode(r){for(ys("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){ys("padding.decode",r);let i=r.length;if(i*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===e;i--)if((i-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}function gc(t,e,r){if(e<2)throw new Error(`convertRadix: invalid from=${e}, base cannot be less than 2`);if(r<2)throw new Error(`convertRadix: invalid to=${r}, base cannot be less than 2`);if(gs(t),!t.length)return[];let i=0;const s=[],n=Array.from(t,a=>{if(Bi(a),a<0||a>=e)throw new Error(`invalid integer: ${a}`);return a}),o=n.length;for(;;){let a=0,c=!0;for(let u=i;u<o;u++){const l=n[u],h=e*a,f=h+l;if(!Number.isSafeInteger(f)||h/e!==a||f-l!==h)throw new Error("convertRadix: carry overflow");const p=f/r;a=f%r;const d=Math.floor(p);if(n[u]=d,!Number.isSafeInteger(d)||d*r+a!==f)throw new Error("convertRadix: carry overflow");if(c)d?c=!1:i=u;else continue}if(s.push(a),c)break}for(let a=0;a<t.length-1&&t[a]===0;a++)s.push(0);return s.reverse()}const ih=(t,e)=>e===0?t:ih(e,t%e),ws=(t,e)=>t+(e-ih(t,e)),dn=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function yc(t,e,r,i){if(gs(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(ws(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${ws(e,r)}`);let s=0,n=0;const o=dn[e],a=dn[r]-1,c=[];for(const u of t){if(Bi(u),u>=o)throw new Error(`convertRadix2: invalid data word=${u} from=${e}`);if(s=s<<e|u,n+e>32)throw new Error(`convertRadix2: carry overflow pos=${n} from=${e}`);for(n+=e;n>=r;n-=r)c.push((s>>n-r&a)>>>0);const l=dn[n];if(l===void 0)throw new Error("invalid carry");s&=l-1}if(s=s<<r-n&a,!i&&n>=e)throw new Error("Excess padding");if(!i&&s>0)throw new Error(`Non-zero padding: ${s}`);return i&&n>0&&c.push(s>>>0),c}function mb(t){Bi(t);const e=2**8;return{encode:r=>{if(!Jl(r))throw new Error("radix.encode input should be Uint8Array");return gc(Array.from(r),e,t)},decode:r=>(Ql("radix.decode",r),Uint8Array.from(gc(r,t,e)))}}function vb(t,e=!1){if(Bi(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(ws(8,t)>32||ws(t,8)>32)throw new Error("radix2: carry overflow");return{encode:r=>{if(!Jl(r))throw new Error("radix2.encode input should be Uint8Array");return yc(Array.from(r),8,t,!e)},decode:r=>(Ql("radix2.decode",r),Uint8Array.from(yc(r,t,8,e)))}}const Eb=eh(vb(5),th("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),bb(5),rh("")),xb=t=>eh(mb(58),th(t),rh("")),Ci=xb("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz");function _b(t){return lb(Ib(t))}function Ib(t){const{payload:e,signature:r}=t,{r:i,s,yParity:n}=r,a=new id.Signature(BigInt(i),BigInt(s)).addRecoveryBit(n).recoverPublicKey(zo(e).substring(2));return tb(a)}var pn={exports:{}},wc;function Sb(){return wc||(wc=1,(function(t){var e=Object.prototype.hasOwnProperty,r="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(r=!1));function s(c,u,l){this.fn=c,this.context=u,this.once=l||!1}function n(c,u,l,h,f){if(typeof l!="function")throw new TypeError("The listener must be a function");var p=new s(l,h||c,f),d=r?r+u:u;return c._events[d]?c._events[d].fn?c._events[d]=[c._events[d],p]:c._events[d].push(p):(c._events[d]=p,c._eventsCount++),c}function o(c,u){--c._eventsCount===0?c._events=new i:delete c._events[u]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var u=[],l,h;if(this._eventsCount===0)return u;for(h in l=this._events)e.call(l,h)&&u.push(r?h.slice(1):h);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(l)):u},a.prototype.listeners=function(u){var l=r?r+u:u,h=this._events[l];if(!h)return[];if(h.fn)return[h.fn];for(var f=0,p=h.length,d=new Array(p);f<p;f++)d[f]=h[f].fn;return d},a.prototype.listenerCount=function(u){var l=r?r+u:u,h=this._events[l];return h?h.fn?1:h.length:0},a.prototype.emit=function(u,l,h,f,p,d){var y=r?r+u:u;if(!this._events[y])return!1;var g=this._events[y],b=arguments.length,m,w;if(g.fn){switch(g.once&&this.removeListener(u,g.fn,void 0,!0),b){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,h),!0;case 4:return g.fn.call(g.context,l,h,f),!0;case 5:return g.fn.call(g.context,l,h,f,p),!0;case 6:return g.fn.call(g.context,l,h,f,p,d),!0}for(w=1,m=new Array(b-1);w<b;w++)m[w-1]=arguments[w];g.fn.apply(g.context,m)}else{var I=g.length,O;for(w=0;w<I;w++)switch(g[w].once&&this.removeListener(u,g[w].fn,void 0,!0),b){case 1:g[w].fn.call(g[w].context);break;case 2:g[w].fn.call(g[w].context,l);break;case 3:g[w].fn.call(g[w].context,l,h);break;case 4:g[w].fn.call(g[w].context,l,h,f);break;default:if(!m)for(O=1,m=new Array(b-1);O<b;O++)m[O-1]=arguments[O];g[w].fn.apply(g[w].context,m)}}return!0},a.prototype.on=function(u,l,h){return n(this,u,l,h,!1)},a.prototype.once=function(u,l,h){return n(this,u,l,h,!0)},a.prototype.removeListener=function(u,l,h,f){var p=r?r+u:u;if(!this._events[p])return this;if(!l)return o(this,p),this;var d=this._events[p];if(d.fn)d.fn===l&&(!f||d.once)&&(!h||d.context===h)&&o(this,p);else{for(var y=0,g=[],b=d.length;y<b;y++)(d[y].fn!==l||f&&!d[y].once||h&&d[y].context!==h)&&g.push(d[y]);g.length?this._events[p]=g.length===1?g[0]:g:o(this,p)}return this},a.prototype.removeAllListeners=function(u){var l;return u?(l=r?r+u:u,this._events[l]&&o(this,l)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=r,a.EventEmitter=a,t.exports=a})(pn)),pn.exports}var Db=Sb();const ZS=td(Db);function $b(t){const e=t.length;let r=0,i=0;for(;i<e;){let s=t.charCodeAt(i++);if((s&4294967168)===0){r++;continue}else if((s&4294965248)===0)r+=2;else{if(s>=55296&&s<=56319&&i<e){const n=t.charCodeAt(i);(n&64512)===56320&&(++i,s=((s&1023)<<10)+(n&1023)+65536)}(s&4294901760)===0?r+=3:r+=4}}return r}function Ob(t,e,r){const i=t.length;let s=r,n=0;for(;n<i;){let o=t.charCodeAt(n++);if((o&4294967168)===0){e[s++]=o;continue}else if((o&4294965248)===0)e[s++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&n<i){const a=t.charCodeAt(n);(a&64512)===56320&&(++n,o=((o&1023)<<10)+(a&1023)+65536)}(o&4294901760)===0?(e[s++]=o>>12&15|224,e[s++]=o>>6&63|128):(e[s++]=o>>18&7|240,e[s++]=o>>12&63|128,e[s++]=o>>6&63|128)}e[s++]=o&63|128}}const Ab=new TextEncoder,Pb=50;function Tb(t,e,r){Ab.encodeInto(t,e.subarray(r))}function Rb(t,e,r){t.length>Pb?Tb(t,e,r):Ob(t,e,r)}const Bb=4096;function sh(t,e,r){let i=e;const s=i+r,n=[];let o="";for(;i<s;){const a=t[i++];if((a&128)===0)n.push(a);else if((a&224)===192){const c=t[i++]&63;n.push((a&31)<<6|c)}else if((a&240)===224){const c=t[i++]&63,u=t[i++]&63;n.push((a&31)<<12|c<<6|u)}else if((a&248)===240){const c=t[i++]&63,u=t[i++]&63,l=t[i++]&63;let h=(a&7)<<18|c<<12|u<<6|l;h>65535&&(h-=65536,n.push(h>>>10&1023|55296),h=56320|h&1023),n.push(h)}else n.push(a);n.length>=Bb&&(o+=String.fromCharCode(...n),n.length=0)}return n.length>0&&(o+=String.fromCharCode(...n)),o}const Cb=new TextDecoder,Ub=200;function Nb(t,e,r){const i=t.subarray(e,e+r);return Cb.decode(i)}function kb(t,e,r){return r>Ub?Nb(t,e,r):sh(t,e,r)}class Zi{type;data;constructor(e,r){this.type=e,this.data=r}}class Je extends Error{constructor(e){super(e);const r=Object.create(Je.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:Je.name})}}const ni=4294967295;function Fb(t,e,r){const i=r/4294967296,s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function nh(t,e,r){const i=Math.floor(r/4294967296),s=r;t.setUint32(e,i),t.setUint32(e+4,s)}function oh(t,e){const r=t.getInt32(e),i=t.getUint32(e+4);return r*4294967296+i}function Lb(t,e){const r=t.getUint32(e),i=t.getUint32(e+4);return r*4294967296+i}const Mb=-1,jb=4294967296-1,qb=17179869184-1;function zb({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=qb)if(e===0&&t<=jb){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,i=t&4294967295,s=new Uint8Array(8),n=new DataView(s.buffer);return n.setUint32(0,e<<2|r&3),n.setUint32(4,i),s}else{const r=new Uint8Array(12),i=new DataView(r.buffer);return i.setUint32(0,e),nh(i,4,t),r}}function Vb(t){const e=t.getTime(),r=Math.floor(e/1e3),i=(e-r*1e3)*1e6,s=Math.floor(i/1e9);return{sec:r+s,nsec:i-s*1e9}}function Kb(t){if(t instanceof Date){const e=Vb(t);return zb(e)}else return null}function Hb(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 r=e.getUint32(0),i=e.getUint32(4),s=(r&3)*4294967296+i,n=r>>>2;return{sec:s,nsec:n}}case 12:{const r=oh(e,4),i=e.getUint32(0);return{sec:r,nsec:i}}default:throw new Je(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Wb(t){const e=Hb(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Gb={type:Mb,encode:Kb,decode:Wb};class Rs{static defaultCodec=new Rs;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Gb)}register({type:e,encode:r,decode:i}){if(e>=0)this.encoders[e]=r,this.decoders[e]=i;else{const s=-1-e;this.builtInEncoders[s]=r,this.builtInDecoders[s]=i}}tryToEncode(e,r){for(let i=0;i<this.builtInEncoders.length;i++){const s=this.builtInEncoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=-1-i;return new Zi(o,n)}}}for(let i=0;i<this.encoders.length;i++){const s=this.encoders[i];if(s!=null){const n=s(e,r);if(n!=null){const o=i;return new Zi(o,n)}}}return e instanceof Zi?e:null}decode(e,r,i){const s=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return s?s(e,r,i):new Zi(r,e)}}function Yb(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function eo(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Yb(t)?new Uint8Array(t):Uint8Array.from(t)}const Zb=100,Jb=2048;let Xb=class ah{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Rs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??Zb,this.initialBufferSize=e?.initialBufferSize??Jb,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 ah({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,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);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,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),i=new Uint8Array(r),s=new DataView(r);i.set(this.bytes),this.view=s,this.bytes=i}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 i=$b(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Rb(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,r){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const i=eo(e);this.writeU8a(i)}encodeArray(e,r){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const s of e)this.doEncode(s,r+1)}countWithoutUndefined(e,r){let i=0;for(const s of r)e[s]!==void 0&&i++;return i}encodeMap(e,r){const i=Object.keys(e);this.sortKeys&&i.sort();const s=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.length;if(s<16)this.writeU8(128+s);else if(s<65536)this.writeU8(222),this.writeU16(s);else if(s<4294967296)this.writeU8(223),this.writeU32(s);else throw new Error(`Too large map object: ${s}`);for(const n of i){const o=e[n];this.ignoreUndefined&&o===void 0||(this.encodeString(n),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),s=i.length;if(s>=4294967296)throw new Error(`Too large extension object: ${s}`);this.writeU8(201),this.writeU32(s),this.writeI8(e.type),this.writeU8a(i);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}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),Fb(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),nh(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 Qb(t,e){return new Xb(e).encodeSharedRef(t)}function gn(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const em=16,tm=16;class rm{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=em,r=tm){this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,i){const s=this.caches[i-1];e:for(const n of s){const o=n.bytes;for(let a=0;a<i;a++)if(o[a]!==e[r+a])continue e;return n.str}return null}store(e,r){const i=this.caches[e.length-1],s={bytes:e,str:r};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=s:i.push(s)}decode(e,r,i){const s=this.find(e,r,i);if(s!=null)return this.hit++,s;this.miss++;const n=sh(e,r,i),o=Uint8Array.prototype.slice.call(e,r,r+i);return this.store(o,n),n}}const to="array",wi="map_key",ch="map_value",im=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Je("The type of key must be string or number but "+typeof t)};class sm{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=to,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=wi,r.readCount=0,r.size=e,r.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===to){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===wi||e.type===ch){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const oi=-1,Vo=new DataView(new ArrayBuffer(0)),nm=new Uint8Array(Vo.buffer);try{Vo.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 bc=new RangeError("Insufficient data"),om=new rm;let am=class uh{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=Vo;bytes=nm;headByte=oi;stack=new sm;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Rs.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??ni,this.maxBinLength=e?.maxBinLength??ni,this.maxArrayLength=e?.maxArrayLength??ni,this.maxMapLength=e?.maxMapLength??ni,this.maxExtLength=e?.maxExtLength??ni,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:om,this.mapKeyConverter=e?.mapKeyConverter??im}clone(){return new uh({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=oi,this.stack.reset()}setBuffer(e){const r=eo(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===oi&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),i=eo(e),s=new Uint8Array(r.length+i.length);s.set(r),s.set(i,r.length),this.setBuffer(s)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:i}=this;return new RangeError(`Extra ${r.byteLength-i} of ${r.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 r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}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 r=!1,i;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:s,pos:n,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${gn(s)} at ${o} (${n} 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,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let i=r,s=-1;for await(const n of e){if(r&&s===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(n),i&&(s=this.readArraySize(),i=!1,this.complete());try{for(;yield this.doDecodeSync(),--s!==0;);}catch(o){if(!(o instanceof RangeError))throw o}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){const e=this.readHeadByte();let r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const s=e-128;if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e<160){const s=e-144;if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else{const s=e-160;r=this.decodeString(s,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const s=this.lookU8();r=this.decodeString(s,1)}else if(e===218){const s=this.lookU16();r=this.decodeString(s,2)}else if(e===219){const s=this.lookU32();r=this.decodeString(s,4)}else if(e===220){const s=this.readU16();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===221){const s=this.readU32();if(s!==0){this.pushArrayState(s),this.complete();continue e}else r=[]}else if(e===222){const s=this.readU16();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===223){const s=this.readU32();if(s!==0){this.pushMapState(s),this.complete();continue e}else r={}}else if(e===196){const s=this.lookU8();r=this.decodeBinary(s,1)}else if(e===197){const s=this.lookU16();r=this.decodeBinary(s,2)}else if(e===198){const s=this.lookU32();r=this.decodeBinary(s,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const s=this.lookU8();r=this.decodeExtension(s,1)}else if(e===200){const s=this.lookU16();r=this.decodeExtension(s,2)}else if(e===201){const s=this.lookU32();r=this.decodeExtension(s,4)}else throw new Je(`Unrecognized type byte: ${gn(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const s=i.top();if(s.type===to)if(s.array[s.position]=r,s.position++,s.position===s.size)r=s.array,i.release(s);else continue e;else if(s.type===wi){if(r==="__proto__")throw new Je("The key __proto__ is not allowed");s.key=this.mapKeyConverter(r),s.type=ch;continue e}else if(s.map[s.key]=r,s.readCount++,s.readCount===s.size)r=s.map,i.release(s);else{s.key=null,s.type=wi;continue e}}return r}}readHeadByte(){return this.headByte===oi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=oi}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 Je(`Unrecognized array type byte: ${gn(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Je(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Je(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){if(e>this.maxStrLength)throw new Je(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+r+e)throw bc;const i=this.pos+r;let s;return this.stateIsMapKey()&&this.keyDecoder?.canBeCached(e)?s=this.keyDecoder.decode(this.bytes,i,e):s=kb(this.bytes,i,e),this.pos+=r+e,s}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===wi:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new Je(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw bc;const i=this.pos+r,s=this.bytes.subarray(i,i+e);return this.pos+=r+e,s}decodeExtension(e,r){if(e>this.maxExtLength)throw new Je(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+r),s=this.decodeBinary(e,r+1);return this.extensionCodec.decode(s,i,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=Lb(this.view,this.pos);return this.pos+=8,e}readI64(){const e=oh(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 cm(t,e){return new am(e).decode(t)}function Ko(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function lh(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ko(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function bi(t,e){e||(e=t.reduce((s,n)=>s+n.length,0));const r=lh(e);let i=0;for(const s of t)r.set(s,i),i+=s.length;return Ko(r)}function um(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,g=0,b=0,m=d.length;b!==m&&d[b]===0;)b++,y++;for(var w=(m-b)*l+1>>>0,I=new Uint8Array(w);b!==m;){for(var O=d[b],T=0,B=w-1;(O!==0||T<g)&&B!==-1;B--,T++)O+=256*I[B]>>>0,I[B]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");g=T,b++}for(var N=w-g;N!==w&&I[N]===0;)N++;for(var $=c.repeat(y);N<w;++N)$+=t.charAt(I[N]);return $}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var g=0,b=0;d[y]===c;)g++,y++;for(var m=(d.length-y)*u+1>>>0,w=new Uint8Array(m);d[y];){var I=r[d.charCodeAt(y)];if(I===255)return;for(var O=0,T=m-1;(I!==0||O<b)&&T!==-1;T--,O++)I+=a*w[T]>>>0,w[T]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");b=O,y++}if(d[y]!==" "){for(var B=m-b;B!==m&&w[B]===0;)B++;for(var N=new Uint8Array(g+(m-B)),$=g;B!==m;)N[$++]=w[B++];return N}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var lm=um,hm=lm;const fm=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")},dm=t=>new TextEncoder().encode(t),pm=t=>new TextDecoder().decode(t);class gm{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class ym{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 hh(this,e)}}class wm{constructor(e){this.decoders=e}or(e){return hh(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const hh=(t,e)=>new wm({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class bm{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new gm(e,r,i),this.decoder=new ym(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Bs=({name:t,prefix:e,encode:r,decode:i})=>new bm(t,e,r,i),Ui=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=hm(r,e);return Bs({prefix:t,name:e,encode:i,decode:n=>fm(s(n))})},mm=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},vm=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Pe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Bs({prefix:e,name:t,encode(s){return vm(s,i,r)},decode(s){return mm(s,i,r,t)}}),Em=Bs({prefix:"\0",name:"identity",encode:t=>pm(t),decode:t=>dm(t)}),xm=Object.freeze(Object.defineProperty({__proto__:null,identity:Em},Symbol.toStringTag,{value:"Module"})),_m=Pe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),Im=Object.freeze(Object.defineProperty({__proto__:null,base2:_m},Symbol.toStringTag,{value:"Module"})),Sm=Pe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Dm=Object.freeze(Object.defineProperty({__proto__:null,base8:Sm},Symbol.toStringTag,{value:"Module"})),$m=Ui({prefix:"9",name:"base10",alphabet:"0123456789"}),Om=Object.freeze(Object.defineProperty({__proto__:null,base10:$m},Symbol.toStringTag,{value:"Module"})),Am=Pe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Pm=Pe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),Tm=Object.freeze(Object.defineProperty({__proto__:null,base16:Am,base16upper:Pm},Symbol.toStringTag,{value:"Module"})),Rm=Pe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Bm=Pe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Cm=Pe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Um=Pe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Nm=Pe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),km=Pe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fm=Pe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Lm=Pe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Mm=Pe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),jm=Object.freeze(Object.defineProperty({__proto__:null,base32:Rm,base32hex:Nm,base32hexpad:Fm,base32hexpadupper:Lm,base32hexupper:km,base32pad:Cm,base32padupper:Um,base32upper:Bm,base32z:Mm},Symbol.toStringTag,{value:"Module"})),qm=Ui({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),zm=Ui({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Vm=Object.freeze(Object.defineProperty({__proto__:null,base36:qm,base36upper:zm},Symbol.toStringTag,{value:"Module"})),Km=Ui({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Hm=Ui({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Wm=Object.freeze(Object.defineProperty({__proto__:null,base58btc:Km,base58flickr:Hm},Symbol.toStringTag,{value:"Module"})),Gm=Pe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Ym=Pe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Zm=Pe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Jm=Pe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Xm=Object.freeze(Object.defineProperty({__proto__:null,base64:Gm,base64pad:Ym,base64url:Zm,base64urlpad:Jm},Symbol.toStringTag,{value:"Module"})),fh=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Qm=fh.reduce((t,e,r)=>(t[r]=e,t),[]),e1=fh.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function t1(t){return t.reduce((e,r)=>(e+=Qm[r],e),"")}function r1(t){const e=[];for(const r of t){const i=e1[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const i1=Bs({prefix:"🚀",name:"base256emoji",encode:t1,decode:r1}),s1=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:i1},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const mc={...xm,...Im,...Dm,...Om,...Tm,...jm,...Vm,...Wm,...Xm,...s1};function dh(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const vc=dh("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),yn=dh("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=lh(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),ph={utf8:vc,"utf-8":vc,hex:mc.base16,latin1:yn,ascii:yn,binary:yn,...mc};function ot(t,e="utf8"){const r=ph[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ko(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function He(t,e="utf8"){const r=ph[e];if(!r)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"):r.encoder.encode(t).substring(1)}const n1={waku:{publish:"waku_publish",batchPublish:"waku_batchPublish",subscribe:"waku_subscribe",batchSubscribe:"waku_batchSubscribe",subscription:"waku_subscription",unsubscribe:"waku_unsubscribe",batchUnsubscribe:"waku_batchUnsubscribe",batchFetchMessages:"waku_batchFetchMessages"},irn:{publish:"irn_publish",batchPublish:"irn_batchPublish",subscribe:"irn_subscribe",batchSubscribe:"irn_batchSubscribe",subscription:"irn_subscription",unsubscribe:"irn_unsubscribe",batchUnsubscribe:"irn_batchUnsubscribe",batchFetchMessages:"irn_batchFetchMessages"},iridium:{publish:"iridium_publish",batchPublish:"iridium_batchPublish",subscribe:"iridium_subscribe",batchSubscribe:"iridium_batchSubscribe",subscription:"iridium_subscription",unsubscribe:"iridium_unsubscribe",batchUnsubscribe:"iridium_batchUnsubscribe",batchFetchMessages:"iridium_batchFetchMessages"}};var wn,Ec;function gh(){if(Ec)return wn;Ec=1;const t="Input must be an string, Buffer or Uint8Array";function e(o){let a;if(o instanceof Uint8Array)a=o;else if(typeof o=="string")a=new TextEncoder().encode(o);else throw new Error(t);return a}function r(o){return Array.prototype.map.call(o,function(a){return(a<16?"0":"")+a.toString(16)}).join("")}function i(o){return(4294967296+o).toString(16).substring(1)}function s(o,a,c){let u=`
`+o+" = ";for(let l=0;l<a.length;l+=2){if(c===32)u+=i(a[l]).toUpperCase(),u+=" ",u+=i(a[l+1]).toUpperCase();else if(c===64)u+=i(a[l+1]).toUpperCase(),u+=i(a[l]).toUpperCase();else throw new Error("Invalid size "+c);l%6===4?u+=`
`+new Array(o.length+4).join(" "):l<a.length-2&&(u+=" ")}console.log(u)}function n(o,a,c){let u=new Date().getTime();const l=new Uint8Array(a);for(let f=0;f<a;f++)l[f]=f%256;const h=new Date().getTime();console.log("Generated random input in "+(h-u)+"ms"),u=h;for(let f=0;f<c;f++){const p=o(l),d=new Date().getTime(),y=d-u;u=d,console.log("Hashed in "+y+"ms: "+p.substring(0,20)+"..."),console.log(Math.round(a/(1<<20)/(y/1e3)*100)/100+" MB PER SECOND")}}return wn={normalizeInput:e,toHex:r,debugPrint:s,testSpeed:n},wn}var bn,xc;function o1(){if(xc)return bn;xc=1;const t=gh();function e(b,m,w){const I=b[m]+b[w];let O=b[m+1]+b[w+1];I>=4294967296&&O++,b[m]=I,b[m+1]=O}function r(b,m,w,I){let O=b[m]+w;w<0&&(O+=4294967296);let T=b[m+1]+I;O>=4294967296&&T++,b[m]=O,b[m+1]=T}function i(b,m){return b[m]^b[m+1]<<8^b[m+2]<<16^b[m+3]<<24}function s(b,m,w,I,O,T){const B=u[O],N=u[O+1],$=u[T],M=u[T+1];e(c,b,m),r(c,b,B,N);let q=c[I]^c[b],R=c[I+1]^c[b+1];c[I]=R,c[I+1]=q,e(c,w,I),q=c[m]^c[w],R=c[m+1]^c[w+1],c[m]=q>>>24^R<<8,c[m+1]=R>>>24^q<<8,e(c,b,m),r(c,b,$,M),q=c[I]^c[b],R=c[I+1]^c[b+1],c[I]=q>>>16^R<<16,c[I+1]=R>>>16^q<<16,e(c,w,I),q=c[m]^c[w],R=c[m+1]^c[w+1],c[m]=R>>>31^q<<1,c[m+1]=q>>>31^R<<1}const n=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),o=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3],a=new Uint8Array(o.map(function(b){return b*2})),c=new Uint32Array(32),u=new Uint32Array(32);function l(b,m){let w=0;for(w=0;w<16;w++)c[w]=b.h[w],c[w+16]=n[w];for(c[24]=c[24]^b.t,c[25]=c[25]^b.t/4294967296,m&&(c[28]=~c[28],c[29]=~c[29]),w=0;w<32;w++)u[w]=i(b.b,4*w);for(w=0;w<12;w++)s(0,8,16,24,a[w*16+0],a[w*16+1]),s(2,10,18,26,a[w*16+2],a[w*16+3]),s(4,12,20,28,a[w*16+4],a[w*16+5]),s(6,14,22,30,a[w*16+6],a[w*16+7]),s(0,10,20,30,a[w*16+8],a[w*16+9]),s(2,12,22,24,a[w*16+10],a[w*16+11]),s(4,14,16,26,a[w*16+12],a[w*16+13]),s(6,8,18,28,a[w*16+14],a[w*16+15]);for(w=0;w<16;w++)b.h[w]=b.h[w]^c[w]^c[w+16]}const h=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]);function f(b,m,w,I){if(b===0||b>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(m&&m.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(w&&w.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(I&&I.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const O={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:b};h.fill(0),h[0]=b,m&&(h[1]=m.length),h[2]=1,h[3]=1,w&&h.set(w,32),I&&h.set(I,48);for(let T=0;T<16;T++)O.h[T]=n[T]^i(h,T*4);return m&&(p(O,m),O.c=128),O}function p(b,m){for(let w=0;w<m.length;w++)b.c===128&&(b.t+=b.c,l(b,!1),b.c=0),b.b[b.c++]=m[w]}function d(b){for(b.t+=b.c;b.c<128;)b.b[b.c++]=0;l(b,!0);const m=new Uint8Array(b.outlen);for(let w=0;w<b.outlen;w++)m[w]=b.h[w>>2]>>8*(w&3);return m}function y(b,m,w,I,O){w=w||64,b=t.normalizeInput(b),I&&(I=t.normalizeInput(I)),O&&(O=t.normalizeInput(O));const T=f(w,m,I,O);return p(T,b),d(T)}function g(b,m,w,I,O){const T=y(b,m,w,I,O);return t.toHex(T)}return bn={blake2b:y,blake2bHex:g,blake2bInit:f,blake2bUpdate:p,blake2bFinal:d},bn}var mn,_c;function a1(){if(_c)return mn;_c=1;const t=gh();function e(d,y){return d[y]^d[y+1]<<8^d[y+2]<<16^d[y+3]<<24}function r(d,y,g,b,m,w){o[d]=o[d]+o[y]+m,o[b]=i(o[b]^o[d],16),o[g]=o[g]+o[b],o[y]=i(o[y]^o[g],12),o[d]=o[d]+o[y]+w,o[b]=i(o[b]^o[d],8),o[g]=o[g]+o[b],o[y]=i(o[y]^o[g],7)}function i(d,y){return d>>>y^d<<32-y}const s=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),n=new Uint8Array([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0]),o=new Uint32Array(16),a=new Uint32Array(16);function c(d,y){let g=0;for(g=0;g<8;g++)o[g]=d.h[g],o[g+8]=s[g];for(o[12]^=d.t,o[13]^=d.t/4294967296,y&&(o[14]=~o[14]),g=0;g<16;g++)a[g]=e(d.b,4*g);for(g=0;g<10;g++)r(0,4,8,12,a[n[g*16+0]],a[n[g*16+1]]),r(1,5,9,13,a[n[g*16+2]],a[n[g*16+3]]),r(2,6,10,14,a[n[g*16+4]],a[n[g*16+5]]),r(3,7,11,15,a[n[g*16+6]],a[n[g*16+7]]),r(0,5,10,15,a[n[g*16+8]],a[n[g*16+9]]),r(1,6,11,12,a[n[g*16+10]],a[n[g*16+11]]),r(2,7,8,13,a[n[g*16+12]],a[n[g*16+13]]),r(3,4,9,14,a[n[g*16+14]],a[n[g*16+15]]);for(g=0;g<8;g++)d.h[g]^=o[g]^o[g+8]}function u(d,y){if(!(d>0&&d<=32))throw new Error("Incorrect output length, should be in [1, 32]");const g=y?y.length:0;if(y&&!(g>0&&g<=32))throw new Error("Incorrect key length, should be in [1, 32]");const b={h:new Uint32Array(s),b:new Uint8Array(64),c:0,t:0,outlen:d};return b.h[0]^=16842752^g<<8^d,g>0&&(l(b,y),b.c=64),b}function l(d,y){for(let g=0;g<y.length;g++)d.c===64&&(d.t+=d.c,c(d,!1),d.c=0),d.b[d.c++]=y[g]}function h(d){for(d.t+=d.c;d.c<64;)d.b[d.c++]=0;c(d,!0);const y=new Uint8Array(d.outlen);for(let g=0;g<d.outlen;g++)y[g]=d.h[g>>2]>>8*(g&3)&255;return y}function f(d,y,g){g=g||32,d=t.normalizeInput(d);const b=u(g,y);return l(b,d),h(b)}function p(d,y,g){const b=f(d,y,g);return t.toHex(b)}return mn={blake2s:f,blake2sHex:p,blake2sInit:u,blake2sUpdate:l,blake2sFinal:h},mn}var vn,Ic;function c1(){if(Ic)return vn;Ic=1;const t=o1(),e=a1();return vn={blake2b:t.blake2b,blake2bHex:t.blake2bHex,blake2bInit:t.blake2bInit,blake2bUpdate:t.blake2bUpdate,blake2bFinal:t.blake2bFinal,blake2s:e.blake2s,blake2sHex:e.blake2sHex,blake2sInit:e.blake2sInit,blake2sUpdate:e.blake2sUpdate,blake2sFinal:e.blake2sFinal},vn}var u1=c1(),l1={};const h1=":";function os(t){const[e,r]=t.split(h1);return{namespace:e,reference:r}}function yh(t,e){return t.includes(":")?[t]:e.chains||[]}const f1={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}},d1={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 L(t,e){const{message:r,code:i}=d1[t];return{message:e?`${r} ${e}`:r,code:i}}function he(t,e){const{message:r,code:i}=f1[t];return{message:e?`${r} ${e}`:r,code:i}}var p1=Object.defineProperty,g1=Object.defineProperties,y1=Object.getOwnPropertyDescriptors,Sc=Object.getOwnPropertySymbols,w1=Object.prototype.hasOwnProperty,b1=Object.prototype.propertyIsEnumerable,ro=(t,e,r)=>e in t?p1(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Dc=(t,e)=>{for(var r in e||(e={}))w1.call(e,r)&&ro(t,r,e[r]);if(Sc)for(var r of Sc(e))b1.call(e,r)&&ro(t,r,e[r]);return t},m1=(t,e)=>g1(t,y1(e)),$c=(t,e,r)=>ro(t,typeof e!="symbol"?e+"":e,r);const v1="ReactNative",Qe={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},E1="js";function bs(){return typeof at<"u"&&typeof at.versions<"u"&&typeof at.versions.node<"u"}function gr(){return!Vt.getDocument()&&!!Vt.getNavigator()&&navigator.product===v1}function x1(){return gr()&&typeof G<"u"&&typeof(G==null?void 0:G.Platform)<"u"&&(G==null?void 0:G.Platform.OS)==="android"}function _1(){return gr()&&typeof G<"u"&&typeof(G==null?void 0:G.Platform)<"u"&&(G==null?void 0:G.Platform.OS)==="ios"}function Qr(){return!bs()&&!!Vt.getNavigator()&&!!Vt.getDocument()}function Ni(){return gr()?Qe.reactNative:bs()?Qe.node:Qr()?Qe.browser:Qe.unknown}function Oc(){var t;try{return gr()&&typeof G<"u"&&typeof(G==null?void 0:G.Application)<"u"?(t=G.Application)==null?void 0:t.applicationId:void 0}catch{return}}function I1(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([i],[s])=>i.localeCompare(s)).forEach(([i,s])=>{s!=null&&r.set(i,String(s))}),r.toString()}function S1(t){var e,r;const i=wh();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t?.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(s=>s!=="")),m1(Dc(Dc({},i),t),{url:t?.url||i.url,name:t?.name||i.name,description:t?.description||i.description,icons:(r=t?.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(s){return console.warn("Error populating app metadata",s),t||i}}function wh(){return $w.getWindowMetadata()||{name:"",description:"",url:"",icons:[""]}}function D1(){if(Ni()===Qe.reactNative&&typeof G<"u"&&typeof(G==null?void 0:G.Platform)<"u"){const{OS:r,Version:i}=G.Platform;return[r,i].join("-")}const t=vw();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 $1(){var t;const e=Ni();return e===Qe.browser?[e,((t=Vt.getLocation())==null?void 0:t.host)||"unknown"].join(":"):e}function bh(t,e,r){const i=D1(),s=$1();return[[t,e].join("-"),[E1,r].join("-"),i,s].join("/")}function O1({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:s,projectId:n,useOnCloseEvent:o,bundleId:a,packageName:c}){const u=r.split("?"),l=bh(t,e,i),h={auth:s,ua:l,projectId:n,useOnCloseEvent:o,packageName:c||void 0,bundleId:a||void 0},f=I1(u[1]||"",h);return u[0]+"?"+f}function Sr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function io(t){return Object.fromEntries(t.entries())}function so(t){return new Map(Object.entries(t))}function xr(t=F.FIVE_MINUTES,e){const r=F.toMiliseconds(t||F.FIVE_MINUTES);let i,s,n,o;return{resolve:a=>{n&&i&&(clearTimeout(n),i(a),o=Promise.resolve(a))},reject:a=>{n&&s&&(clearTimeout(n),s(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);n=setTimeout(()=>{const u=L("EXPIRED"),l=new Error(e||u.message);l.code=u.code,c(l)},r),i=a,s=c})}}function Dt(t,e,r){return new Promise(async(i,s)=>{const n=setTimeout(()=>s(new Error(r)),e);try{const o=await t;i(o)}catch(o){s(o)}clearTimeout(n)})}function mh(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 A1(t){return mh("topic",t)}function P1(t){return mh("id",t)}function vh(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function be(t,e){return F.fromMiliseconds(Date.now()+F.toMiliseconds(t))}function er(t){return Date.now()>=F.toMiliseconds(t)}function ne(t,e){return`${t}${e?`:${e}`:""}`}function pt(t=[],e=[]){return[...new Set([...t,...e])]}async function T1({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const s=typeof r=="string"?JSON.parse(r):r,n=s?.href;if(typeof n!="string")return;const o=R1(n,t,e),a=Ni();if(a===Qe.browser){if(!((i=Vt.getDocument())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}B1(o)}else a===Qe.reactNative&&typeof(G==null?void 0:G.Linking)<"u"&&await G.Linking.openURL(o)}catch(s){console.error(s)}}function R1(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;t.endsWith("/")&&(t=t.slice(0,-1));let s=`${t}`;if(t.startsWith("https://t.me")){const n=t.includes("?")?"&startapp=":"?startapp=";s=`${s}${n}${k1(i,!0)}`}else s=`${s}/wc?${i}`;return s}function B1(t){let e="_self";N1()?e="_top":(U1()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function C1(t,e){let r="";try{if(Qr()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Ac(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Pc(){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 Ho(){return typeof at<"u"&&l1.IS_VITEST==="true"}function U1(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function N1(){try{return window.self!==window.top}catch{return!1}}function k1(t,e=!1){const r=ie.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Eh(t){return ie.from(t,"base64").toString("utf-8")}function F1(t){return new Promise(e=>setTimeout(e,t))}let L1=class{constructor({limit:e}){$c(this,"limit"),$c(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}};const Ji=BigInt(2**32-1),Tc=BigInt(32);function xh(t,e=!1){return e?{h:Number(t&Ji),l:Number(t>>Tc&Ji)}:{h:Number(t>>Tc&Ji)|0,l:Number(t&Ji)|0}}function _h(t,e=!1){const r=t.length;let i=new Uint32Array(r),s=new Uint32Array(r);for(let n=0;n<r;n++){const{h:o,l:a}=xh(t[n],e);[i[n],s[n]]=[o,a]}return[i,s]}const Rc=(t,e,r)=>t>>>r,Bc=(t,e,r)=>t<<32-r|e>>>r,tr=(t,e,r)=>t>>>r|e<<32-r,rr=(t,e,r)=>t<<32-r|e>>>r,pi=(t,e,r)=>t<<64-r|e>>>r-32,gi=(t,e,r)=>t>>>r-32|e<<64-r,M1=(t,e)=>e,j1=(t,e)=>t,q1=(t,e,r)=>t<<r|e>>>32-r,z1=(t,e,r)=>e<<r|t>>>32-r,V1=(t,e,r)=>e<<r-32|t>>>64-r,K1=(t,e,r)=>t<<r-32|e>>>64-r;function dt(t,e,r,i){const s=(e>>>0)+(i>>>0);return{h:t+r+(s/2**32|0)|0,l:s|0}}const Wo=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Go=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,H1=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),W1=(t,e,r,i,s)=>e+r+i+s+(t/2**32|0)|0,G1=(t,e,r,i,s)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(s>>>0),Y1=(t,e,r,i,s,n)=>e+r+i+s+n+(t/2**32|0)|0,Fr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Cs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Kt(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function yt(t,...e){if(!Cs(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 Us(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");Kt(t.outputLen),Kt(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 Yo(t,e){yt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Si(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function ct(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function En(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function mt(t,e){return t<<32-e|t>>>e}const Ih=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Sh(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const Nt=Ih?t=>t:t=>Sh(t);function Z1(t){for(let e=0;e<t.length;e++)t[e]=Sh(t[e]);return t}const ir=Ih?t=>t:Z1,Dh=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",J1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Hr(t){if(yt(t),Dh)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=J1[t[r]];return e}const Bt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Cc(t){if(t>=Bt._0&&t<=Bt._9)return t-Bt._0;if(t>=Bt.A&&t<=Bt.F)return t-(Bt.A-10);if(t>=Bt.a&&t<=Bt.f)return t-(Bt.a-10)}function ms(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Dh)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let s=0,n=0;s<r;s++,n+=2){const o=Cc(t.charCodeAt(n)),a=Cc(t.charCodeAt(n+1));if(o===void 0||a===void 0){const c=t[n]+t[n+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+n)}i[s]=o*16+a}return i}function $h(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function gt(t){return typeof t=="string"&&(t=$h(t)),yt(t),t}function nr(...t){let e=0;for(let i=0;i<t.length;i++){const s=t[i];yt(s),e+=s.length}const r=new Uint8Array(e);for(let i=0,s=0;i<t.length;i++){const n=t[i];r.set(n,s),s+=n.length}return r}let Ns=class{};function ki(t){const e=i=>t().update(gt(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function X1(t){const e=(i,s)=>t(s).update(gt(i)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}function Br(t=32){if(Fr&&typeof Fr.getRandomValues=="function")return Fr.getRandomValues(new Uint8Array(t));if(Fr&&typeof Fr.randomBytes=="function")return Uint8Array.from(Fr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Q1=BigInt(0),ai=BigInt(1),ev=BigInt(2),tv=BigInt(7),rv=BigInt(256),iv=BigInt(113),Oh=[],Ah=[],Ph=[];for(let t=0,e=ai,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Oh.push(2*(5*i+r)),Ah.push((t+1)*(t+2)/2%64);let s=Q1;for(let n=0;n<7;n++)e=(e<<ai^(e>>tv)*iv)%rv,e&ev&&(s^=ai<<(ai<<BigInt(n))-ai);Ph.push(s)}const Th=_h(Ph,!0),sv=Th[0],nv=Th[1],Uc=(t,e,r)=>r>32?V1(t,e,r):q1(t,e,r),Nc=(t,e,r)=>r>32?K1(t,e,r):z1(t,e,r);function ov(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[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=r[c],l=r[c+1],h=Uc(u,l,1)^r[a],f=Nc(u,l,1)^r[a+1];for(let p=0;p<50;p+=10)t[o+p]^=h,t[o+p+1]^=f}let s=t[2],n=t[3];for(let o=0;o<24;o++){const a=Ah[o],c=Uc(s,n,a),u=Nc(s,n,a),l=Oh[o];s=t[l],n=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++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=sv[i],t[1]^=nv[i]}ct(r)}let av=class Rh extends Ns{constructor(e,r,i,s=!1,n=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=r,this.outputLen=i,this.enableXOF=s,this.rounds=n,Kt(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Si(this.state)}clone(){return this._cloneInto()}keccak(){ir(this.state32),ov(this.state32,this.rounds),ir(this.state32),this.posOut=0,this.pos=0}update(e){dr(this),e=gt(e),yt(e);const{blockLen:r,state:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(r-this.pos,s-n);for(let a=0;a<o;a++)i[this.pos++]^=e[n++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:s}=this;e[i]^=r,(r&128)!==0&&i===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){dr(this,!1),yt(e),this.finish();const r=this.state,{blockLen:i}=this;for(let s=0,n=e.length;s<n;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,n-s);e.set(r.subarray(this.posOut,this.posOut+o),s),this.posOut+=o,s+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Kt(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Yo(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,ct(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:s,rounds:n,enableXOF:o}=this;return e||(e=new Rh(r,i,s,o,n)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=n,e.suffix=i,e.outputLen=s,e.enableXOF=o,e.destroyed=this.destroyed,e}};const cv=(t,e,r)=>ki(()=>new av(e,t,r)),uv=cv(1,136,256/8);function lv(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n),c=i?4:0,u=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+u,a,i)}function hv(t,e,r){return t&e^~t&r}function fv(t,e,r){return t&e^t&r^e&r}let Bh=class extends Ns{constructor(e,r,i,s){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=s,this.buffer=new Uint8Array(e),this.view=En(this.buffer)}update(e){dr(this),e=gt(e),yt(e);const{view:r,buffer:i,blockLen:s}=this,n=e.length;for(let o=0;o<n;){const a=Math.min(s-this.pos,n-o);if(a===s){const c=En(e);for(;s<=n-o;o+=s)this.process(c,o);continue}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===s&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){dr(this),Yo(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:s,isLE:n}=this;let{pos:o}=this;r[o++]=128,ct(this.buffer.subarray(o)),this.padOffset>s-o&&(this.process(i,0),o=0);for(let h=o;h<s;h++)r[h]=0;lv(i,s-8,BigInt(this.length*8),n),this.process(i,0);const a=En(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const u=c/4,l=this.get();if(u>l.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<u;h++)a.setUint32(4*h,l[h],n)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:s,finished:n,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=n,e.length=s,e.pos=a,s%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}};const Gt=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Re=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Be=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),dv=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]),Yt=new Uint32Array(64);class pv extends Bh{constructor(e=32){super(64,e,8,!1),this.A=Gt[0]|0,this.B=Gt[1]|0,this.C=Gt[2]|0,this.D=Gt[3]|0,this.E=Gt[4]|0,this.F=Gt[5]|0,this.G=Gt[6]|0,this.H=Gt[7]|0}get(){const{A:e,B:r,C:i,D:s,E:n,F:o,G:a,H:c}=this;return[e,r,i,s,n,o,a,c]}set(e,r,i,s,n,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=s|0,this.E=n|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)Yt[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=Yt[h-15],p=Yt[h-2],d=mt(f,7)^mt(f,18)^f>>>3,y=mt(p,17)^mt(p,19)^p>>>10;Yt[h]=y+Yt[h-7]+d+Yt[h-16]|0}let{A:i,B:s,C:n,D:o,E:a,F:c,G:u,H:l}=this;for(let h=0;h<64;h++){const f=mt(a,6)^mt(a,11)^mt(a,25),p=l+f+hv(a,c,u)+dv[h]+Yt[h]|0,d=(mt(i,2)^mt(i,13)^mt(i,22))+fv(i,s,n)|0;l=u,u=c,c=a,a=o+p|0,o=n,n=s,s=i,i=p+d|0}i=i+this.A|0,s=s+this.B|0,n=n+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(i,s,n,o,a,c,u,l)}roundClean(){ct(Yt)}destroy(){this.set(0,0,0,0,0,0,0,0),ct(this.buffer)}}const Ch=_h(["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))),gv=Ch[0],yv=Ch[1],Zt=new Uint32Array(80),Jt=new Uint32Array(80);let Zo=class extends Bh{constructor(e=64){super(128,e,16,!1),this.Ah=Be[0]|0,this.Al=Be[1]|0,this.Bh=Be[2]|0,this.Bl=Be[3]|0,this.Ch=Be[4]|0,this.Cl=Be[5]|0,this.Dh=Be[6]|0,this.Dl=Be[7]|0,this.Eh=Be[8]|0,this.El=Be[9]|0,this.Fh=Be[10]|0,this.Fl=Be[11]|0,this.Gh=Be[12]|0,this.Gl=Be[13]|0,this.Hh=Be[14]|0,this.Hl=Be[15]|0}get(){const{Ah:e,Al:r,Bh:i,Bl:s,Ch:n,Cl:o,Dh:a,Dl:c,Eh:u,El:l,Fh:h,Fl:f,Gh:p,Gl:d,Hh:y,Hl:g}=this;return[e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g]}set(e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g){this.Ah=e|0,this.Al=r|0,this.Bh=i|0,this.Bl=s|0,this.Ch=n|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=u|0,this.El=l|0,this.Fh=h|0,this.Fl=f|0,this.Gh=p|0,this.Gl=d|0,this.Hh=y|0,this.Hl=g|0}process(e,r){for(let w=0;w<16;w++,r+=4)Zt[w]=e.getUint32(r),Jt[w]=e.getUint32(r+=4);for(let w=16;w<80;w++){const I=Zt[w-15]|0,O=Jt[w-15]|0,T=tr(I,O,1)^tr(I,O,8)^Rc(I,O,7),B=rr(I,O,1)^rr(I,O,8)^Bc(I,O,7),N=Zt[w-2]|0,$=Jt[w-2]|0,M=tr(N,$,19)^pi(N,$,61)^Rc(N,$,6),q=rr(N,$,19)^gi(N,$,61)^Bc(N,$,6),R=H1(B,q,Jt[w-7],Jt[w-16]),_=W1(R,T,M,Zt[w-7],Zt[w-16]);Zt[w]=_|0,Jt[w]=R|0}let{Ah:i,Al:s,Bh:n,Bl:o,Ch:a,Cl:c,Dh:u,Dl:l,Eh:h,El:f,Fh:p,Fl:d,Gh:y,Gl:g,Hh:b,Hl:m}=this;for(let w=0;w<80;w++){const I=tr(h,f,14)^tr(h,f,18)^pi(h,f,41),O=rr(h,f,14)^rr(h,f,18)^gi(h,f,41),T=h&p^~h&y,B=f&d^~f&g,N=G1(m,O,B,yv[w],Jt[w]),$=Y1(N,b,I,T,gv[w],Zt[w]),M=N|0,q=tr(i,s,28)^pi(i,s,34)^pi(i,s,39),R=rr(i,s,28)^gi(i,s,34)^gi(i,s,39),_=i&n^i&a^n&a,S=s&o^s&c^o&c;b=y|0,m=g|0,y=p|0,g=d|0,p=h|0,d=f|0,{h,l:f}=dt(u|0,l|0,$|0,M|0),u=a|0,l=c|0,a=n|0,c=o|0,n=i|0,o=s|0;const E=Wo(M,R,S);i=Go(E,$,q,_),s=E|0}({h:i,l:s}=dt(this.Ah|0,this.Al|0,i|0,s|0)),{h:n,l:o}=dt(this.Bh|0,this.Bl|0,n|0,o|0),{h:a,l:c}=dt(this.Ch|0,this.Cl|0,a|0,c|0),{h:u,l}=dt(this.Dh|0,this.Dl|0,u|0,l|0),{h,l:f}=dt(this.Eh|0,this.El|0,h|0,f|0),{h:p,l:d}=dt(this.Fh|0,this.Fl|0,p|0,d|0),{h:y,l:g}=dt(this.Gh|0,this.Gl|0,y|0,g|0),{h:b,l:m}=dt(this.Hh|0,this.Hl|0,b|0,m|0),this.set(i,s,n,o,a,c,u,l,h,f,p,d,y,g,b,m)}roundClean(){ct(Zt,Jt)}destroy(){ct(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class wv extends Zo{constructor(){super(48),this.Ah=Re[0]|0,this.Al=Re[1]|0,this.Bh=Re[2]|0,this.Bl=Re[3]|0,this.Ch=Re[4]|0,this.Cl=Re[5]|0,this.Dh=Re[6]|0,this.Dl=Re[7]|0,this.Eh=Re[8]|0,this.El=Re[9]|0,this.Fh=Re[10]|0,this.Fl=Re[11]|0,this.Gh=Re[12]|0,this.Gl=Re[13]|0,this.Hh=Re[14]|0,this.Hl=Re[15]|0}}const Ce=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class bv extends Zo{constructor(){super(32),this.Ah=Ce[0]|0,this.Al=Ce[1]|0,this.Bh=Ce[2]|0,this.Bl=Ce[3]|0,this.Ch=Ce[4]|0,this.Cl=Ce[5]|0,this.Dh=Ce[6]|0,this.Dl=Ce[7]|0,this.Eh=Ce[8]|0,this.El=Ce[9]|0,this.Fh=Ce[10]|0,this.Fl=Ce[11]|0,this.Gh=Ce[12]|0,this.Gl=Ce[13]|0,this.Hh=Ce[14]|0,this.Hl=Ce[15]|0}}const ks=ki(()=>new pv),mv=ki(()=>new Zo),vv=ki(()=>new wv),Ev=ki(()=>new bv),xv=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]),we=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),j=new Uint32Array(32);function Xt(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=j[2*t],u=j[2*t+1],l=j[2*e],h=j[2*e+1],f=j[2*r],p=j[2*r+1],d=j[2*i],y=j[2*i+1],g=Wo(c,l,o);u=Go(g,u,h,a),c=g|0,{Dh:y,Dl:d}={Dh:y^u,Dl:d^c},{Dh:y,Dl:d}={Dh:M1(y,d),Dl:j1(y)},{h:p,l:f}=dt(p,f,y,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:tr(h,l,24),Bl:rr(h,l,24)},j[2*t]=c,j[2*t+1]=u,j[2*e]=l,j[2*e+1]=h,j[2*r]=f,j[2*r+1]=p,j[2*i]=d,j[2*i+1]=y}function Qt(t,e,r,i,s,n){const o=s[n],a=s[n+1];let c=j[2*t],u=j[2*t+1],l=j[2*e],h=j[2*e+1],f=j[2*r],p=j[2*r+1],d=j[2*i],y=j[2*i+1],g=Wo(c,l,o);u=Go(g,u,h,a),c=g|0,{Dh:y,Dl:d}={Dh:y^u,Dl:d^c},{Dh:y,Dl:d}={Dh:tr(y,d,16),Dl:rr(y,d,16)},{h:p,l:f}=dt(p,f,y,d),{Bh:h,Bl:l}={Bh:h^p,Bl:l^f},{Bh:h,Bl:l}={Bh:pi(h,l,63),Bl:gi(h,l,63)},j[2*t]=c,j[2*t+1]=u,j[2*e]=l,j[2*e+1]=h,j[2*r]=f,j[2*r+1]=p,j[2*i]=d,j[2*i+1]=y}function _v(t,e={},r,i,s){if(Kt(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:n,salt:o,personalization:a}=e;if(n!==void 0&&(n.length<1||n.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==s)throw new Error("personalization must be undefined or "+s)}class Iv extends Ns{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,Kt(e),Kt(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=Si(this.buffer)}update(e){dr(this),e=gt(e),yt(e);const{blockLen:r,buffer:i,buffer32:s}=this,n=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<n;){this.pos===r&&(ir(s),this.compress(s,0,!1),ir(s),this.pos=0);const u=Math.min(r-this.pos,n-c),l=o+c;if(u===r&&!(l%4)&&c+u<n){const h=new Uint32Array(a,l,Math.floor((n-c)/4));ir(h);for(let f=0;c+r<n;f+=s.length,c+=r)this.length+=r,this.compress(h,f,!1);ir(h);continue}i.set(e.subarray(c,c+u),this.pos),this.pos+=u,this.length+=u,c+=u}return this}digestInto(e){dr(this),Yo(e,this);const{pos:r,buffer32:i}=this;this.finished=!0,ct(this.buffer.subarray(r)),ir(i),this.compress(i,0,!0),ir(i);const s=Si(e);this.get().forEach((n,o)=>s[o]=Nt(n))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){const{buffer:r,length:i,finished:s,destroyed:n,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=n,e.finished=s,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Sv extends Iv{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),this.v0l=we[0]|0,this.v0h=we[1]|0,this.v1l=we[2]|0,this.v1h=we[3]|0,this.v2l=we[4]|0,this.v2h=we[5]|0,this.v3l=we[6]|0,this.v3h=we[7]|0,this.v4l=we[8]|0,this.v4h=we[9]|0,this.v5l=we[10]|0,this.v5h=we[11]|0,this.v6l=we[12]|0,this.v6h=we[13]|0,this.v7l=we[14]|0,this.v7h=we[15]|0,_v(r,e,64,16,16);let{key:i,personalization:s,salt:n}=e,o=0;if(i!==void 0&&(i=gt(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,n!==void 0){n=gt(n);const a=Si(n);this.v4l^=Nt(a[0]),this.v4h^=Nt(a[1]),this.v5l^=Nt(a[2]),this.v5h^=Nt(a[3])}if(s!==void 0){s=gt(s);const a=Si(s);this.v6l^=Nt(a[0]),this.v6h^=Nt(a[1]),this.v7l^=Nt(a[2]),this.v7h^=Nt(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:i,v1h:s,v2l:n,v2h:o,v3l:a,v3h:c,v4l:u,v4h:l,v5l:h,v5h:f,v6l:p,v6h:d,v7l:y,v7h:g}=this;return[e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g]}set(e,r,i,s,n,o,a,c,u,l,h,f,p,d,y,g){this.v0l=e|0,this.v0h=r|0,this.v1l=i|0,this.v1h=s|0,this.v2l=n|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=u|0,this.v4h=l|0,this.v5l=h|0,this.v5h=f|0,this.v6l=p|0,this.v6h=d|0,this.v7l=y|0,this.v7h=g|0}compress(e,r,i){this.get().forEach((c,u)=>j[u]=c),j.set(we,16);let{h:s,l:n}=xh(BigInt(this.length));j[24]=we[8]^n,j[25]=we[9]^s,i&&(j[28]=~j[28],j[29]=~j[29]);let o=0;const a=xv;for(let c=0;c<12;c++)Xt(0,4,8,12,e,r+2*a[o++]),Qt(0,4,8,12,e,r+2*a[o++]),Xt(1,5,9,13,e,r+2*a[o++]),Qt(1,5,9,13,e,r+2*a[o++]),Xt(2,6,10,14,e,r+2*a[o++]),Qt(2,6,10,14,e,r+2*a[o++]),Xt(3,7,11,15,e,r+2*a[o++]),Qt(3,7,11,15,e,r+2*a[o++]),Xt(0,5,10,15,e,r+2*a[o++]),Qt(0,5,10,15,e,r+2*a[o++]),Xt(1,6,11,12,e,r+2*a[o++]),Qt(1,6,11,12,e,r+2*a[o++]),Xt(2,7,8,13,e,r+2*a[o++]),Qt(2,7,8,13,e,r+2*a[o++]),Xt(3,4,9,14,e,r+2*a[o++]),Qt(3,4,9,14,e,r+2*a[o++]);this.v0l^=j[0]^j[16],this.v0h^=j[1]^j[17],this.v1l^=j[2]^j[18],this.v1h^=j[3]^j[19],this.v2l^=j[4]^j[20],this.v2h^=j[5]^j[21],this.v3l^=j[6]^j[22],this.v3h^=j[7]^j[23],this.v4l^=j[8]^j[24],this.v4h^=j[9]^j[25],this.v5l^=j[10]^j[26],this.v5h^=j[11]^j[27],this.v6l^=j[12]^j[28],this.v6h^=j[13]^j[29],this.v7l^=j[14]^j[30],this.v7h^=j[15]^j[31],ct(j)}destroy(){this.destroyed=!0,ct(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const Dv=X1(t=>new Sv(t)),$v="https://rpc.walletconnect.org/v1";function Uh(t){const e=`Ethereum Signed Message:
${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+ie.from(uv(r)).toString("hex")}async function Ov(t,e,r,i,s,n){switch(r.t){case"eip191":return await Av(t,e,r.s);case"eip1271":return await Pv(t,e,r.s,i,s,n);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Av(t,e,r){const i=db(r);return _b({payload:Uh(e),signature:i}).toLowerCase()===t.toLowerCase()}async function Pv(t,e,r,i,s,n){const o=os(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",u=r.substring(2),l=(u.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Uh(e)).substring(2),f=a+h+c+l+u,p=await fetch(`${n||$v}/?chainId=${i}&projectId=${s}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Tv(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:d}=await p.json();return d?d.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Tv(){return Date.now()+Math.floor(Math.random()*1e3)}function Rv(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const s=1+i*64;if(r.length<s)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const n=ie.from(t,"base64").slice(1,65);return Ci.encode(n)}function Bv(t){const e=new Uint8Array(ie.from(t,"base64")),r=Array.from("TransactionData::").map(n=>n.charCodeAt(0)),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length);const s=Dv(i,{dkLen:32});return Ci.encode(s)}function kc(t){const e=new Uint8Array(ks(Cv(t)));return Ci.encode(e)}function Cv(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 Fc(t){const e=ie.from(t,"base64"),r=cm(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const i=Qb(r),s=ie.from("TX"),n=ie.concat([s,ie.from(i)]),o=Ev(n);return Eb.encode(o).replace(/=+$/,"")}function xn(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),ie.from(e)}function Uv(t){const e=ie.from(t.signed.bodyBytes,"base64"),r=ie.from(t.signed.authInfoBytes,"base64"),i=ie.from(t.signature.signature,"base64"),s=[];s.push(ie.from([10])),s.push(xn(e.length)),s.push(e),s.push(ie.from([18])),s.push(xn(r.length)),s.push(r),s.push(ie.from([26])),s.push(xn(i.length)),s.push(i);const n=ie.concat(s),o=ks(n);return ie.from(o).toString("hex").toUpperCase()}function Nv(t){var e,r;const i=[];try{if(typeof t=="string")return i.push(t),i;if(typeof t!="object")return i;t!=null&&t.id&&i.push(t.id);const s=(r=(e=t?.capabilities)==null?void 0:e.caip345)==null?void 0:r.transactionHashes;s&&i.push(...s)}catch(s){console.warn("getWalletSendCallsHashes failed: ",s)}return i}var kv=Object.defineProperty,Fv=Object.defineProperties,Lv=Object.getOwnPropertyDescriptors,Lc=Object.getOwnPropertySymbols,Mv=Object.prototype.hasOwnProperty,jv=Object.prototype.propertyIsEnumerable,Mc=(t,e,r)=>e in t?kv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qv=(t,e)=>{for(var r in e||(e={}))Mv.call(e,r)&&Mc(t,r,e[r]);if(Lc)for(var r of Lc(e))jv.call(e,r)&&Mc(t,r,e[r]);return t},zv=(t,e)=>Fv(t,Lv(e));const Nh="did:pkh:",Vv={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Kv=t=>t?Vv[t]||t:"",Fs=t=>t?.split(":"),Hv=t=>{const e=t&&Fs(t);if(e)return t.includes(Nh)?e[3]:e[1]},Wv=t=>{const e=t&&Fs(t);if(e)return t.includes(Nh)?e[2]:e[0]},no=t=>{const e=t&&Fs(t);if(e)return e[2]+":"+e[3]},vs=t=>{const e=t&&Fs(t);if(e)return e.pop()};async function jc(t){const{cacao:e,projectId:r}=t,{s:i,p:s}=e,n=kh(s,s.iss),o=vs(s.iss);return await Ov(o,n,i,no(s.iss),r)}const kh=(t,e)=>{const r=Wv(e);if(!r)throw new Error("Invalid issuer: "+e);const i=`${t.domain} wants you to sign in with your ${Kv(r)} account:`,s=vs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let n=t.statement||void 0;const o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${Hv(e)}`,u=`Nonce: ${t.nonce}`,l=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,p=t.requestId?`Request ID: ${t.requestId}`:void 0,d=t.resources?`Resources:${t.resources.map(g=>`
- ${g}`).join("")}`:void 0,y=as(t.resources);if(y){const g=Di(y);n=r2(n,g)}return[i,s,"",n,"",o,a,c,u,l,h,f,p,d].filter(g=>g!=null).join(`
`)};function Gv(t){return ie.from(JSON.stringify(t)).toString("base64")}function Yv(t){return JSON.parse(ie.from(t,"base64").toString("utf-8"))}function Ar(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(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(s=>{const n=i[s];if(!Array.isArray(n))throw new Error(`Ability limits ${s} must be an array of objects, found: ${n}`);if(!n.length)throw new Error(`Value of ${s} is empty array, must be an array with objects`);n.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${s}) must be an array of objects, found: ${o}`)})})})}function Zv(t,e,r,i={}){return r?.sort((s,n)=>s.localeCompare(n)),{att:{[t]:Jv(e,r,i)}}}function Jv(t,e,r={}){e=e?.sort((s,n)=>s.localeCompare(n));const i=e.map(s=>({[`${t}/${s}`]:[r]}));return Object.assign({},...i)}function Fh(t){return Ar(t),`urn:recap:${Gv(t).replace(/=/g,"")}`}function Di(t){const e=Yv(t.replace("urn:recap:",""));return Ar(e),e}function Xv(t,e,r){const i=Zv(t,e,r);return Fh(i)}function Qv(t){return t&&t.includes("urn:recap:")}function e2(t,e){const r=Di(t),i=Di(e),s=t2(r,i);return Fh(s)}function t2(t,e){Ar(t),Ar(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((s,n)=>s.localeCompare(n)),i={att:{}};return r.forEach(s=>{var n,o;Object.keys(((n=t.att)==null?void 0:n[s])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[s])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,u;i.att[s]=zv(qv({},i.att[s]),{[a]:((c=t.att[s])==null?void 0:c[a])||((u=e.att[s])==null?void 0:u[a])})})}),i}function r2(t="",e){Ar(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let s=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const u={};c.forEach(h=>{u[h.ability]||(u[h.ability]=[]),u[h.ability].push(h.action)});const l=Object.keys(u).map(h=>(s++,`(${s}) '${h}': '${u[h].join("', '")}' for '${a}'.`));i.push(l.join(", ").replace(".,","."))});const n=i.join(" "),o=`${r}${n}`;return`${t?t+" ":""}${o}`}function qc(t){var e;const r=Di(t);Ar(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(s=>s.split("/")[1]):[]}function zc(t){const e=Di(t);Ar(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(s=>{var n;(n=s?.[0])!=null&&n.chains&&r.push(s[0].chains)})}),[...new Set(r.flat())]}function as(t){if(!t)return;const e=t?.[t.length-1];return Qv(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Lh(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function oo(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function _n(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function ze(t,...e){if(!Lh(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 Vc(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 i2(t,e){ze(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function hr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Yr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function s2(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const n2=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o2(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ao(t){if(typeof t=="string")t=o2(t);else if(Lh(t))t=co(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function a2(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function c2(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const u2=(t,e)=>{function r(i,...s){if(ze(i),!n2)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const u=s[0];if(!u)throw new Error("nonce / iv required");t.varSizeNonce?ze(u):ze(u,t.nonceLength)}const n=t.tagLength;n&&s[1]!==void 0&&ze(s[1]);const o=e(i,...s),a=(u,l)=>{if(l!==void 0){if(u!==2)throw new Error("cipher output not supported");ze(l)}};let c=!1;return{encrypt(u,l){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,ze(u),a(o.encrypt.length,l),o.encrypt(u,l)},decrypt(u,l){if(ze(u),n&&u.length<n)throw new Error("invalid ciphertext length: smaller than tagLength="+n);return a(o.decrypt.length,l),o.decrypt(u,l)}}}return Object.assign(r,t),r};function Kc(t,e,r=!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(r&&!h2(e))throw new Error("invalid output, must be aligned");return e}function Hc(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const s=BigInt(32),n=BigInt(4294967295),o=Number(r>>s&n),a=Number(r&n);t.setUint32(e+4,o,i),t.setUint32(e+0,a,i)}function l2(t,e,r){oo(r);const i=new Uint8Array(16),s=s2(i);return Hc(s,0,BigInt(e),r),Hc(s,8,BigInt(t),r),i}function h2(t){return t.byteOffset%4===0}function co(t){return Uint8Array.from(t)}const Mh=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),f2=Mh("expand 16-byte k"),d2=Mh("expand 32-byte k"),p2=hr(f2),g2=hr(d2);function te(t,e){return t<<e|t>>>32-e}function uo(t){return t.byteOffset%4===0}const Xi=64,y2=16,jh=2**32-1,Wc=new Uint32Array;function w2(t,e,r,i,s,n,o,a){const c=s.length,u=new Uint8Array(Xi),l=hr(u),h=uo(s)&&uo(n),f=h?hr(s):Wc,p=h?hr(n):Wc;for(let d=0;d<c;o++){if(t(e,r,i,l,o,a),o>=jh)throw new Error("arx: counter overflow");const y=Math.min(Xi,c-d);if(h&&y===Xi){const g=d/4;if(d%4!==0)throw new Error("arx: invalid block position");for(let b=0,m;b<y2;b++)m=g+b,p[m]=f[m]^l[b];d+=Xi;continue}for(let g=0,b;g<y;g++)b=d+g,n[b]=s[b]^u[g];d+=y}}function b2(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:s,counterRight:n,rounds:o}=a2({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return _n(s),_n(o),oo(n),oo(r),(a,c,u,l,h=0)=>{ze(a),ze(c),ze(u);const f=u.length;if(l===void 0&&(l=new Uint8Array(f)),ze(l),_n(h),h<0||h>=jh)throw new Error("arx: counter overflow");if(l.length<f)throw new Error(`arx: output (${l.length}) is shorter than data (${f})`);const p=[];let d=a.length,y,g;if(d===32)p.push(y=co(a)),g=g2;else if(d===16&&r)y=new Uint8Array(32),y.set(a),y.set(a,16),g=p2,p.push(y);else throw new Error(`arx: invalid 32-byte key, got length=${d}`);uo(c)||p.push(c=co(c));const b=hr(y);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(g,b,hr(c.subarray(0,16)),b),c=c.subarray(16)}const m=16-s;if(m!==c.length)throw new Error(`arx: nonce must be ${m} or 16 bytes`);if(m!==12){const I=new Uint8Array(12);I.set(c,n?0:12-c.length),c=I,p.push(c)}const w=hr(c);return w2(t,g,b,w,u,l,h,o),Yr(...p),l}}const Se=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class m2{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=ao(e),ze(e,32);const r=Se(e,0),i=Se(e,2),s=Se(e,4),n=Se(e,6),o=Se(e,8),a=Se(e,10),c=Se(e,12),u=Se(e,14);this.r[0]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>10|s<<6)&7939,this.r[3]=(s>>>7|n<<9)&8191,this.r[4]=(n>>>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]=Se(e,16+2*l)}process(e,r,i=!1){const s=i?0:2048,{h:n,r:o}=this,a=o[0],c=o[1],u=o[2],l=o[3],h=o[4],f=o[5],p=o[6],d=o[7],y=o[8],g=o[9],b=Se(e,r+0),m=Se(e,r+2),w=Se(e,r+4),I=Se(e,r+6),O=Se(e,r+8),T=Se(e,r+10),B=Se(e,r+12),N=Se(e,r+14);let $=n[0]+(b&8191),M=n[1]+((b>>>13|m<<3)&8191),q=n[2]+((m>>>10|w<<6)&8191),R=n[3]+((w>>>7|I<<9)&8191),_=n[4]+((I>>>4|O<<12)&8191),S=n[5]+(O>>>1&8191),E=n[6]+((O>>>14|T<<2)&8191),v=n[7]+((T>>>11|B<<5)&8191),D=n[8]+((B>>>8|N<<8)&8191),P=n[9]+(N>>>5|s),x=0,A=x+$*a+M*(5*g)+q*(5*y)+R*(5*d)+_*(5*p);x=A>>>13,A&=8191,A+=S*(5*f)+E*(5*h)+v*(5*l)+D*(5*u)+P*(5*c),x+=A>>>13,A&=8191;let U=x+$*c+M*a+q*(5*g)+R*(5*y)+_*(5*d);x=U>>>13,U&=8191,U+=S*(5*p)+E*(5*f)+v*(5*h)+D*(5*l)+P*(5*u),x+=U>>>13,U&=8191;let k=x+$*u+M*c+q*a+R*(5*g)+_*(5*y);x=k>>>13,k&=8191,k+=S*(5*d)+E*(5*p)+v*(5*f)+D*(5*h)+P*(5*l),x+=k>>>13,k&=8191;let K=x+$*l+M*u+q*c+R*a+_*(5*g);x=K>>>13,K&=8191,K+=S*(5*y)+E*(5*d)+v*(5*p)+D*(5*f)+P*(5*h),x+=K>>>13,K&=8191;let V=x+$*h+M*l+q*u+R*c+_*a;x=V>>>13,V&=8191,V+=S*(5*g)+E*(5*y)+v*(5*d)+D*(5*p)+P*(5*f),x+=V>>>13,V&=8191;let z=x+$*f+M*h+q*l+R*u+_*c;x=z>>>13,z&=8191,z+=S*a+E*(5*g)+v*(5*y)+D*(5*d)+P*(5*p),x+=z>>>13,z&=8191;let H=x+$*p+M*f+q*h+R*l+_*u;x=H>>>13,H&=8191,H+=S*c+E*a+v*(5*g)+D*(5*y)+P*(5*d),x+=H>>>13,H&=8191;let Y=x+$*d+M*p+q*f+R*h+_*l;x=Y>>>13,Y&=8191,Y+=S*u+E*c+v*a+D*(5*g)+P*(5*y),x+=Y>>>13,Y&=8191;let X=x+$*y+M*d+q*p+R*f+_*h;x=X>>>13,X&=8191,X+=S*l+E*u+v*c+D*a+P*(5*g),x+=X>>>13,X&=8191;let W=x+$*g+M*y+q*d+R*p+_*f;x=W>>>13,W&=8191,W+=S*h+E*l+v*u+D*c+P*a,x+=W>>>13,W&=8191,x=(x<<2)+x|0,x=x+A|0,A=x&8191,x=x>>>13,U+=x,n[0]=A,n[1]=U,n[2]=k,n[3]=K,n[4]=V,n[5]=z,n[6]=H,n[7]=Y,n[8]=X,n[9]=W}finalize(){const{h:e,pad:r}=this,i=new Uint16Array(10);let s=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=s,s=e[a]>>>13,e[a]&=8191;e[0]+=s*5,s=e[0]>>>13,e[0]&=8191,e[1]+=s,s=e[1]>>>13,e[1]&=8191,e[2]+=s,i[0]=e[0]+5,s=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+s,s=i[a]>>>13,i[a]&=8191;i[9]-=8192;let n=(s^1)-1;for(let a=0;a<10;a++)i[a]&=n;n=~n;for(let a=0;a<10;a++)e[a]=e[a]&n|i[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]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Yr(i)}update(e){Vc(this),e=ao(e),ze(e);const{buffer:r,blockLen:i}=this,s=e.length;for(let n=0;n<s;){const o=Math.min(i-this.pos,s-n);if(o===i){for(;i<=s-n;n+=i)this.process(e,n);continue}r.set(e.subarray(n,n+o),this.pos),this.pos+=o,n+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Yr(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vc(this),i2(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:s}=this;if(s){for(r[s++]=1;s<16;s++)r[s]=0;this.process(r,0,!0)}this.finalize();let n=0;for(let o=0;o<8;o++)e[n++]=i[o]>>>0,e[n++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function v2(t){const e=(i,s)=>t(s).update(ao(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const E2=v2(t=>new m2(t));function x2(t,e,r,i,s,n=20){let o=t[0],a=t[1],c=t[2],u=t[3],l=e[0],h=e[1],f=e[2],p=e[3],d=e[4],y=e[5],g=e[6],b=e[7],m=s,w=r[0],I=r[1],O=r[2],T=o,B=a,N=c,$=u,M=l,q=h,R=f,_=p,S=d,E=y,v=g,D=b,P=m,x=w,A=I,U=O;for(let K=0;K<n;K+=2)T=T+M|0,P=te(P^T,16),S=S+P|0,M=te(M^S,12),T=T+M|0,P=te(P^T,8),S=S+P|0,M=te(M^S,7),B=B+q|0,x=te(x^B,16),E=E+x|0,q=te(q^E,12),B=B+q|0,x=te(x^B,8),E=E+x|0,q=te(q^E,7),N=N+R|0,A=te(A^N,16),v=v+A|0,R=te(R^v,12),N=N+R|0,A=te(A^N,8),v=v+A|0,R=te(R^v,7),$=$+_|0,U=te(U^$,16),D=D+U|0,_=te(_^D,12),$=$+_|0,U=te(U^$,8),D=D+U|0,_=te(_^D,7),T=T+q|0,U=te(U^T,16),v=v+U|0,q=te(q^v,12),T=T+q|0,U=te(U^T,8),v=v+U|0,q=te(q^v,7),B=B+R|0,P=te(P^B,16),D=D+P|0,R=te(R^D,12),B=B+R|0,P=te(P^B,8),D=D+P|0,R=te(R^D,7),N=N+_|0,x=te(x^N,16),S=S+x|0,_=te(_^S,12),N=N+_|0,x=te(x^N,8),S=S+x|0,_=te(_^S,7),$=$+M|0,A=te(A^$,16),E=E+A|0,M=te(M^E,12),$=$+M|0,A=te(A^$,8),E=E+A|0,M=te(M^E,7);let k=0;i[k++]=o+T|0,i[k++]=a+B|0,i[k++]=c+N|0,i[k++]=u+$|0,i[k++]=l+M|0,i[k++]=h+q|0,i[k++]=f+R|0,i[k++]=p+_|0,i[k++]=d+S|0,i[k++]=y+E|0,i[k++]=g+v|0,i[k++]=b+D|0,i[k++]=m+P|0,i[k++]=w+x|0,i[k++]=I+A|0,i[k++]=O+U|0}const _2=b2(x2,{counterRight:!1,counterLength:4,allowShortKeys:!1}),I2=new Uint8Array(16),Gc=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(I2.subarray(r))},S2=new Uint8Array(32);function Yc(t,e,r,i,s){const n=t(e,r,S2),o=E2.create(n);s&&Gc(o,s),Gc(o,i);const a=l2(i.length,s?s.length:0,!0);o.update(a);const c=o.digest();return Yr(n,a),c}const D2=t=>(e,r,i)=>({encrypt(s,n){const o=s.length;n=Kc(o+16,n,!1),n.set(s);const a=n.subarray(0,-16);t(e,r,a,a,1);const c=Yc(t,e,r,a,i);return n.set(c,o),Yr(c),n},decrypt(s,n){n=Kc(s.length-16,n,!1);const o=s.subarray(0,-16),a=s.subarray(-16),c=Yc(t,e,r,o,i);if(!c2(a,c))throw new Error("invalid tag");return n.set(s.subarray(0,-16)),t(e,r,n,n,1),Yr(c),n}}),qh=u2({blockSize:64,nonceLength:12,tagLength:16},D2(_2));let zh=class extends Ns{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Us(e);const i=gt(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const s=this.blockLen,n=new Uint8Array(s);n.set(i.length>s?e.create().update(i).digest():i);for(let o=0;o<n.length;o++)n[o]^=54;this.iHash.update(n),this.oHash=e.create();for(let o=0;o<n.length;o++)n[o]^=106;this.oHash.update(n),ct(n)}update(e){return dr(this),this.iHash.update(e),this}digestInto(e){dr(this),yt(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:r,iHash:i,finished:s,destroyed:n,blockLen:o,outputLen:a}=this;return e=e,e.finished=s,e.destroyed=n,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const Ls=(t,e,r)=>new zh(t,e).update(r).digest();Ls.create=(t,e)=>new zh(t,e);function $2(t,e,r){return Us(t),r===void 0&&(r=new Uint8Array(t.outputLen)),Ls(t,gt(r),gt(e))}const In=Uint8Array.from([0]),Zc=Uint8Array.of();function O2(t,e,r,i=32){Us(t),Kt(i);const s=t.outputLen;if(i>255*s)throw new Error("Length should be <= 255*HashLen");const n=Math.ceil(i/s);r===void 0&&(r=Zc);const o=new Uint8Array(n*s),a=Ls.create(t,e),c=a._cloneInto(),u=new Uint8Array(a.outputLen);for(let l=0;l<n;l++)In[0]=l+1,c.update(l===0?Zc:u).update(r).update(In).digestInto(u),o.set(u,s*l),a._cloneInto(c);return a.destroy(),c.destroy(),ct(u,In),o.slice(0,i)}const A2=(t,e,r,i,s)=>O2(t,$2(t,e,r),i,s),Ms=ks,Jo=BigInt(0),lo=BigInt(1);function Es(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Dr(t,e,r=""){const i=Cs(t),s=t?.length,n=e!==void 0;if(!i||n&&s!==e){const o=r&&`"${r}" `,a=n?` of length ${e}`:"",c=i?`length=${s}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qi(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Vh(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Jo:BigInt("0x"+t)}function js(t){return Vh(Hr(t))}function xs(t){return yt(t),Vh(Hr(Uint8Array.from(t).reverse()))}function Xo(t,e){return ms(t.toString(16).padStart(e*2,"0"))}function Qo(t,e){return Xo(t,e).reverse()}function Ne(t,e,r){let i;if(typeof e=="string")try{i=ms(e)}catch(n){throw new Error(t+" must be hex string or Uint8Array, cause: "+n)}else if(Cs(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const s=i.length;if(typeof r=="number"&&s!==r)throw new Error(t+" of length "+r+" expected, got "+s);return i}const Sn=t=>typeof t=="bigint"&&Jo<=t;function P2(t,e,r){return Sn(t)&&Sn(e)&&Sn(r)&&e<=t&&t<r}function ho(t,e,r,i){if(!P2(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function Kh(t){let e;for(e=0;t>Jo;t>>=lo,e+=1);return e}const Fi=t=>(lo<<BigInt(t))-lo;function T2(t,e,r){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 r!="function")throw new Error("hmacFn must be a function");const i=f=>new Uint8Array(f),s=f=>Uint8Array.of(f);let n=i(t),o=i(t),a=0;const c=()=>{n.fill(1),o.fill(0),a=0},u=(...f)=>r(o,n,...f),l=(f=i(0))=>{o=u(s(0),f),n=u(),f.length!==0&&(o=u(s(1),f),n=u())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const p=[];for(;f<e;){n=u();const d=n.slice();p.push(d),f+=n.length}return nr(...p)};return(f,p)=>{c(),l(f);let d;for(;!(d=p(h()));)l();return c(),d}}function qs(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function i(s,n,o){const a=t[s];if(o&&a===void 0)return;const c=typeof a;if(c!==n||a===null)throw new Error(`param "${s}" is invalid: expected ${n}, got ${c}`)}Object.entries(e).forEach(([s,n])=>i(s,n,!1)),Object.entries(r).forEach(([s,n])=>i(s,n,!0))}function Jc(t){const e=new WeakMap;return(r,...i)=>{const s=e.get(r);if(s!==void 0)return s;const n=t(r,...i);return e.set(r,n),n}}const Ke=BigInt(0),ke=BigInt(1),$r=BigInt(2),Hh=BigInt(3),Wh=BigInt(4),Gh=BigInt(5),R2=BigInt(7),Yh=BigInt(8),B2=BigInt(9),Zh=BigInt(16);function Xe(t,e){const r=t%e;return r>=Ke?r:e+r}function ft(t,e,r){let i=t;for(;e-- >Ke;)i*=i,i%=r;return i}function Xc(t,e){if(t===Ke)throw new Error("invert: expected non-zero number");if(e<=Ke)throw new Error("invert: expected positive modulus, got "+e);let r=Xe(t,e),i=e,s=Ke,n=ke;for(;r!==Ke;){const o=i/r,a=i%r,c=s-n*o;i=r,r=a,s=n,n=c}if(i!==ke)throw new Error("invert: does not exist");return Xe(s,e)}function ea(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function Jh(t,e){const r=(t.ORDER+ke)/Wh,i=t.pow(e,r);return ea(t,i,e),i}function C2(t,e){const r=(t.ORDER-Gh)/Yh,i=t.mul(e,$r),s=t.pow(i,r),n=t.mul(e,s),o=t.mul(t.mul(n,$r),s),a=t.mul(n,t.sub(o,t.ONE));return ea(t,a,e),a}function U2(t){const e=yr(t),r=Xh(t),i=r(e,e.neg(e.ONE)),s=r(e,i),n=r(e,e.neg(i)),o=(t+R2)/Zh;return(a,c)=>{let u=a.pow(c,o),l=a.mul(u,i);const h=a.mul(u,s),f=a.mul(u,n),p=a.eql(a.sqr(l),c),d=a.eql(a.sqr(h),c);u=a.cmov(u,l,p),l=a.cmov(f,h,d);const y=a.eql(a.sqr(l),c),g=a.cmov(u,l,y);return ea(a,g,c),g}}function Xh(t){if(t<Hh)throw new Error("sqrt is not defined for small field");let e=t-ke,r=0;for(;e%$r===Ke;)e/=$r,r++;let i=$r;const s=yr(t);for(;Qc(s,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return Jh;let n=s.pow(i,e);const o=(e+ke)/$r;return function(a,c){if(a.is0(c))return c;if(Qc(a,c)!==1)throw new Error("Cannot find square root");let u=r,l=a.mul(a.ONE,n),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let p=1,d=a.sqr(h);for(;!a.eql(d,a.ONE);)if(p++,d=a.sqr(d),p===u)throw new Error("Cannot find square root");const y=ke<<BigInt(u-p-1),g=a.pow(l,y);u=p,l=a.sqr(g),h=a.mul(h,l),f=a.mul(f,g)}return f}}function N2(t){return t%Wh===Hh?Jh:t%Yh===Gh?C2:t%Zh===B2?U2(t):Xh(t)}const k2=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function F2(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=k2.reduce((i,s)=>(i[s]="function",i),e);return qs(t,r),t}function L2(t,e,r){if(r<Ke)throw new Error("invalid exponent, negatives unsupported");if(r===Ke)return t.ONE;if(r===ke)return e;let i=t.ONE,s=e;for(;r>Ke;)r&ke&&(i=t.mul(i,s)),s=t.sqr(s),r>>=ke;return i}function Qh(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),s=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),n=t.inv(s);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),n),i}function Qc(t,e){const r=(t.ORDER-ke)/$r,i=t.pow(e,r),s=t.eql(i,t.ONE),n=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!s&&!n&&!o)throw new Error("invalid Legendre symbol result");return s?1:n?0:-1}function ef(t,e){e!==void 0&&Kt(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function yr(t,e,r=!1,i={}){if(t<=Ke)throw new Error("invalid field: expected ORDER > 0, got "+t);let s,n,o=!1,a;if(typeof e=="object"&&e!=null){if(i.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(s=f.BITS),f.sqrt&&(n=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(s=e),i.sqrt&&(n=i.sqrt);const{nBitLength:c,nByteLength:u}=ef(t,s);if(u>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let l;const h=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:u,MASK:Fi(c),ZERO:Ke,ONE:ke,allowedLengths:a,create:f=>Xe(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return Ke<=f&&f<t},is0:f=>f===Ke,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&ke)===ke,neg:f=>Xe(-f,t),eql:(f,p)=>f===p,sqr:f=>Xe(f*f,t),add:(f,p)=>Xe(f+p,t),sub:(f,p)=>Xe(f-p,t),mul:(f,p)=>Xe(f*p,t),pow:(f,p)=>L2(h,f,p),div:(f,p)=>Xe(f*Xc(p,t),t),sqrN:f=>f*f,addN:(f,p)=>f+p,subN:(f,p)=>f-p,mulN:(f,p)=>f*p,inv:f=>Xc(f,t),sqrt:n||(f=>(l||(l=N2(t)),l(h,f))),toBytes:f=>r?Qo(f,u):Xo(f,u),fromBytes:(f,p=!0)=>{if(a){if(!a.includes(f.length)||f.length>u)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const y=new Uint8Array(u);y.set(f,r?0:y.length-f.length),f=y}if(f.length!==u)throw new Error("Field.fromBytes: expected "+u+" bytes, got "+f.length);let d=r?xs(f):js(f);if(o&&(d=Xe(d,t)),!p&&!h.isValid(d))throw new Error("invalid field element: outside of range 0..ORDER");return d},invertBatch:f=>Qh(h,f),cmov:(f,p,d)=>d?p:f});return Object.freeze(h)}function tf(t){if(typeof t!="bigint")throw new Error("field order must be bigint");const e=t.toString(2).length;return Math.ceil(e/8)}function rf(t){const e=tf(t);return e+Math.ceil(e/2)}function M2(t,e,r=!1){const i=t.length,s=tf(e),n=rf(e);if(i<16||i<n||i>1024)throw new Error("expected "+n+"-1024 bytes of input, got "+i);const o=r?xs(t):js(t),a=Xe(o,e-ke)+ke;return r?Qo(a,s):Xo(a,s)}const Zr=BigInt(0),Or=BigInt(1);function _s(t,e){const r=e.negate();return t?r:e}function Dn(t,e){const r=Qh(t.Fp,e.map(i=>i.Z));return e.map((i,s)=>t.fromAffine(i.toAffine(r[s])))}function sf(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function $n(t,e){sf(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),s=2**t,n=Fi(t),o=BigInt(t);return{windows:r,windowSize:i,mask:n,maxNumber:s,shiftBy:o}}function eu(t,e,r){const{windowSize:i,mask:s,maxNumber:n,shiftBy:o}=r;let a=Number(t&s),c=t>>o;a>i&&(a-=n,c+=Or);const u=e*i,l=u+Math.abs(a)-1,h=a===0,f=a<0,p=e%2!==0;return{nextN:c,offset:l,isZero:h,isNeg:f,isNegF:p,offsetF:u}}function j2(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function q2(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const On=new WeakMap,nf=new WeakMap;function An(t){return nf.get(t)||1}function tu(t){if(t!==Zr)throw new Error("invalid wNAF")}class z2{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,i=this.ZERO){let s=e;for(;r>Zr;)r&Or&&(i=i.add(s)),s=s.double(),r>>=Or;return i}precomputeWindow(e,r){const{windows:i,windowSize:s}=$n(r,this.bits),n=[];let o=e,a=o;for(let c=0;c<i;c++){a=o,n.push(a);for(let u=1;u<s;u++)a=a.add(o),n.push(a);o=a.double()}return n}wNAF(e,r,i){if(!this.Fn.isValid(i))throw new Error("invalid scalar");let s=this.ZERO,n=this.BASE;const o=$n(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:u,isZero:l,isNeg:h,isNegF:f,offsetF:p}=eu(i,a,o);i=c,l?n=n.add(_s(f,r[p])):s=s.add(_s(h,r[u]))}return tu(i),{p:s,f:n}}wNAFUnsafe(e,r,i,s=this.ZERO){const n=$n(e,this.bits);for(let o=0;o<n.windows&&i!==Zr;o++){const{nextN:a,offset:c,isZero:u,isNeg:l}=eu(i,o,n);if(i=a,!u){const h=r[c];s=s.add(l?h.negate():h)}}return tu(i),s}getPrecomputes(e,r,i){let s=On.get(r);return s||(s=this.precomputeWindow(r,e),e!==1&&(typeof i=="function"&&(s=i(s)),On.set(r,s))),s}cached(e,r,i){const s=An(e);return this.wNAF(s,this.getPrecomputes(s,e,i),r)}unsafe(e,r,i,s){const n=An(e);return n===1?this._unsafeLadder(e,r,s):this.wNAFUnsafe(n,this.getPrecomputes(n,e,i),r,s)}createCache(e,r){sf(r,this.bits),nf.set(e,r),On.delete(e)}hasCache(e){return An(e)!==1}}function V2(t,e,r,i){let s=e,n=t.ZERO,o=t.ZERO;for(;r>Zr||i>Zr;)r&Or&&(n=n.add(s)),i&Or&&(o=o.add(s)),s=s.double(),r>>=Or,i>>=Or;return{p1:n,p2:o}}function K2(t,e,r,i){j2(r,t),q2(i,e);const s=r.length,n=i.length;if(s!==n)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Kh(BigInt(s));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const u=Fi(c),l=new Array(Number(u)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let p=h;p>=0;p-=c){l.fill(o);for(let y=0;y<n;y++){const g=i[y],b=Number(g>>BigInt(p)&u);l[b]=l[b].add(r[y])}let d=o;for(let y=l.length-1,g=o;y>0;y--)g=g.add(l[y]),d=d.add(g);if(f=f.add(d),p!==0)for(let y=0;y<c;y++)f=f.double()}return f}function ru(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return F2(e),e}else return yr(t,{isLE:r})}function H2(t,e,r={},i){if(i===void 0&&(i=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>Zr))throw new Error(`CURVE.${a} must be positive bigint`)}const s=ru(e.p,r.Fp,i),n=ru(e.n,r.Fn,i),o=["Gx","Gy","a","b"];for(const a of o)if(!s.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:s,Fn:n}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),$h("HashToScalar-");const ci=BigInt(0),Lr=BigInt(1),es=BigInt(2);function W2(t){return qs(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function G2(t){const e=W2(t),{P:r,type:i,adjustScalarBytes:s,powPminus2:n,randomBytes:o}=e,a=i==="x25519";if(!a&&i!=="x448")throw new Error("invalid type");const c=o||Br,u=a?255:448,l=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),p=a?es**BigInt(254):es**BigInt(447),d=a?BigInt(8)*es**BigInt(251)-Lr:BigInt(4)*es**BigInt(445)-Lr,y=p+d+Lr,g=R=>Xe(R,r),b=m(h);function m(R){return Qo(g(R),l)}function w(R){const _=Ne("u coordinate",R,l);return a&&(_[31]&=127),g(xs(_))}function I(R){return xs(s(Ne("scalar",R,l)))}function O(R,_){const S=N(w(_),I(R));if(S===ci)throw new Error("invalid private or public key received");return m(S)}function T(R){return O(R,b)}function B(R,_,S){const E=g(R*(_-S));return _=g(_-E),S=g(S+E),{x_2:_,x_3:S}}function N(R,_){ho("u",R,ci,r),ho("scalar",_,p,y);const S=_,E=R;let v=Lr,D=ci,P=R,x=Lr,A=ci;for(let k=BigInt(u-1);k>=ci;k--){const K=S>>k&Lr;A^=K,{x_2:v,x_3:P}=B(A,v,P),{x_2:D,x_3:x}=B(A,D,x),A=K;const V=v+D,z=g(V*V),H=v-D,Y=g(H*H),X=z-Y,W=P+x,se=P-x,ye=g(se*V),Ge=g(W*H),wt=ye+Ge,At=ye-Ge;P=g(wt*wt),x=g(E*g(At*At)),v=g(z*Y),D=g(X*(z+g(f*X)))}({x_2:v,x_3:P}=B(A,v,P)),{x_2:D,x_3:x}=B(A,D,x);const U=n(D);return g(v*U)}const $={secretKey:l,publicKey:l,seed:l},M=(R=c(l))=>(yt(R,$.seed),R);function q(R){const _=M(R);return{secretKey:_,publicKey:T(_)}}return{keygen:q,getSharedSecret:(R,_)=>O(R,_),getPublicKey:R=>T(R),scalarMult:O,scalarMultBase:T,utils:{randomSecretKey:M,randomPrivateKey:M},GuBytes:b.slice(),lengths:$}}const Y2=BigInt(1),iu=BigInt(2),Z2=BigInt(3),J2=BigInt(5);BigInt(8);const of=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),X2={p:of,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function Q2(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),s=BigInt(80),n=of,o=t*t%n*t%n,a=ft(o,iu,n)*o%n,c=ft(a,Y2,n)*t%n,u=ft(c,J2,n)*c%n,l=ft(u,e,n)*u%n,h=ft(l,r,n)*l%n,f=ft(h,i,n)*h%n,p=ft(f,s,n)*f%n,d=ft(p,s,n)*f%n,y=ft(d,e,n)*u%n;return{pow_p_5_8:ft(y,iu,n)*t%n,b2:o}}function eE(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const tE=yr(X2.p,{isLE:!0}),fo=(()=>{const t=tE.ORDER;return G2({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:i}=Q2(e);return Xe(ft(r,Z2,t)*i,t)},adjustScalarBytes:eE})})(),su=(t,e)=>(t+(t>=0?e:-e)/af)/e;function rE(t,e,r){const[[i,s],[n,o]]=e,a=su(o*t,r),c=su(-s*t,r);let u=t-a*i-c*n,l=-a*s-c*o;const h=u<jt,f=l<jt;h&&(u=-u),f&&(l=-l);const p=Fi(Math.ceil(Kh(r)/2))+Wr;if(u<jt||u>=p||l<jt||l>=p)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:u,k2neg:f,k2:l}}function po(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Pn(t,e){const r={};for(let i of Object.keys(e))r[i]=t[i]===void 0?e[i]:t[i];return Es(r.lowS,"lowS"),Es(r.prehash,"prehash"),r.format!==void 0&&po(r.format),r}class iE extends Error{constructor(e=""){super(e)}}const Lt={Err:iE,_tlv:{encode:(t,e)=>{const{Err:r}=Lt;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,s=Qi(i);if(s.length/2&128)throw new r("tlv.encode: long form length too big");const n=i>127?Qi(s.length/2|128):"";return Qi(t)+n+s+e},decode(t,e){const{Err:r}=Lt;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const s=e[i++],n=!!(s&128);let o=0;if(!n)o=s;else{const c=s&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const u=e.subarray(i,i+c);if(u.length!==c)throw new r("tlv.decode: length bytes not complete");if(u[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const l of u)o=o<<8|l;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=Lt;if(t<jt)throw new e("integer: negative integers are not allowed");let r=Qi(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=Lt;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return js(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=Lt,s=Ne("signature",t),{v:n,l:o}=i.decode(48,s);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,n),{v:u,l}=i.decode(2,c);if(l.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(u)}},hexFromSig(t){const{_tlv:e,_int:r}=Lt,i=e.encode(2,r.encode(t.r)),s=e.encode(2,r.encode(t.s)),n=i+s;return e.encode(48,n)}},jt=BigInt(0),Wr=BigInt(1),af=BigInt(2),ts=BigInt(3),sE=BigInt(4);function zr(t,e){const{BYTES:r}=t;let i;if(typeof e=="bigint")i=e;else{let s=Ne("private key",e);try{i=t.fromBytes(s)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function nE(t,e={}){const r=H2("weierstrass",t,e),{Fp:i,Fn:s}=r;let n=r.CURVE;const{h:o,n:a}=n;qs(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!i.is0(n.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const u=uf(i,s);function l(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(R,_,S){const{x:E,y:v}=_.toAffine(),D=i.toBytes(E);if(Es(S,"isCompressed"),S){l();const P=!i.isOdd(v);return nr(cf(P),D)}else return nr(Uint8Array.of(4),D,i.toBytes(v))}function f(R){Dr(R,void 0,"Point");const{publicKey:_,publicKeyUncompressed:S}=u,E=R.length,v=R[0],D=R.subarray(1);if(E===_&&(v===2||v===3)){const P=i.fromBytes(D);if(!i.isValid(P))throw new Error("bad point: is not on curve, wrong x");const x=y(P);let A;try{A=i.sqrt(x)}catch(k){const K=k instanceof Error?": "+k.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}l();const U=i.isOdd(A);return(v&1)===1!==U&&(A=i.neg(A)),{x:P,y:A}}else if(E===S&&v===4){const P=i.BYTES,x=i.fromBytes(D.subarray(0,P)),A=i.fromBytes(D.subarray(P,P*2));if(!g(x,A))throw new Error("bad point: is not on curve");return{x,y:A}}else throw new Error(`bad point: got length ${E}, expected compressed=${_} or uncompressed=${S}`)}const p=e.toBytes||h,d=e.fromBytes||f;function y(R){const _=i.sqr(R),S=i.mul(_,R);return i.add(i.add(S,i.mul(R,n.a)),n.b)}function g(R,_){const S=i.sqr(_),E=y(R);return i.eql(S,E)}if(!g(n.Gx,n.Gy))throw new Error("bad curve params: generator point");const b=i.mul(i.pow(n.a,ts),sE),m=i.mul(i.sqr(n.b),BigInt(27));if(i.is0(i.add(b,m)))throw new Error("bad curve params: a or b");function w(R,_,S=!1){if(!i.isValid(_)||S&&i.is0(_))throw new Error(`bad point coordinate ${R}`);return _}function I(R){if(!(R instanceof $))throw new Error("ProjectivePoint expected")}function O(R){if(!c||!c.basises)throw new Error("no endo");return rE(R,c.basises,s.ORDER)}const T=Jc((R,_)=>{const{X:S,Y:E,Z:v}=R;if(i.eql(v,i.ONE))return{x:S,y:E};const D=R.is0();_==null&&(_=D?i.ONE:i.inv(v));const P=i.mul(S,_),x=i.mul(E,_),A=i.mul(v,_);if(D)return{x:i.ZERO,y:i.ZERO};if(!i.eql(A,i.ONE))throw new Error("invZ was invalid");return{x:P,y:x}}),B=Jc(R=>{if(R.is0()){if(e.allowInfinityPoint&&!i.is0(R.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:S}=R.toAffine();if(!i.isValid(_)||!i.isValid(S))throw new Error("bad point: x or y not field elements");if(!g(_,S))throw new Error("bad point: equation left != right");if(!R.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function N(R,_,S,E,v){return S=new $(i.mul(S.X,R),S.Y,S.Z),_=_s(E,_),S=_s(v,S),_.add(S)}class ${constructor(_,S,E){this.X=w("x",_),this.Y=w("y",S,!0),this.Z=w("z",E),Object.freeze(this)}static CURVE(){return n}static fromAffine(_){const{x:S,y:E}=_||{};if(!_||!i.isValid(S)||!i.isValid(E))throw new Error("invalid affine point");if(_ instanceof $)throw new Error("projective point not allowed");return i.is0(S)&&i.is0(E)?$.ZERO:new $(S,E,i.ONE)}static fromBytes(_){const S=$.fromAffine(d(Dr(_,void 0,"point")));return S.assertValidity(),S}static fromHex(_){return $.fromBytes(Ne("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,S=!0){return q.createCache(this,_),S||this.multiply(ts),this}assertValidity(){B(this)}hasEvenY(){const{y:_}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(_)}equals(_){I(_);const{X:S,Y:E,Z:v}=this,{X:D,Y:P,Z:x}=_,A=i.eql(i.mul(S,x),i.mul(D,v)),U=i.eql(i.mul(E,x),i.mul(P,v));return A&&U}negate(){return new $(this.X,i.neg(this.Y),this.Z)}double(){const{a:_,b:S}=n,E=i.mul(S,ts),{X:v,Y:D,Z:P}=this;let x=i.ZERO,A=i.ZERO,U=i.ZERO,k=i.mul(v,v),K=i.mul(D,D),V=i.mul(P,P),z=i.mul(v,D);return z=i.add(z,z),U=i.mul(v,P),U=i.add(U,U),x=i.mul(_,U),A=i.mul(E,V),A=i.add(x,A),x=i.sub(K,A),A=i.add(K,A),A=i.mul(x,A),x=i.mul(z,x),U=i.mul(E,U),V=i.mul(_,V),z=i.sub(k,V),z=i.mul(_,z),z=i.add(z,U),U=i.add(k,k),k=i.add(U,k),k=i.add(k,V),k=i.mul(k,z),A=i.add(A,k),V=i.mul(D,P),V=i.add(V,V),k=i.mul(V,z),x=i.sub(x,k),U=i.mul(V,K),U=i.add(U,U),U=i.add(U,U),new $(x,A,U)}add(_){I(_);const{X:S,Y:E,Z:v}=this,{X:D,Y:P,Z:x}=_;let A=i.ZERO,U=i.ZERO,k=i.ZERO;const K=n.a,V=i.mul(n.b,ts);let z=i.mul(S,D),H=i.mul(E,P),Y=i.mul(v,x),X=i.add(S,E),W=i.add(D,P);X=i.mul(X,W),W=i.add(z,H),X=i.sub(X,W),W=i.add(S,v);let se=i.add(D,x);return W=i.mul(W,se),se=i.add(z,Y),W=i.sub(W,se),se=i.add(E,v),A=i.add(P,x),se=i.mul(se,A),A=i.add(H,Y),se=i.sub(se,A),k=i.mul(K,W),A=i.mul(V,Y),k=i.add(A,k),A=i.sub(H,k),k=i.add(H,k),U=i.mul(A,k),H=i.add(z,z),H=i.add(H,z),Y=i.mul(K,Y),W=i.mul(V,W),H=i.add(H,Y),Y=i.sub(z,Y),Y=i.mul(K,Y),W=i.add(W,Y),z=i.mul(H,W),U=i.add(U,z),z=i.mul(se,W),A=i.mul(X,A),A=i.sub(A,z),z=i.mul(X,H),k=i.mul(se,k),k=i.add(k,z),new $(A,U,k)}subtract(_){return this.add(_.negate())}is0(){return this.equals($.ZERO)}multiply(_){const{endo:S}=e;if(!s.isValidNot0(_))throw new Error("invalid scalar: out of range");let E,v;const D=P=>q.cached(this,P,x=>Dn($,x));if(S){const{k1neg:P,k1:x,k2neg:A,k2:U}=O(_),{p:k,f:K}=D(x),{p:V,f:z}=D(U);v=K.add(z),E=N(S.beta,k,V,P,A)}else{const{p:P,f:x}=D(_);E=P,v=x}return Dn($,[E,v])[0]}multiplyUnsafe(_){const{endo:S}=e,E=this;if(!s.isValid(_))throw new Error("invalid scalar: out of range");if(_===jt||E.is0())return $.ZERO;if(_===Wr)return E;if(q.hasCache(this))return this.multiply(_);if(S){const{k1neg:v,k1:D,k2neg:P,k2:x}=O(_),{p1:A,p2:U}=V2($,E,D,x);return N(S.beta,A,U,v,P)}else return q.unsafe(E,_)}multiplyAndAddUnsafe(_,S,E){const v=this.multiplyUnsafe(S).add(_.multiplyUnsafe(E));return v.is0()?void 0:v}toAffine(_){return T(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return o===Wr?!0:_?_($,this):q.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return o===Wr?this:_?_($,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(_=!0){return Es(_,"isCompressed"),this.assertValidity(),p($,this,_)}toHex(_=!0){return Hr(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Dn($,_)}static msm(_,S){return K2($,s,_,S)}static fromPrivateKey(_){return $.BASE.multiply(zr(s,_))}}$.BASE=new $(n.Gx,n.Gy,i.ONE),$.ZERO=new $(i.ZERO,i.ONE,i.ZERO),$.Fp=i,$.Fn=s;const M=s.BITS,q=new z2($,e.endo?Math.ceil(M/2):M);return $.BASE.precompute(8),$}function cf(t){return Uint8Array.of(t?2:3)}function uf(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function oE(t,e={}){const{Fn:r}=t,i=e.randomBytes||Br,s=Object.assign(uf(t.Fp,r),{seed:rf(r.ORDER)});function n(f){try{return!!zr(r,f)}catch{return!1}}function o(f,p){const{publicKey:d,publicKeyUncompressed:y}=s;try{const g=f.length;return p===!0&&g!==d||p===!1&&g!==y?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=i(s.seed)){return M2(Dr(f,s.seed,"seed"),r.ORDER)}function c(f,p=!0){return t.BASE.multiply(zr(r,f)).toBytes(p)}function u(f){const p=a(f);return{secretKey:p,publicKey:c(p)}}function l(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:p,publicKey:d,publicKeyUncompressed:y}=s;if(r.allowedLengths||p===d)return;const g=Ne("key",f).length;return g===d||g===y}function h(f,p,d=!0){if(l(f)===!0)throw new Error("first arg must be private key");if(l(p)===!1)throw new Error("second arg must be public key");const y=zr(r,f);return t.fromHex(p).multiply(y).toBytes(d)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:u,Point:t,utils:{isValidSecretKey:n,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:n,randomPrivateKey:a,normPrivateKeyToScalar:f=>zr(r,f),precompute(f=8,p=t.BASE){return p.precompute(f,!1)}},lengths:s})}function aE(t,e,r={}){Us(e),qs(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=r.randomBytes||Br,s=r.hmac||((S,...E)=>Ls(e,S,nr(...E))),{Fp:n,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:p}=oE(t,r),d={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},y="compact";function g(S){const E=a>>Wr;return S>E}function b(S,E){if(!o.isValidNot0(E))throw new Error(`invalid signature ${S}: out of range 1..Point.Fn.ORDER`);return E}function m(S,E){po(E);const v=p.signature,D=E==="compact"?v:E==="recovered"?v+1:void 0;return Dr(S,D,`${E} signature`)}class w{constructor(E,v,D){this.r=b("r",E),this.s=b("s",v),D!=null&&(this.recovery=D),Object.freeze(this)}static fromBytes(E,v=y){m(E,v);let D;if(v==="der"){const{r:U,s:k}=Lt.toSig(Dr(E));return new w(U,k)}v==="recovered"&&(D=E[0],v="compact",E=E.subarray(1));const P=o.BYTES,x=E.subarray(0,P),A=E.subarray(P,P*2);return new w(o.fromBytes(x),o.fromBytes(A),D)}static fromHex(E,v){return this.fromBytes(ms(E),v)}addRecoveryBit(E){return new w(this.r,this.s,E)}recoverPublicKey(E){const v=n.ORDER,{r:D,s:P,recovery:x}=this;if(x==null||![0,1,2,3].includes(x))throw new Error("recovery id invalid");if(a*af<v&&x>1)throw new Error("recovery id is ambiguous for h>1 curve");const A=x===2||x===3?D+a:D;if(!n.isValid(A))throw new Error("recovery id 2 or 3 invalid");const U=n.toBytes(A),k=t.fromBytes(nr(cf((x&1)===0),U)),K=o.inv(A),V=O(Ne("msgHash",E)),z=o.create(-V*K),H=o.create(P*K),Y=t.BASE.multiplyUnsafe(z).add(k.multiplyUnsafe(H));if(Y.is0())throw new Error("point at infinify");return Y.assertValidity(),Y}hasHighS(){return g(this.s)}toBytes(E=y){if(po(E),E==="der")return ms(Lt.hexFromSig(this));const v=o.toBytes(this.r),D=o.toBytes(this.s);if(E==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return nr(Uint8Array.of(this.recovery),v,D)}return nr(v,D)}toHex(E){return Hr(this.toBytes(E))}assertValidity(){}static fromCompact(E){return w.fromBytes(Ne("sig",E),"compact")}static fromDER(E){return w.fromBytes(Ne("sig",E),"der")}normalizeS(){return this.hasHighS()?new w(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Hr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Hr(this.toBytes("compact"))}}const I=r.bits2int||function(S){if(S.length>8192)throw new Error("input is too large");const E=js(S),v=S.length*8-c;return v>0?E>>BigInt(v):E},O=r.bits2int_modN||function(S){return o.create(I(S))},T=Fi(c);function B(S){return ho("num < 2^"+c,S,jt,T),o.toBytes(S)}function N(S,E){return Dr(S,void 0,"message"),E?Dr(e(S),void 0,"prehashed message"):S}function $(S,E,v){if(["recovered","canonical"].some(H=>H in v))throw new Error("sign() legacy options not supported");const{lowS:D,prehash:P,extraEntropy:x}=Pn(v,d);S=N(S,P);const A=O(S),U=zr(o,E),k=[B(U),B(A)];if(x!=null&&x!==!1){const H=x===!0?i(p.secretKey):x;k.push(Ne("extraEntropy",H))}const K=nr(...k),V=A;function z(H){const Y=I(H);if(!o.isValidNot0(Y))return;const X=o.inv(Y),W=t.BASE.multiply(Y).toAffine(),se=o.create(W.x);if(se===jt)return;const ye=o.create(X*o.create(V+se*U));if(ye===jt)return;let Ge=(W.x===se?0:2)|Number(W.y&Wr),wt=ye;return D&&g(ye)&&(wt=o.neg(ye),Ge^=1),new w(se,wt,Ge)}return{seed:K,k2sig:z}}function M(S,E,v={}){S=Ne("message",S);const{seed:D,k2sig:P}=$(S,E,v);return T2(e.outputLen,o.BYTES,s)(D,P)}function q(S){let E;const v=typeof S=="string"||Cs(S),D=!v&&S!==null&&typeof S=="object"&&typeof S.r=="bigint"&&typeof S.s=="bigint";if(!v&&!D)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(D)E=new w(S.r,S.s);else if(v){try{E=w.fromBytes(Ne("sig",S),"der")}catch(P){if(!(P instanceof Lt.Err))throw P}if(!E)try{E=w.fromBytes(Ne("sig",S),"compact")}catch{return!1}}return E||!1}function R(S,E,v,D={}){const{lowS:P,prehash:x,format:A}=Pn(D,d);if(v=Ne("publicKey",v),E=N(Ne("message",E),x),"strict"in D)throw new Error("options.strict was renamed to lowS");const U=A===void 0?q(S):w.fromBytes(Ne("sig",S),A);if(U===!1)return!1;try{const k=t.fromBytes(v);if(P&&U.hasHighS())return!1;const{r:K,s:V}=U,z=O(E),H=o.inv(V),Y=o.create(z*H),X=o.create(K*H),W=t.BASE.multiplyUnsafe(Y).add(k.multiplyUnsafe(X));return W.is0()?!1:o.create(W.x)===K}catch{return!1}}function _(S,E,v={}){const{prehash:D}=Pn(v,d);return E=N(E,D),w.fromBytes(S,"recovered").recoverPublicKey(E).toBytes()}return Object.freeze({keygen:u,getPublicKey:l,getSharedSecret:h,utils:f,lengths:p,Point:t,sign:M,verify:R,recoverPublicKey:_,Signature:w,hash:e})}function cE(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},r=t.Fp;let i=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const s=yr(e.n,{BITS:t.nBitLength,allowedLengths:i,modFromBytes:t.wrapPrivateKey}),n={Fp:r,Fn:s,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:n}}function uE(t){const{CURVE:e,curveOpts:r}=cE(t),i={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:i}}function lE(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,ef(r.Fn.ORDER,r.Fn.BITS))})}function hE(t){const{CURVE:e,curveOpts:r,hash:i,ecdsaOpts:s}=uE(t),n=nE(e,r),o=aE(n,i,s);return lE(t,o)}function go(t,e){const r=i=>hE({...t,hash:i});return{...r(e),create:r}}const lf={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},hf={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},ff={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},fE=yr(lf.p),dE=yr(hf.p),pE=yr(ff.p),gE=go({...lf,Fp:fE,lowS:!1},ks);go({...hf,Fp:dE,lowS:!1},vv),go({...ff,Fp:pE,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},mv);const yE=gE,df="base10",Fe="base16",Ve="base64pad",or="base64url",Li="utf8",pf=0,zt=1,Mi=2,wE=0,nu=1,mi=12,ta=32;function bE(){const t=fo.utils.randomPrivateKey(),e=fo.getPublicKey(t);return{privateKey:He(t,Fe),publicKey:He(e,Fe)}}function yo(){const t=Br(ta);return He(t,Fe)}function mE(t,e){const r=fo.getSharedSecret(ot(t,Fe),ot(e,Fe)),i=A2(Ms,r,void 0,void 0,ta);return He(i,Fe)}function cs(t){const e=Ms(ot(t,Fe));return He(e,Fe)}function st(t){const e=Ms(ot(t,Li));return He(e,Fe)}function gf(t){return ot(`${t}`,df)}function Pr(t){return Number(He(t,df))}function yf(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function wf(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function vE(t){const e=gf(typeof t.type<"u"?t.type:pf);if(Pr(e)===zt&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?ot(t.senderPublicKey,Fe):void 0,i=typeof t.iv<"u"?ot(t.iv,Fe):Br(mi),s=ot(t.symKey,Fe),n=qh(s,i).encrypt(ot(t.message,Li)),o=bf({type:e,sealed:n,iv:i,senderPublicKey:r});return t.encoding===or?yf(o):o}function EE(t){const e=ot(t.symKey,Fe),{sealed:r,iv:i}=$i({encoded:t.encoded,encoding:t.encoding}),s=qh(e,i).decrypt(r);if(s===null)throw new Error("Failed to decrypt");return He(s,Li)}function xE(t,e){const r=gf(Mi),i=Br(mi),s=ot(t,Li),n=bf({type:r,sealed:s,iv:i});return e===or?yf(n):n}function _E(t,e){const{sealed:r}=$i({encoded:t,encoding:e});return He(r,Li)}function bf(t){if(Pr(t.type)===Mi)return He(bi([t.type,t.sealed]),Ve);if(Pr(t.type)===zt){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return He(bi([t.type,t.senderPublicKey,t.iv,t.sealed]),Ve)}return He(bi([t.type,t.iv,t.sealed]),Ve)}function $i(t){const e=(t.encoding||Ve)===or?wf(t.encoded):t.encoded,r=ot(e,Ve),i=r.slice(wE,nu),s=nu;if(Pr(i)===zt){const c=s+ta,u=c+mi,l=r.slice(s,c),h=r.slice(c,u),f=r.slice(u);return{type:i,sealed:f,iv:h,senderPublicKey:l}}if(Pr(i)===Mi){const c=r.slice(s),u=Br(mi);return{type:i,sealed:c,iv:u}}const n=s+mi,o=r.slice(s,n),a=r.slice(n);return{type:i,sealed:a,iv:o}}function IE(t,e){const r=$i({encoded:t,encoding:e?.encoding});return mf({type:Pr(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?He(r.senderPublicKey,Fe):void 0,receiverPublicKey:e?.receiverPublicKey})}function mf(t){const e=t?.type||pf;if(e===zt){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 ou(t){return t.type===zt&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function au(t){return t.type===Mi}function SE(t){const e=ie.from(t.x,"base64"),r=ie.from(t.y,"base64");return bi([new Uint8Array([4]),e,r])}function DE(t,e){const[r,i,s]=t.split("."),n=ie.from(wf(s),"base64");if(n.length!==64)throw new Error("Invalid signature length");const o=n.slice(0,32),a=n.slice(32,64),c=`${r}.${i}`,u=Ms(c),l=SE(e);if(!yE.verify(bi([o,a]),u,l))throw new Error("Invalid signature");return Qn(t).payload}const $E="irn";function Is(t){return t?.relay||{protocol:$E}}function Vr(t){const e=n1[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var OE=Object.defineProperty,AE=Object.defineProperties,PE=Object.getOwnPropertyDescriptors,cu=Object.getOwnPropertySymbols,TE=Object.prototype.hasOwnProperty,RE=Object.prototype.propertyIsEnumerable,uu=(t,e,r)=>e in t?OE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Tn=(t,e)=>{for(var r in e||(e={}))TE.call(e,r)&&uu(t,r,e[r]);if(cu)for(var r of cu(e))RE.call(e,r)&&uu(t,r,e[r]);return t},BE=(t,e)=>AE(t,PE(e));function CE(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(s=>{if(s.startsWith(i)){const n=s.replace(i,""),o=t[s];r[n]=o}}),r}function lu(t){if(!t.includes("wc:")){const u=Eh(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(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),s=t.substring(e+1,r).split("@"),n=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(n),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:UE(s[0]),version:parseInt(s[1],10),symKey:a.symKey,relay:CE(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function UE(t){return t.startsWith("//")?t.substring(2):t}function NE(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(s=>{const n=s,o=r+e+n;t[n]&&(i[o]=t[n])}),i}function hu(t){const e=new URLSearchParams,r=Tn(Tn(BE(Tn({},NE(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(r).sort(([i],[s])=>i.localeCompare(s)).forEach(([i,s])=>{s!==void 0&&e.append(i,String(s))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function rs(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var kE=Object.defineProperty,FE=Object.defineProperties,LE=Object.getOwnPropertyDescriptors,fu=Object.getOwnPropertySymbols,ME=Object.prototype.hasOwnProperty,jE=Object.prototype.propertyIsEnumerable,du=(t,e,r)=>e in t?kE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qE=(t,e)=>{for(var r in e||(e={}))ME.call(e,r)&&du(t,r,e[r]);if(fu)for(var r of fu(e))jE.call(e,r)&&du(t,r,e[r]);return t},zE=(t,e)=>FE(t,LE(e));function ei(t){const e=[];return t.forEach(r=>{const[i,s]=r.split(":");e.push(`${i}:${s}`)}),e}function vf(t){const e=[];return Object.values(t).forEach(r=>{e.push(...ei(r.accounts))}),[...new Set(e)]}function VE(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.methods)}),[...new Set(e)]}function KE(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.events)}),[...new Set(e)]}function HE(t,e){const r=[];return Object.values(t).forEach(i=>{ei(i.accounts).includes(e)&&r.push(...i.methods)}),r}function WE(t,e){const r=[];return Object.values(t).forEach(i=>{ei(i.accounts).includes(e)&&r.push(...i.events)}),r}function rD(t){var e;const{proposal:{requiredNamespaces:r,optionalNamespaces:i={}},supportedNamespaces:s}=t,n=Ss(r),o=Ss(i),a={};Object.keys(s).forEach(l=>{const h=s[l].chains,f=s[l].methods,p=s[l].events,d=s[l].accounts;h.forEach(y=>{if(!d.some(g=>g.includes(y)))throw new Error(`No accounts provided for chain ${y} in namespace ${l}`)}),a[l]={chains:h,methods:f,events:p,accounts:d}});const c=wo(r,a,"approve()");if(c)throw new Error(c.message);const u={};if(!Object.keys(r).length&&!Object.keys(i).length)return a;Object.keys(n).forEach(l=>{const h=s[l].chains.filter(y=>{var g,b;return(b=(g=n[l])==null?void 0:g.chains)==null?void 0:b.includes(y)}),f=s[l].methods.filter(y=>{var g,b;return(b=(g=n[l])==null?void 0:g.methods)==null?void 0:b.includes(y)}),p=s[l].events.filter(y=>{var g,b;return(b=(g=n[l])==null?void 0:g.events)==null?void 0:b.includes(y)}),d=h.map(y=>s[l].accounts.filter(g=>g.includes(`${y}:`))).flat();u[l]={chains:h,methods:f,events:p,accounts:d}}),Object.keys(o).forEach(l=>{var h,f,p,d,y,g;if(!s[l])return;const b=(f=(h=o[l])==null?void 0:h.chains)==null?void 0:f.filter(O=>s[l].chains.includes(O)),m=s[l].methods.filter(O=>{var T,B;return(B=(T=o[l])==null?void 0:T.methods)==null?void 0:B.includes(O)}),w=s[l].events.filter(O=>{var T,B;return(B=(T=o[l])==null?void 0:T.events)==null?void 0:B.includes(O)}),I=b?.map(O=>s[l].accounts.filter(T=>T.includes(`${O}:`))).flat();u[l]={chains:pt((p=u[l])==null?void 0:p.chains,b),methods:pt((d=u[l])==null?void 0:d.methods,m),events:pt((y=u[l])==null?void 0:y.events,w),accounts:pt((g=u[l])==null?void 0:g.accounts,I)}});for(const[l,h]of Object.entries(u))(h.accounts.length===0||((e=h?.chains)==null?void 0:e.length)===0)&&delete u[l];return u}function Ef(t){return t.includes(":")}function GE(t){return Ef(t)?t.split(":")[0]:t}function Ss(t){var e,r,i;const s={};if(!Oi(t))return s;for(const[n,o]of Object.entries(t)){const a=Ef(n)?[n]:o.chains,c=o.methods||[],u=o.events||[],l=GE(n);s[l]=zE(qE({},s[l]),{chains:pt(a,(e=s[l])==null?void 0:e.chains),methods:pt(c,(r=s[l])==null?void 0:r.methods),events:pt(u,(i=s[l])==null?void 0:i.events)})}return s}function YE(t){const e={};return t?.forEach(r=>{var i;const[s,n]=r.split(":");e[s]||(e[s]={accounts:[],chains:[],events:[],methods:[]}),e[s].accounts.push(r),(i=e[s].chains)==null||i.push(`${s}:${n}`)}),e}function pu(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=YE(e);for(const[i,s]of Object.entries(r))s.methods?s.methods=pt(s.methods,t):s.methods=t,s.events=["chainChanged","accountsChanged"];return r}function ZE(t,e){var r,i,s,n,o,a;const c=Ss(t),u=Ss(e),l={},h=Object.keys(c).concat(Object.keys(u));for(const f of h)l[f]={chains:pt((r=c[f])==null?void 0:r.chains,(i=u[f])==null?void 0:i.chains),methods:pt((s=c[f])==null?void 0:s.methods,(n=u[f])==null?void 0:n.methods),events:pt((o=c[f])==null?void 0:o.events,(a=u[f])==null?void 0:a.events)};return l}function Jr(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Oi(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function ge(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function ra(t,e){return typeof t=="number"&&!isNaN(t)}function JE(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),s=Object.keys(r);let n=!0;return Sr(s,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:u}=t.namespaces[o],l=ei(a),h=r[o];(!Sr(yh(o,h),l)||!Sr(h.methods,c)||!Sr(h.events,u))&&(n=!1)}),n):!1}function Ds(t){return ge(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function XE(t){if(ge(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Ds(r)}}return!1}function QE(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(ge(t,!1)){if(e(t))return!0;const r=Eh(t);return e(r)}}catch{}return!1}function ex(t){var e;return(e=t?.proposer)==null?void 0:e.publicKey}function tx(t){return t?.topic}function rx(t,e){let r=null;return ge(t?.publicKey,!1)||(r=L("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function gu(t){let e=!0;return Jr(t)?t.length&&(e=t.every(r=>ge(r,!1))):e=!1,e}function ix(t,e,r){let i=null;return Jr(e)&&e.length?e.forEach(s=>{i||Ds(s)||(i=he("UNSUPPORTED_CHAINS",`${r}, chain ${s} should be a string and conform to "namespace:chainId" format`))}):Ds(t)||(i=he("UNSUPPORTED_CHAINS",`${r}, 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"] }`)),i}function sx(t,e,r){let i=null;return Object.entries(t).forEach(([s,n])=>{if(i)return;const o=ix(s,yh(s,n),`${e} ${r}`);o&&(i=o)}),i}function nx(t,e){let r=null;return Jr(t)?t.forEach(i=>{r||XE(i)||(r=he("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=he("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function ox(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=nx(i?.accounts,`${e} namespace`);s&&(r=s)}),r}function ax(t,e){let r=null;return gu(t?.methods)?gu(t?.events)||(r=he("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=he("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function xf(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const s=ax(i,`${e}, namespace`);s&&(r=s)}),r}function cx(t,e,r){let i=null;if(t&&Oi(t)){const s=xf(t,e);s&&(i=s);const n=sx(t,e,r);n&&(i=n)}else i=L("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function Rn(t,e){let r=null;if(t&&Oi(t)){const i=xf(t,e);i&&(r=i);const s=ox(t,e);s&&(r=s)}else r=L("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function _f(t){return ge(t.protocol,!0)}function ux(t,e){let r=!1;return t?t&&Jr(t)&&t.length&&t.forEach(i=>{r=_f(i)}):r=!0,r}function lx(t){return typeof t=="number"}function qe(t){return typeof t<"u"&&typeof t!==null}function hx(t){return!(!t||typeof t!="object"||!t.code||!ra(t.code)||!t.message||!ge(t.message,!1))}function fx(t){return!(_e(t)||!ge(t.method,!1))}function dx(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!ra(t.id)||!ge(t.jsonrpc,!1))}function px(t){return!(_e(t)||!ge(t.name,!1))}function yu(t,e){return!(!Ds(e)||!vf(t).includes(e))}function gx(t,e,r){return ge(r,!1)?HE(t,e).includes(r):!1}function yx(t,e,r){return ge(r,!1)?WE(t,e).includes(r):!1}function wo(t,e,r){let i=null;const s=wx(t),n=bx(e),o=Object.keys(s),a=Object.keys(n),c=wu(Object.keys(t)),u=wu(Object.keys(e)),l=c.filter(h=>!u.includes(h));return l.length&&(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
      Required: ${l.toString()}
      Received: ${Object.keys(e).toString()}`)),Sr(o,a)||(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
      Required: ${o.toString()}
      Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const f=ei(e[h].accounts);f.includes(h)||(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
        Required: ${h}
        Approved: ${f.toString()}`))}),o.forEach(h=>{i||(Sr(s[h].methods,n[h].methods)?Sr(s[h].events,n[h].events)||(i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=L("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function wx(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(s=>{e[s]={methods:t[r].methods,events:t[r].events}})}),e}function wu(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function bx(t){const e={};return Object.keys(t).forEach(r=>{r.includes(":")?e[r]=t[r]:ei(t[r].accounts)?.forEach(s=>{e[s]={accounts:t[r].accounts.filter(n=>n.includes(`${s}:`)),methods:t[r].methods,events:t[r].events}})}),e}function mx(t,e){return ra(t)&&t<=e.max&&t>=e.min}function bu(){const t=Ni();return new Promise(e=>{switch(t){case Qe.browser:e(vx());break;case Qe.reactNative:e(Ex());break;case Qe.node:e(xx());break;default:e(!0)}})}function vx(){return Qr()&&navigator?.onLine}async function Ex(){return gr()&&typeof G<"u"&&G!=null&&G.NetInfo?(await(G==null?void 0:G.NetInfo.fetch()))?.isConnected:!0}function xx(){return!0}function _x(t){switch(Ni()){case Qe.browser:Ix(t);break;case Qe.reactNative:Sx(t);break}}function Ix(t){!gr()&&Qr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function Sx(t){gr()&&typeof G<"u"&&G!=null&&G.NetInfo&&G?.NetInfo.addEventListener(e=>t(e?.isConnected))}function Dx(){var t;return Qr()&&Vt.getDocument()?((t=Vt.getDocument())==null?void 0:t.visibilityState)==="visible":!0}const Bn={};class ui{static get(e){return Bn[e]}static set(e,r){Bn[e]=r}static delete(e){delete Bn[e]}}function $x(t){const e=Ci.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function Ox({publicKey:t,signature:e,payload:r}){var i;const s=bo(r.method),n=128|parseInt(((i=r.version)==null?void 0:i.toString())||"4"),o=Tx(r.address),a=r.era==="00"?new Uint8Array([0]):bo(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),u=new Uint8Array([c&255,c>>8&255]),l=BigInt(`0x${Px(r.tip)}`),h=Bx(l),f=new Uint8Array([0,...t,o,...e,...a,...u,...h,...s]),p=Rx(f.length+1);return new Uint8Array([...p,n,...f])}function Ax(t){const e=bo(t),r=u1.blake2b(e,void 0,32);return"0x"+ie.from(r).toString("hex")}function bo(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function Px(t){return t.startsWith("0x")?t.slice(2):t}function Tx(t){const e=Ci.decode(t)[0];return e===42?0:e===60?2:1}function Rx(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 Bx(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 Cx(t){const e=Uint8Array.from(ie.from(t.signature,"hex")),r=$x(t.transaction.address),i=Ox({publicKey:r,signature:e,payload:t.transaction}),s=ie.from(i).toString("hex");return Ax(s)}function If({logger:t,name:e}){const r=typeof t=="string"?ll({opts:{level:t,name:e}}).logger:t;return r.level=typeof t=="string"?t:t.level,r}const Ux="PARSE_ERROR",Nx="INVALID_REQUEST",kx="METHOD_NOT_FOUND",Fx="INVALID_PARAMS",Sf="INTERNAL_ERROR",ia="SERVER_ERROR",Lx=[-32700,-32600,-32601,-32602,-32603],vi={[Ux]:{code:-32700,message:"Parse error"},[Nx]:{code:-32600,message:"Invalid Request"},[kx]:{code:-32601,message:"Method not found"},[Fx]:{code:-32602,message:"Invalid params"},[Sf]:{code:-32603,message:"Internal error"},[ia]:{code:-32e3,message:"Server error"}},Df=ia;function Mx(t){return Lx.includes(t)}function mu(t){return Object.keys(vi).includes(t)?vi[t]:vi[Df]}function jx(t){const e=Object.values(vi).find(r=>r.code===t);return e||vi[Df]}function qx(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var Cn={},Ct={},vu;function zx(){if(vu)return Ct;vu=1,Object.defineProperty(Ct,"__esModule",{value:!0}),Ct.isBrowserCryptoAvailable=Ct.getSubtleCrypto=Ct.getBrowerCrypto=void 0;function t(){return(Ur===null||Ur===void 0?void 0:Ur.crypto)||(Ur===null||Ur===void 0?void 0:Ur.msCrypto)||{}}Ct.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}Ct.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return Ct.isBrowserCryptoAvailable=r,Ct}var Ut={},Eu;function Vx(){if(Eu)return Ut;Eu=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.isBrowser=Ut.isNode=Ut.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}Ut.isReactNative=t;function e(){return typeof at<"u"&&typeof at.versions<"u"&&typeof at.versions.node<"u"}Ut.isNode=e;function r(){return!t()&&!e()}return Ut.isBrowser=r,Ut}var xu;function Kx(){return xu||(xu=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ai;e.__exportStar(zx(),t),e.__exportStar(Vx(),t)})(Cn)),Cn}var Hx=Kx();function _t(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function cr(t=6){return BigInt(_t(t))}function Mt(t,e,r){return{id:r||_t(),jsonrpc:"2.0",method:t,params:e}}function $s(t,e){return{id:t,jsonrpc:"2.0",result:e}}function sa(t,e,r){return{id:t,jsonrpc:"2.0",error:Wx(e)}}function Wx(t,e){return typeof t>"u"?mu(Sf):(typeof t=="string"&&(t=Object.assign(Object.assign({},mu(ia)),{message:t})),Mx(t.code)&&(t=jx(t.code)),t)}class Gx{}class Yx extends Gx{constructor(){super()}}class Zx extends Yx{constructor(e){super()}}const Jx="^wss?:";function Xx(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Qx(t,e){const r=Xx(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function _u(t){return Qx(t,Jx)}function e3(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function $f(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function na(t){return $f(t)&&"method"in t}function zs(t){return $f(t)&&(It(t)||nt(t))}function It(t){return"result"in t}function nt(t){return"error"in t}class t3 extends Zx{constructor(e){super(e),this.events=new Ot.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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Mt(e.method,e.params||[],e.id||cr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,s)=>{if(!this.connection.connected)try{await this.open()}catch(n){s(n)}this.events.on(`${e.id}`,n=>{nt(n)?s(n.error):i(n.result)});try{await this.connection.send(e,r)}catch(n){s(n)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),zs(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 r3=()=>typeof WebSocket<"u"?WebSocket:typeof G<"u"&&typeof G.WebSocket<"u"?G.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),i3=()=>typeof WebSocket<"u"||typeof G<"u"&&typeof G.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Iu=t=>t.split("?")[0],Su=10,s3=r3();let n3=class{constructor(e){if(this.url=e,this.events=new Ot.EventEmitter,this.registering=!1,!_u(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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(Ti(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!_u(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,s)=>{this.events.once("register_error",n=>{this.resetMaxListeners(),s(n)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return s(new Error("WebSocket connection is missing or invalid"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const s=Hx.isReactNative()?void 0:{rejectUnauthorized:!e3(e)},n=new s3(e,[],s);i3()?n.onerror=o=>{const a=o;i(this.emitError(a.error))}:n.on("error",o=>{i(this.emitError(o))}),n.onopen=()=>{this.onOpen(n),r(n)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),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 r=typeof e.data=="string"?Gr(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),s=i.message||i.toString(),n=sa(e,s);this.events.emit("payload",n)}parseError(e,r=this.url){return qx(e,Iu(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Su&&this.events.setMaxListeners(Su)}emitError(e){const r=this.parseError(new Error(e?.message||`WebSocket connection failed for host: ${Iu(this.url)}`));return this.events.emit("register_error",r),r}};var o3={};const Of="wc",Af=2,mo="core",$t=`${Of}@2:${mo}:`,a3={logger:"error"},c3={database:":memory:"},u3="crypto",Du="client_ed25519_seed",l3=F.ONE_DAY,h3="keychain",f3="0.3",d3="messages",p3="0.3",g3=F.SIX_HOURS,y3="publisher",Pf="irn",w3="error",Tf="wss://relay.walletconnect.org",b3="relayer",fe={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"},m3="_subscription",tt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},v3=.1,vo="2.23.7",ue={link_mode:"link_mode",relay:"relay"},us={inbound:"inbound",outbound:"outbound"},E3="0.3",x3="WALLETCONNECT_CLIENT_ID",$u="WALLETCONNECT_LINK_MODE_APPS",Ze={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},_3="subscription",I3="0.3",S3="pairing",D3="0.3",li={wc_pairingDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:F.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:F.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:F.ONE_DAY,prompt:!1,tag:0},res:{ttl:F.ONE_DAY,prompt:!1,tag:0}}},Ir={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},lt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},$3="history",O3="0.3",A3="expirer",it={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},P3="0.3",T3="verify-api",R3="https://verify.walletconnect.com",Rf="https://verify.walletconnect.org",Ei=Rf,B3=`${Ei}/v3`,C3=[R3,Rf],U3="echo",N3="https://echo.walletconnect.com",xt={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"},kt={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"},ht={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"},vr={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"},Er={authenticated_session_approve_started:"authenticated_session_approve_started",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve"},hi={no_internet_connection:"no_internet_connection",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},k3=.1,F3="event-client",L3=86400,M3="https://pulse.walletconnect.org/batch";function j3(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var s=0;s<t.length;s++){var n=t.charAt(s),o=n.charCodeAt(0);if(r[o]!==255)throw new TypeError(n+" is ambiguous");r[o]=s}var a=t.length,c=t.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function h(d){if(d instanceof Uint8Array||(ArrayBuffer.isView(d)?d=new Uint8Array(d.buffer,d.byteOffset,d.byteLength):Array.isArray(d)&&(d=Uint8Array.from(d))),!(d instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(d.length===0)return"";for(var y=0,g=0,b=0,m=d.length;b!==m&&d[b]===0;)b++,y++;for(var w=(m-b)*l+1>>>0,I=new Uint8Array(w);b!==m;){for(var O=d[b],T=0,B=w-1;(O!==0||T<g)&&B!==-1;B--,T++)O+=256*I[B]>>>0,I[B]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");g=T,b++}for(var N=w-g;N!==w&&I[N]===0;)N++;for(var $=c.repeat(y);N<w;++N)$+=t.charAt(I[N]);return $}function f(d){if(typeof d!="string")throw new TypeError("Expected String");if(d.length===0)return new Uint8Array;var y=0;if(d[y]!==" "){for(var g=0,b=0;d[y]===c;)g++,y++;for(var m=(d.length-y)*u+1>>>0,w=new Uint8Array(m);d[y];){var I=r[d.charCodeAt(y)];if(I===255)return;for(var O=0,T=m-1;(I!==0||O<b)&&T!==-1;T--,O++)I+=a*w[T]>>>0,w[T]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");b=O,y++}if(d[y]!==" "){for(var B=m-b;B!==m&&w[B]===0;)B++;for(var N=new Uint8Array(g+(m-B)),$=g;B!==m;)N[$++]=w[B++];return N}}}function p(d){var y=f(d);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:p}}var q3=j3,z3=q3;const Bf=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")},V3=t=>new TextEncoder().encode(t),K3=t=>new TextDecoder().decode(t);class H3{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class W3{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}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 Cf(this,e)}}class G3{constructor(e){this.decoders=e}or(e){return Cf(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Cf=(t,e)=>new G3({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class Y3{constructor(e,r,i,s){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=s,this.encoder=new H3(e,r,i),this.decoder=new W3(e,r,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Vs=({name:t,prefix:e,encode:r,decode:i})=>new Y3(t,e,r,i),ji=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:s}=z3(r,e);return Vs({prefix:t,name:e,encode:i,decode:n=>Bf(s(n))})},Z3=(t,e,r,i)=>{const s={};for(let l=0;l<e.length;++l)s[e[l]]=l;let n=t.length;for(;t[n-1]==="=";)--n;const o=new Uint8Array(n*r/8|0);let a=0,c=0,u=0;for(let l=0;l<n;++l){const h=s[t[l]];if(h===void 0)throw new SyntaxError(`Non-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[u++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},J3=(t,e,r)=>{const i=e[e.length-1]==="=",s=(1<<r)-1;let n="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,n+=e[s&a>>o];if(o&&(n+=e[s&a<<r-o]),i)for(;n.length*r&7;)n+="=";return n},Te=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Vs({prefix:e,name:t,encode(s){return J3(s,i,r)},decode(s){return Z3(s,i,r,t)}}),X3=Vs({prefix:"\0",name:"identity",encode:t=>K3(t),decode:t=>V3(t)});var Q3=Object.freeze({__proto__:null,identity:X3});const e_=Te({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var t_=Object.freeze({__proto__:null,base2:e_});const r_=Te({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var i_=Object.freeze({__proto__:null,base8:r_});const s_=ji({prefix:"9",name:"base10",alphabet:"0123456789"});var n_=Object.freeze({__proto__:null,base10:s_});const o_=Te({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),a_=Te({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var c_=Object.freeze({__proto__:null,base16:o_,base16upper:a_});const u_=Te({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),l_=Te({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),h_=Te({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),f_=Te({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),d_=Te({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),p_=Te({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),g_=Te({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),y_=Te({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),w_=Te({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var b_=Object.freeze({__proto__:null,base32:u_,base32upper:l_,base32pad:h_,base32padupper:f_,base32hex:d_,base32hexupper:p_,base32hexpad:g_,base32hexpadupper:y_,base32z:w_});const m_=ji({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),v_=ji({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var E_=Object.freeze({__proto__:null,base36:m_,base36upper:v_});const x_=ji({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),__=ji({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var I_=Object.freeze({__proto__:null,base58btc:x_,base58flickr:__});const S_=Te({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),D_=Te({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),$_=Te({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),O_=Te({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var A_=Object.freeze({__proto__:null,base64:S_,base64pad:D_,base64url:$_,base64urlpad:O_});const Uf=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),P_=Uf.reduce((t,e,r)=>(t[r]=e,t),[]),T_=Uf.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function R_(t){return t.reduce((e,r)=>(e+=P_[r],e),"")}function B_(t){const e=[];for(const r of t){const i=T_[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const C_=Vs({prefix:"🚀",name:"base256emoji",encode:R_,decode:B_});var U_=Object.freeze({__proto__:null,base256emoji:C_}),N_=Nf,Ou=128,k_=-128,F_=Math.pow(2,31);function Nf(t,e,r){e=e||[],r=r||0;for(var i=r;t>=F_;)e[r++]=t&255|Ou,t/=128;for(;t&k_;)e[r++]=t&255|Ou,t>>>=7;return e[r]=t|0,Nf.bytes=r-i+1,e}var L_=Eo,M_=128,Au=127;function Eo(t,i){var r=0,i=i||0,s=0,n=i,o,a=t.length;do{if(n>=a)throw Eo.bytes=0,new RangeError("Could not decode varint");o=t[n++],r+=s<28?(o&Au)<<s:(o&Au)*Math.pow(2,s),s+=7}while(o>=M_);return Eo.bytes=n-i,r}var j_=Math.pow(2,7),q_=Math.pow(2,14),z_=Math.pow(2,21),V_=Math.pow(2,28),K_=Math.pow(2,35),H_=Math.pow(2,42),W_=Math.pow(2,49),G_=Math.pow(2,56),Y_=Math.pow(2,63),Z_=function(t){return t<j_?1:t<q_?2:t<z_?3:t<V_?4:t<K_?5:t<H_?6:t<W_?7:t<G_?8:t<Y_?9:10},J_={encode:N_,decode:L_,encodingLength:Z_},kf=J_;const Pu=(t,e,r=0)=>(kf.encode(t,e,r),e),Tu=t=>kf.encodingLength(t),xo=(t,e)=>{const r=e.byteLength,i=Tu(t),s=i+Tu(r),n=new Uint8Array(s+r);return Pu(t,n,0),Pu(r,n,i),n.set(e,s),new X_(t,r,e,n)};class X_{constructor(e,r,i,s){this.code=e,this.size=r,this.digest=i,this.bytes=s}}const Ff=({name:t,code:e,encode:r})=>new Q_(t,e,r);class Q_{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?xo(this.code,r):r.then(i=>xo(this.code,i))}else throw Error("Unknown type, must be binary type")}}const Lf=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),e8=Ff({name:"sha2-256",code:18,encode:Lf("SHA-256")}),t8=Ff({name:"sha2-512",code:19,encode:Lf("SHA-512")});var r8=Object.freeze({__proto__:null,sha256:e8,sha512:t8});const Mf=0,i8="identity",jf=Bf,s8=t=>xo(Mf,jf(t)),n8={code:Mf,name:i8,encode:jf,digest:s8};var o8=Object.freeze({__proto__:null,identity:n8});new TextEncoder,new TextDecoder;const Ru={...Q3,...t_,...i_,...n_,...c_,...b_,...E_,...I_,...A_,...U_};({...r8,...o8});function qf(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function a8(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?qf(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function zf(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const Bu=zf("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Un=zf("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=a8(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),c8={utf8:Bu,"utf-8":Bu,hex:Ru.base16,latin1:Un,ascii:Un,binary:Un,...Ru};function u8(t,e="utf8"){const r=c8[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?qf(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var l8=Object.defineProperty,h8=(t,e,r)=>e in t?l8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,vt=(t,e,r)=>h8(t,typeof e!="symbol"?e+"":e,r);class f8{constructor(e,r){this.core=e,this.logger=r,vt(this,"keychain",new Map),vt(this,"name",h3),vt(this,"version",f3),vt(this,"initialized",!1),vt(this,"storagePrefix",$t),vt(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),vt(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),vt(this,"set",async(i,s)=>{this.isInitialized(),this.keychain.set(i,s),await this.persist()}),vt(this,"get",i=>{this.isInitialized();const s=this.keychain.get(i);if(typeof s>"u"){const{message:n}=L("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(n)}return s}),vt(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=et(r,this.name)}get context(){return We(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,io(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?so(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var d8=Object.defineProperty,p8=(t,e,r)=>e in t?d8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ve=(t,e,r)=>p8(t,typeof e!="symbol"?e+"":e,r);class g8{constructor(e,r,i){this.core=e,this.logger=r,ve(this,"name",u3),ve(this,"keychain"),ve(this,"randomSessionIdentifier",yo()),ve(this,"initialized",!1),ve(this,"clientId"),ve(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),ve(this,"hasKeys",s=>(this.isInitialized(),this.keychain.has(s))),ve(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const s=await this.getClientSeed(),n=ic(s),o=Ll(n.publicKey);return this.clientId=o,o}),ve(this,"generateKeyPair",()=>{this.isInitialized();const s=bE();return this.setPrivateKey(s.publicKey,s.privateKey)}),ve(this,"signJWT",async s=>{this.isInitialized();const n=await this.getClientSeed(),o=ic(n),a=this.randomSessionIdentifier;return await hw(a,s,l3,o)}),ve(this,"generateSharedKey",(s,n,o)=>{this.isInitialized();const a=this.getPrivateKey(s),c=mE(a,n);return this.setSymKey(c,o)}),ve(this,"setSymKey",async(s,n)=>{this.isInitialized();const o=n||cs(s);return await this.keychain.set(o,s),o}),ve(this,"deleteKeyPair",async s=>{this.isInitialized(),await this.keychain.del(s)}),ve(this,"deleteSymKey",async s=>{this.isInitialized(),await this.keychain.del(s)}),ve(this,"encode",async(s,n,o)=>{this.isInitialized();const a=mf(o),c=Ti(n);if(au(a))return xE(c,o?.encoding);if(ou(a)){const f=a.senderPublicKey,p=a.receiverPublicKey;s=await this.generateSharedKey(f,p)}const u=this.getSymKey(s),{type:l,senderPublicKey:h}=a;return vE({type:l,symKey:u,message:c,senderPublicKey:h,encoding:o?.encoding})}),ve(this,"decode",async(s,n,o)=>{this.isInitialized();const a=IE(n,o);if(au(a)){const c=_E(n,o?.encoding);return Gr(c)}if(ou(a)){const c=a.receiverPublicKey,u=a.senderPublicKey;s=await this.generateSharedKey(c,u)}try{const c=this.getSymKey(s),u=EE({symKey:c,encoded:n,encoding:o?.encoding});return Gr(u)}catch(c){this.logger.error(`Failed to decode message from topic: '${s}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),ve(this,"getPayloadType",(s,n=Ve)=>{const o=$i({encoded:s,encoding:n});return Pr(o.type)}),ve(this,"getPayloadSenderPublicKey",(s,n=Ve)=>{const o=$i({encoded:s,encoding:n});return o.senderPublicKey?He(o.senderPublicKey,Fe):void 0}),this.core=e,this.logger=et(r,this.name),this.keychain=i||new f8(this.core,this.logger)}get context(){return We(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Du)}catch{e=yo(),await this.keychain.set(Du,e)}return u8(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var y8=Object.defineProperty,w8=Object.defineProperties,b8=Object.getOwnPropertyDescriptors,Cu=Object.getOwnPropertySymbols,m8=Object.prototype.hasOwnProperty,v8=Object.prototype.propertyIsEnumerable,_o=(t,e,r)=>e in t?y8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,E8=(t,e)=>{for(var r in e||(e={}))m8.call(e,r)&&_o(t,r,e[r]);if(Cu)for(var r of Cu(e))v8.call(e,r)&&_o(t,r,e[r]);return t},x8=(t,e)=>w8(t,b8(e)),Ye=(t,e,r)=>_o(t,typeof e!="symbol"?e+"":e,r);class _8 extends ug{constructor(e,r){super(e,r),this.logger=e,this.core=r,Ye(this,"messages",new Map),Ye(this,"messagesWithoutClientAck",new Map),Ye(this,"name",d3),Ye(this,"version",p3),Ye(this,"initialized",!1),Ye(this,"storagePrefix",$t),Ye(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);const s=await this.getRelayerMessagesWithoutClientAck();typeof s<"u"&&(this.messagesWithoutClientAck=s),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),Ye(this,"set",async(i,s,n)=>{this.isInitialized();const o=st(s);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=s,this.messages.set(i,a),n===us.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,x8(E8({},c),{[o]:s}))}return await this.persist(),o}),Ye(this,"get",i=>{this.isInitialized();let s=this.messages.get(i);return typeof s>"u"&&(s={}),s}),Ye(this,"getWithoutAck",i=>{this.isInitialized();const s={};for(const n of i){const o=this.messagesWithoutClientAck.get(n)||{};s[n]=Object.values(o)}return s}),Ye(this,"has",(i,s)=>{this.isInitialized();const n=this.get(i),o=st(s);return typeof n[o]<"u"}),Ye(this,"ack",async(i,s)=>{this.isInitialized();const n=this.messagesWithoutClientAck.get(i);if(typeof n>"u")return;const o=st(s);delete n[o],Object.keys(n).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,n),await this.persist()}),Ye(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=et(e,this.name),this.core=r}get context(){return We(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,io(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,io(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?so(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?so(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var I8=Object.defineProperty,S8=Object.defineProperties,D8=Object.getOwnPropertyDescriptors,Uu=Object.getOwnPropertySymbols,$8=Object.prototype.hasOwnProperty,O8=Object.prototype.propertyIsEnumerable,Io=(t,e,r)=>e in t?I8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mr=(t,e)=>{for(var r in e||(e={}))$8.call(e,r)&&Io(t,r,e[r]);if(Uu)for(var r of Uu(e))O8.call(e,r)&&Io(t,r,e[r]);return t},Nu=(t,e)=>S8(t,D8(e)),rt=(t,e,r)=>Io(t,typeof e!="symbol"?e+"":e,r);class A8 extends lg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,rt(this,"events",new Ot.EventEmitter),rt(this,"name",y3),rt(this,"queue",new Map),rt(this,"publishTimeout",F.toMiliseconds(F.ONE_MINUTE)),rt(this,"initialPublishTimeout",F.toMiliseconds(F.ONE_SECOND*15)),rt(this,"needsTransportRestart",!1),rt(this,"publish",async(i,s,n)=>{var o,a,c,u,l;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:s,opts:n}});const h=n?.ttl||g3,f=n?.prompt||!1,p=n?.tag||0,d=n?.id||cr().toString(),y=Vr(Is().protocol),g={id:d,method:n?.publishMethod||y.publish,params:Mr({topic:i,message:s,ttl:h,prompt:f,tag:p,attestation:n?.attestation},n?.tvf)},b=`Failed to publish payload, please try again. id:${d} tag:${p}`;try{_e((o=g.params)==null?void 0:o.prompt)&&((a=g.params)==null||delete a.prompt),_e((c=g.params)==null?void 0:c.tag)&&((u=g.params)==null||delete u.tag);const m=new Promise(async w=>{const I=({id:T})=>{var B;((B=g.id)==null?void 0:B.toString())===T.toString()&&(this.removeRequestFromQueue(T),this.relayer.events.removeListener(fe.publish,I),w())};this.relayer.events.on(fe.publish,I);const O=Dt(new Promise((T,B)=>{this.rpcPublish(g,n).then(T).catch(N=>{this.logger.warn(N,N?.message),B(N)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${d} tag:${p}`);try{await O,this.events.removeListener(fe.publish,I)}catch(T){this.queue.set(d,{request:g,opts:n,attempt:1}),this.logger.warn(T,T?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:d,topic:i,message:s,opts:n}}),await Dt(m,this.publishTimeout,b)}catch(m){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(m),(l=n?.internal)!=null&&l.throwOnFailedPublish)throw m}finally{this.queue.delete(d)}}),rt(this,"publishCustom",async i=>{var s,n,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:u,opts:l={}}=i,{attestation:h,tvf:f,publishMethod:p,prompt:d,tag:y,ttl:g=F.FIVE_MINUTES}=l,b=l.id||cr().toString(),m=Vr(Is().protocol),w=p||m.publish,I={id:b,method:w,params:Mr(Nu(Mr({},u),{ttl:g,prompt:d,tag:y,attestation:h}),f)},O=`Failed to publish custom payload, please try again. id:${b} tag:${y}`;try{_e((s=I.params)==null?void 0:s.prompt)&&((n=I.params)==null||delete n.prompt),_e((o=I.params)==null?void 0:o.tag)&&((a=I.params)==null||delete a.tag);const T=new Promise(async B=>{const N=({id:M})=>{var q;((q=I.id)==null?void 0:q.toString())===M.toString()&&(this.removeRequestFromQueue(M),this.relayer.events.removeListener(fe.publish,N),B())};this.relayer.events.on(fe.publish,N);const $=Dt(new Promise((M,q)=>{this.rpcPublish(I,l).then(M).catch(R=>{this.logger.warn(R,R?.message),q(R)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${w} id:${b} tag:${y}`);try{await $,this.events.removeListener(fe.publish,N)}catch(M){this.queue.set(b,{request:I,opts:l,attempt:1}),this.logger.warn(M,M?.message)}});this.logger.trace({type:"method",method:"publish",params:{id:b,payload:u,opts:l}}),await Dt(T,this.publishTimeout,O)}catch(T){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(T),(c=l?.internal)!=null&&c.throwOnFailedPublish)throw T}finally{this.queue.delete(b)}}),rt(this,"on",(i,s)=>{this.events.on(i,s)}),rt(this,"once",(i,s)=>{this.events.once(i,s)}),rt(this,"off",(i,s)=>{this.events.off(i,s)}),rt(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.relayer=e,this.logger=et(r,this.name),this.registerEventListeners()}get context(){return We(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(fe.publish,Mr(Mr({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const s=e.attempt+1;this.queue.set(r,Nu(Mr({},e),{attempt:s})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.tag}, attempt: ${s}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(Rr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(fe.connection_stalled);return}this.checkQueue()}),this.relayer.on(fe.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var P8=Object.defineProperty,T8=(t,e,r)=>e in t?P8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,jr=(t,e,r)=>T8(t,typeof e!="symbol"?e+"":e,r);class R8{constructor(){jr(this,"map",new Map),jr(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),jr(this,"get",e=>this.map.get(e)||[]),jr(this,"exists",(e,r)=>this.get(e).includes(r)),jr(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const s=i.filter(n=>n!==r);if(!s.length){this.map.delete(e);return}this.map.set(e,s)}),jr(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var B8=Object.defineProperty,C8=Object.defineProperties,U8=Object.getOwnPropertyDescriptors,ku=Object.getOwnPropertySymbols,N8=Object.prototype.hasOwnProperty,k8=Object.prototype.propertyIsEnumerable,So=(t,e,r)=>e in t?B8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fi=(t,e)=>{for(var r in e||(e={}))N8.call(e,r)&&So(t,r,e[r]);if(ku)for(var r of ku(e))k8.call(e,r)&&So(t,r,e[r]);return t},Nn=(t,e)=>C8(t,U8(e)),ae=(t,e,r)=>So(t,typeof e!="symbol"?e+"":e,r);class F8 extends dg{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ae(this,"subscriptions",new Map),ae(this,"topicMap",new R8),ae(this,"events",new Ot.EventEmitter),ae(this,"name",_3),ae(this,"version",I3),ae(this,"pending",new Map),ae(this,"cached",[]),ae(this,"initialized",!1),ae(this,"storagePrefix",$t),ae(this,"subscribeTimeout",F.toMiliseconds(F.ONE_MINUTE)),ae(this,"initialSubscribeTimeout",F.toMiliseconds(F.ONE_SECOND*15)),ae(this,"clientId"),ae(this,"batchSubscribeTopicsLimit",500),ae(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ae(this,"subscribe",async(i,s)=>{var n;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}});try{const o=Is(s),a={topic:i,relay:o,transportType:s?.transportType};(n=s?.internal)!=null&&n.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,o,s);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:s}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ae(this,"unsubscribe",async(i,s)=>{this.isInitialized(),typeof s?.id<"u"?await this.unsubscribeById(i,s.id,s):await this.unsubscribeByTopic(i,s)}),ae(this,"isSubscribed",i=>new Promise(s=>{s(this.topicMap.topics.includes(i))})),ae(this,"isKnownTopic",i=>new Promise(s=>{s(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(n=>n.topic===i))})),ae(this,"on",(i,s)=>{this.events.on(i,s)}),ae(this,"once",(i,s)=>{this.events.once(i,s)}),ae(this,"off",(i,s)=>{this.events.off(i,s)}),ae(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),ae(this,"start",async()=>{await this.onConnect()}),ae(this,"stop",async()=>{await this.onDisconnect()}),ae(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ae(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const i=[];this.pending.forEach(s=>{i.push(s)}),await this.batchSubscribe(i)}),ae(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(Rr.pulse,async()=>{await this.checkPending()}),this.events.on(Ze.created,async i=>{const s=Ze.created;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()}),this.events.on(Ze.deleted,async i=>{const s=Ze.deleted;this.logger.info(`Emitting ${s}`),this.logger.debug({type:"event",event:s,data:i}),await this.persist()})}),this.relayer=e,this.logger=et(r,this.name),this.clientId=""}get context(){return We(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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async s=>await this.unsubscribeById(e,s,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const s=Is(i);await this.restartToComplete({topic:e,id:r,relay:s}),await this.rpcUnsubscribe(e,r,s);const n=he("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,n),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(s){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(s),s}}async rpcSubscribe(e,r,i){var s,n;const o=await this.getSubscriptionId(e);if((s=i?.internal)!=null&&s.skipSubscribe)return o;(!i||i?.transportType===ue.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:Vr(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(n=i?.internal)==null?void 0:n.throwOnFailedPublish;try{if(i?.transportType===ue.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},F.toMiliseconds(F.ONE_SECOND)),o;const u=new Promise(async h=>{const f=p=>{p.topic===e&&(this.events.removeListener(Ze.created,f),h(p.id))};this.events.on(Ze.created,f);try{const p=await Dt(new Promise((d,y)=>{this.relayer.request(a).catch(g=>{this.logger.warn(g,g?.message),y(g)}).then(d)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(Ze.created,f),h(p)}catch{}}),l=await Dt(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(fe.connection_stalled),c)throw u}return null}async rpcBatchSubscribe(e){if(!e.length)return!0;const r=e[0].relay,i={method:Vr(r.protocol).batchSubscribe,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{return await Dt(new Promise((s,n)=>{this.relayer.request(i).then(s).catch(o=>{this.logger.warn(o),n(o)})}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again"),!0}catch{return this.relayer.events.emit(fe.connection_stalled),!1}}async rpcBatchFetchMessages(e){if(!e.length)return;const r=e[0].relay,i={method:Vr(r.protocol).batchFetchMessages,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let s;try{s=await await Dt(new Promise((n,o)=>{this.relayer.request(i).catch(a=>{this.logger.warn(a),o(a)}).then(n)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(fe.connection_stalled)}return s}rpcUnsubscribe(e,r,i){const s={method:Vr(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:s}),this.relayer.request(s)}onSubscribe(e,r){this.setSubscription(e,Nn(fi({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,fi({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),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,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,fi({},r)),this.topicMap.set(r.topic,e),this.events.emit(Ze.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(Ze.deleted,Nn(fi({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(Ze.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const s=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(s)}}this.events.emit(Ze.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){if(e.length){if(!await this.rpcBatchSubscribe(e)){this.logger.warn(`Batch subscribe failed for ${e.length} topics, adding to pending for retry`),e.forEach(r=>{this.pending.set(r.topic,r)});return}this.onBatchSubscribe(await Promise.all(e.map(async r=>Nn(fi({},r),{id:await this.getSubscriptionId(r.topic)}))))}}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await F1(F.toMiliseconds(F.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return st(e+await this.getClientId())}}var L8=Object.defineProperty,Fu=Object.getOwnPropertySymbols,M8=Object.prototype.hasOwnProperty,j8=Object.prototype.propertyIsEnumerable,Do=(t,e,r)=>e in t?L8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Lu=(t,e)=>{for(var r in e||(e={}))M8.call(e,r)&&Do(t,r,e[r]);if(Fu)for(var r of Fu(e))j8.call(e,r)&&Do(t,r,e[r]);return t},J=(t,e,r)=>Do(t,typeof e!="symbol"?e+"":e,r);class q8 extends hg{constructor(e){var r;super(e),J(this,"protocol","wc"),J(this,"version",2),J(this,"core"),J(this,"logger"),J(this,"events",new Ot.EventEmitter),J(this,"provider"),J(this,"messages"),J(this,"subscriber"),J(this,"publisher"),J(this,"name",b3),J(this,"transportExplicitlyClosed",!1),J(this,"initialized",!1),J(this,"connectionAttemptInProgress",!1),J(this,"relayUrl"),J(this,"projectId"),J(this,"packageName"),J(this,"bundleId"),J(this,"hasExperiencedNetworkDisruption",!1),J(this,"pingTimeout"),J(this,"heartBeatTimeout",F.toMiliseconds(F.THIRTY_SECONDS+F.FIVE_SECONDS)),J(this,"reconnectTimeout"),J(this,"connectPromise"),J(this,"reconnectInProgress",!1),J(this,"requestsInFlight",[]),J(this,"connectTimeout",F.toMiliseconds(F.ONE_SECOND*15)),J(this,"stalledRestartInProgress",!1),J(this,"stalledRestartTimeout"),J(this,"stalledRestartBackoff",0),J(this,"stalledRestartBaseInterval",F.toMiliseconds(F.ONE_SECOND*2)),J(this,"stalledRestartMaxInterval",F.toMiliseconds(F.THIRTY_SECONDS)),J(this,"request",async i=>{var s,n;this.logger.debug("Publishing Request Payload");const o=i.id||cr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(s=i.params)==null?void 0:s.topic},"relayer.request - publishing...");const a=`${o}:${((n=i.params)==null?void 0:n.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);return this.requestsInFlight=this.requestsInFlight.filter(u=>u!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),J(this,"resetPingTimeout",()=>{bs()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var i,s,n,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null?void 0:n.terminate)==null||o.call(n)}catch(a){this.logger.warn(a,a?.message)}},this.heartBeatTimeout))}),J(this,"onPayloadHandler",i=>{this.onProviderPayload(i),this.resetPingTimeout()}),J(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(fe.connect)}),J(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),J(this,"onProviderErrorHandler",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(fe.error,i),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(s=>this.logger.warn(s))}),J(this,"registerProviderListeners",()=>{this.provider.on(tt.payload,this.onPayloadHandler),this.provider.on(tt.connect,this.onConnectHandler),this.provider.on(tt.disconnect,this.onDisconnectHandler),this.provider.on(tt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=If({logger:(r=e.logger)!=null?r:w3,name:this.name}),this.messages=new _8(this.logger,e.core),this.subscriber=new F8(this,this.logger),this.publisher=new A8(this,this.logger),this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Tf,x1()?this.packageName=Oc():_1()&&(this.bundleId=Oc()),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 We(this.logger)}get connected(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:ue.relay},us.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,s,n;this.isInitialized(),(!(r!=null&&r.transportType)||r?.transportType==="relay")&&await this.toEstablishConnection();const o=typeof((i=r?.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(s=r?.internal)==null?void 0:s.throwOnFailedPublish;let a=((n=this.subscriber.topicMap.get(e))==null?void 0:n[0])||"",c;const u=l=>{l.topic===e&&(this.subscriber.off(Ze.created,u),c())};return await Promise.all([new Promise(l=>{c=l,this.subscriber.on(Ze.created,u)}),new Promise(async(l,h)=>{a=await this.subscriber.subscribe(e,Lu({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,l()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Dt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,clearTimeout(this.stalledRestartTimeout),this.stalledRestartInProgress=!1,this.stalledRestartBackoff=0,await this.resetTransport()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.resetTransport(),await this.transportOpen())}async resetTransport(){this.reconnectInProgress=!0,clearTimeout(this.reconnectTimeout),this.reconnectTimeout=void 0,await this.transportDisconnect(),await this.subscriber.stop(),this.reconnectInProgress=!1}async confirmOnlineStateOrThrow(){if(!await bu())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 r=e.sort((i,s)=>i.publishedAt-s.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(s){this.logger.warn(s,"Error while processing batch message event: "+s?.message)}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const s=be(F.FIVE_MINUTES),n={topic:i,expiry:s,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,n)}this.events.emit(fe.message,e),await this.recordMessageEvent(e,us.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,s)=>{const n=()=>{s(new Error("Connection interrupted while trying to connect"))};this.provider.once(tt.disconnect,n),await Dt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{s(o)}).finally(()=>{this.provider.off(tt.disconnect,n),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{s(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(tt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(tt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,i()})}catch(i){await this.subscriber.stop();const s=i;this.logger.warn({},s.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${r}`);break}await new Promise(i=>setTimeout(i,F.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,s,n;if(bs())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((n=(s=(i=this.provider)==null?void 0:i.connection)==null?void 0:s.socket)==null||n.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 t3(new n3(O1({sdkVersion:vo,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,r){const{topic:i,message:s}=e;await this.messages.set(i,s,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const s=this.messages.has(r,i);return s&&this.logger.warn(`Ignoring duplicate message: ${i}`),s}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),na(e)){if(!e.method.endsWith(m3))return;const r=e.params,{topic:i,message:s,publishedAt:n,attestation:o}=r.data,a={topic:i,message:s,publishedAt:n,transportType:ue.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Lu({type:"event",event:r.id},a)),this.events.emit(r.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else zs(e)&&this.events.emit(fe.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,us.inbound),this.events.emit(fe.message,e))}async acknowledgePayload(e){const r=$s(e.id,!0);await this.provider.connection.send(r)}unregisterProviderListeners(){this.provider.off(tt.payload,this.onPayloadHandler),this.provider.off(tt.connect,this.onConnectHandler),this.provider.off(tt.disconnect,this.onDisconnectHandler),this.provider.off(tt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await bu();_x(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i?.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(Rr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&Dx())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r?.message)}}),this.events.on(fe.connection_stalled,()=>{if(this.transportExplicitlyClosed||this.stalledRestartInProgress)return;this.stalledRestartInProgress=!0;const r=this.stalledRestartBackoff===0?0:Math.min(Math.pow(2,this.stalledRestartBackoff-1)*this.stalledRestartBaseInterval,this.stalledRestartMaxInterval);this.stalledRestartBackoff++,this.logger.warn(`Connection stalled, restarting transport${r?` in ${r}ms`:""}...`),this.stalledRestartTimeout=setTimeout(async()=>{try{if(this.transportExplicitlyClosed)return;await this.restartTransport()}catch(i){this.logger.error(i,i?.message)}finally{this.stalledRestartInProgress=!1}},r)})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(fe.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},F.toMiliseconds(v3)))))}isInitialized(){if(!this.initialized){const{message:e}=L("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 z8(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Mu(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function ju(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const V8="[object RegExp]",K8="[object String]",H8="[object Number]",W8="[object Boolean]",qu="[object Arguments]",G8="[object Symbol]",Y8="[object Date]",Z8="[object Map]",J8="[object Set]",X8="[object Array]",Q8="[object Function]",eI="[object ArrayBuffer]",kn="[object Object]",tI="[object Error]",rI="[object DataView]",iI="[object Uint8Array]",sI="[object Uint8ClampedArray]",nI="[object Uint16Array]",oI="[object Uint32Array]",aI="[object BigUint64Array]",cI="[object Int8Array]",uI="[object Int16Array]",lI="[object Int32Array]",hI="[object BigInt64Array]",fI="[object Float32Array]",dI="[object Float64Array]";function zu(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 pI(t,e,r){return yi(t,e,void 0,void 0,void 0,void 0,r)}function yi(t,e,r,i,s,n,o){const a=o(t,e,r,i,s,n);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return xi(t,e,n,o)}return xi(t,e,n,o)}function xi(t,e,r,i){if(Object.is(t,e))return!0;let s=ju(t),n=ju(e);if(s===qu&&(s=kn),n===qu&&(n=kn),s!==n)return!1;switch(s){case K8:return t.toString()===e.toString();case H8:{const c=t.valueOf(),u=e.valueOf();return z8(c,u)}case W8:case Y8:case G8:return Object.is(t.valueOf(),e.valueOf());case V8:return t.source===e.source&&t.flags===e.flags;case Q8:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(s){case Z8:{if(t.size!==e.size)return!1;for(const[c,u]of t.entries())if(!e.has(c)||!yi(u,e.get(c),c,t,e,r,i))return!1;return!0}case J8:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),u=Array.from(e.values());for(let l=0;l<c.length;l++){const h=c[l],f=u.findIndex(p=>yi(h,p,void 0,t,e,r,i));if(f===-1)return!1;u.splice(f,1)}return!0}case X8:case iI:case sI:case nI:case oI:case aI:case cI:case uI:case lI:case hI:case fI:case dI:{if(typeof ie<"u"&&ie.isBuffer(t)!==ie.isBuffer(e)||t.length!==e.length)return!1;for(let c=0;c<t.length;c++)if(!yi(t[c],e[c],c,t,e,r,i))return!1;return!0}case eI:return t.byteLength!==e.byteLength?!1:xi(new Uint8Array(t),new Uint8Array(e),r,i);case rI:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:xi(new Uint8Array(t),new Uint8Array(e),r,i);case tI:return t.name===e.name&&t.message===e.message;case kn:{if(!(xi(t.constructor,e.constructor,r,i)||zu(t)&&zu(e)))return!1;const c=[...Object.keys(t),...Mu(t)],u=[...Object.keys(e),...Mu(e)];if(c.length!==u.length)return!1;for(let l=0;l<c.length;l++){const h=c[l],f=t[h];if(!Object.hasOwn(e,h))return!1;const p=e[h];if(!yi(f,p,h,t,e,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function gI(){}function yI(t,e){return pI(t,e,gI)}var wI=Object.defineProperty,Vu=Object.getOwnPropertySymbols,bI=Object.prototype.hasOwnProperty,mI=Object.prototype.propertyIsEnumerable,$o=(t,e,r)=>e in t?wI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ku=(t,e)=>{for(var r in e||(e={}))bI.call(e,r)&&$o(t,r,e[r]);if(Vu)for(var r of Vu(e))mI.call(e,r)&&$o(t,r,e[r]);return t},Me=(t,e,r)=>$o(t,typeof e!="symbol"?e+"":e,r);class Cr extends fg{constructor(e,r,i,s=$t,n=void 0){super(e,r,i,s),this.core=e,this.logger=r,this.name=i,Me(this,"map",new Map),Me(this,"version",E3),Me(this,"cached",[]),Me(this,"initialized",!1),Me(this,"getKey"),Me(this,"storagePrefix",$t),Me(this,"recentlyDeleted",[]),Me(this,"recentlyDeletedLimit",200),Me(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!_e(o)?this.map.set(this.getKey(o),o):ex(o)?this.map.set(o.id,o):tx(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Me(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())}),Me(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Me(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>yI(a[c],o[c]))):this.values)),Me(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=Ku(Ku({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Me(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=et(r,this.name),this.storagePrefix=s,this.getKey=n}get context(){return We(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 r=this.map.get(e);if(!r){if(this.recentlyDeleted.includes(e)){const{message:s}=L("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(s),new Error(s)}const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}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:r}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vI=Object.defineProperty,EI=(t,e,r)=>e in t?vI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Q=(t,e,r)=>EI(t,typeof e!="symbol"?e+"":e,r);class xI{constructor(e,r){this.core=e,this.logger=r,Q(this,"name",S3),Q(this,"version",D3),Q(this,"events",new Qu),Q(this,"pairings"),Q(this,"initialized",!1),Q(this,"storagePrefix",$t),Q(this,"ignoredPayloadTypes",[zt]),Q(this,"registeredMethods",[]),Q(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),Q(this,"register",({methods:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),Q(this,"create",async i=>{this.isInitialized();const s=yo(),n=await this.core.crypto.setSymKey(s),o=be(F.FIVE_MINUTES),a={protocol:Pf},c={topic:n,expiry:o,relay:a,active:!1,methods:i?.methods},u=hu({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:s,relay:a,expiryTimestamp:o,methods:i?.methods});return this.events.emit(Ir.create,c),this.core.expirer.set(n,o),await this.pairings.set(n,c),await this.core.relayer.subscribe(n,{transportType:i?.transportType,internal:i?.internal}),{topic:n,uri:u}}),Q(this,"pair",async i=>{this.isInitialized();const s=this.core.eventClient.createEvent({properties:{topic:i?.uri,trace:[xt.pairing_started]}});this.isValidPair(i,s);const{topic:n,symKey:o,relay:a,expiryTimestamp:c,methods:u}=lu(i.uri);s.props.properties.topic=n,s.addTrace(xt.pairing_uri_validation_success),s.addTrace(xt.pairing_uri_not_expired);let l;if(this.pairings.keys.includes(n)){if(l=this.pairings.get(n),s.addTrace(xt.existing_pairing),l.active)throw s.setError(kt.active_pairing_already_exists),new Error(`Pairing already exists: ${n}. Please try again with a new connection URI.`);s.addTrace(xt.pairing_not_expired)}const h=c||be(F.FIVE_MINUTES),f={topic:n,relay:a,expiry:h,active:!1,methods:u};this.core.expirer.set(n,h),await this.pairings.set(n,f),s.addTrace(xt.store_new_pairing),i.activatePairing&&await this.activate({topic:n}),this.events.emit(Ir.create,f),s.addTrace(xt.emit_inactive_pairing),this.core.crypto.keychain.has(n)||await this.core.crypto.setSymKey(o,n),s.addTrace(xt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{s.setError(kt.no_internet_connection)}try{await this.core.relayer.subscribe(n,{relay:a})}catch(p){throw s.setError(kt.subscribe_pairing_topic_failure),p}return s.addTrace(xt.subscribe_pairing_topic_success),f}),Q(this,"activate",async({topic:i})=>{this.isInitialized();const s=be(F.FIVE_MINUTES);this.core.expirer.set(i,s),await this.pairings.update(i,{active:!0,expiry:s})}),Q(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:s}=i;if(this.pairings.keys.includes(s)){const n=await this.sendRequest(s,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=xr();this.events.once(ne("pairing_ping",n),({error:u})=>{u?c(u):a()}),await o()}}),Q(this,"updateExpiry",async({topic:i,expiry:s})=>{this.isInitialized(),await this.pairings.update(i,{expiry:s})}),Q(this,"updateMetadata",async({topic:i,metadata:s})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:s})}),Q(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),Q(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:s}=i;this.pairings.keys.includes(s)&&(await this.sendRequest(s,"wc_pairingDelete",he("USER_DISCONNECTED")),await this.deletePairing(s))}),Q(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:s,relay:n,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(s);return hu({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:c,relay:n,expiryTimestamp:o,methods:a})}),Q(this,"sendRequest",async(i,s,n)=>{const o=Mt(s,n),a=await this.core.crypto.encode(i,o),c=li[s].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),Q(this,"sendResult",async(i,s,n)=>{const o=$s(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=li[c].res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),Q(this,"sendError",async(i,s,n)=>{const o=sa(i,n),a=await this.core.crypto.encode(s,o),c=(await this.core.history.get(s,i)).request.method,u=li[c]?li[c].res:li.unregistered_method.res;await this.core.relayer.publish(s,a,u),await this.core.history.resolve(o)}),Q(this,"deletePairing",async(i,s)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,he("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),s?Promise.resolve():this.core.expirer.del(i)])}),Q(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(s=>er(s.expiry));await Promise.all(i.map(s=>this.deletePairing(s.topic)))}),Q(this,"onRelayEventRequest",async i=>{const{topic:s,payload:n}=i;switch(n.method){case"wc_pairingPing":return await this.onPairingPingRequest(s,n);case"wc_pairingDelete":return await this.onPairingDeleteRequest(s,n);default:return await this.onUnknownRpcMethodRequest(s,n)}}),Q(this,"onRelayEventResponse",async i=>{const{topic:s,payload:n}=i,o=(await this.core.history.get(s,n.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(s,n);default:return this.onUnknownRpcMethodResponse(o)}}),Q(this,"onPairingPingRequest",async(i,s)=>{const{id:n}=s;try{this.isValidPing({topic:i}),await this.sendResult(n,i,!0),this.events.emit(Ir.ping,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onPairingPingResponse",(i,s)=>{const{id:n}=s;setTimeout(()=>{It(s)?this.events.emit(ne("pairing_ping",n),{}):nt(s)&&this.events.emit(ne("pairing_ping",n),{error:s.error})},500)}),Q(this,"onPairingDeleteRequest",async(i,s)=>{const{id:n}=s;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Ir.delete,{id:n,topic:i})}catch(o){await this.sendError(n,i,o),this.logger.error(o)}}),Q(this,"onUnknownRpcMethodRequest",async(i,s)=>{const{id:n,method:o}=s;try{if(this.registeredMethods.includes(o))return;const a=he("WC_METHOD_UNSUPPORTED",o);await this.sendError(n,i,a),this.logger.error(a)}catch(a){await this.sendError(n,i,a),this.logger.error(a)}}),Q(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(he("WC_METHOD_UNSUPPORTED",i))}),Q(this,"isValidPair",(i,s)=>{var n;if(!qe(i)){const{message:a}=L("MISSING_OR_INVALID",`pair() params: ${i}`);throw s.setError(kt.malformed_pairing_uri),new Error(a)}if(!QE(i.uri)){const{message:a}=L("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw s.setError(kt.malformed_pairing_uri),new Error(a)}const o=lu(i?.uri);if(!((n=o?.relay)!=null&&n.protocol)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#relay-protocol");throw s.setError(kt.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=L("MISSING_OR_INVALID","pair() uri#symKey");throw s.setError(kt.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&F.toMiliseconds(o?.expiryTimestamp)<Date.now()){s.setError(kt.pairing_expired);const{message:a}=L("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),Q(this,"isValidPing",async i=>{if(!qe(i)){const{message:n}=L("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidDisconnect",async i=>{if(!qe(i)){const{message:n}=L("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:s}=i;await this.isValidPairingTopic(s)}),Q(this,"isValidPairingTopic",async i=>{if(!ge(i,!1)){const{message:s}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(s)}if(!this.pairings.keys.includes(i)){const{message:s}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(s)}if(er(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:s}=L("EXPIRED",`pairing topic: ${i}`);throw new Error(s)}}),this.core=e,this.logger=et(r,this.name),this.pairings=new Cr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return We(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(fe.message,async e=>{const{topic:r,message:i,transportType:s}=e;if(this.pairings.keys.includes(r)&&s!==ue.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const n=await this.core.crypto.decode(r,i);na(n)?(this.core.history.set(r,n),await this.onRelayEventRequest({topic:r,payload:n})):zs(n)&&(await this.core.history.resolve(n),await this.onRelayEventResponse({topic:r,payload:n}),this.core.history.delete(r,n.id)),await this.core.relayer.messages.ack(r,i)}catch(n){this.logger.error(n)}})}registerExpirerEvents(){this.core.expirer.on(it.expired,async e=>{const{topic:r}=vh(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Ir.expire,{topic:r}))})}}var _I=Object.defineProperty,II=(t,e,r)=>e in t?_I(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,De=(t,e,r)=>II(t,typeof e!="symbol"?e+"":e,r);class SI extends cg{constructor(e,r){super(e,r),this.core=e,this.logger=r,De(this,"records",new Map),De(this,"events",new Ot.EventEmitter),De(this,"name",$3),De(this,"version",O3),De(this,"cached",[]),De(this,"initialized",!1),De(this,"storagePrefix",$t),De(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),De(this,"set",(i,s,n)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:s,chainId:n}),this.records.has(s.id))return;const o={id:s.id,topic:i,request:{method:s.method,params:s.params||null},chainId:n,expiry:be(F.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(lt.created,o)}),De(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const s=await this.getRecord(i.id);typeof s.response>"u"&&(s.response=nt(i)?{error:i.error}:{result:i.result},this.records.set(s.id,s),this.persist(),this.events.emit(lt.updated,s))}),De(this,"get",async(i,s)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:s}),await this.getRecord(s))),De(this,"delete",(i,s)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:s}),this.values.forEach(n=>{if(n.topic===i){if(typeof s<"u"&&n.id!==s)return;this.records.delete(n.id),this.events.emit(lt.deleted,n)}}),this.persist()}),De(this,"exists",async(i,s)=>(this.isInitialized(),this.records.has(s)?(await this.getRecord(s)).topic===i:!1)),De(this,"on",(i,s)=>{this.events.on(i,s)}),De(this,"once",(i,s)=>{this.events.once(i,s)}),De(this,"off",(i,s)=>{this.events.off(i,s)}),De(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=et(r,this.name)}get context(){return We(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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Mt(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),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 r=this.records.get(e);if(!r){const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(lt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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(lt.created,e=>{const r=lt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(lt.updated,e=>{const r=lt.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(lt.deleted,e=>{const r=lt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(Rr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{F.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(lt.deleted,r,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var DI=Object.defineProperty,$I=(t,e,r)=>e in t?DI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ue=(t,e,r)=>$I(t,typeof e!="symbol"?e+"":e,r);class OI extends pg{constructor(e,r){super(e,r),this.core=e,this.logger=r,Ue(this,"expirations",new Map),Ue(this,"events",new Ot.EventEmitter),Ue(this,"name",A3),Ue(this,"version",P3),Ue(this,"cached",[]),Ue(this,"initialized",!1),Ue(this,"storagePrefix",$t),Ue(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Ue(this,"has",i=>{try{const s=this.formatTarget(i);return typeof this.getExpiration(s)<"u"}catch{return!1}}),Ue(this,"set",(i,s)=>{this.isInitialized();const n=this.formatTarget(i),o={target:n,expiry:s};this.expirations.set(n,o),this.checkExpiry(n,o),this.events.emit(it.created,{target:n,expiration:o})}),Ue(this,"get",i=>{this.isInitialized();const s=this.formatTarget(i);return this.getExpiration(s)}),Ue(this,"del",i=>{if(this.isInitialized(),this.has(i)){const s=this.formatTarget(i),n=this.getExpiration(s);this.expirations.delete(s),this.events.emit(it.deleted,{target:s,expiration:n})}}),Ue(this,"on",(i,s)=>{this.events.on(i,s)}),Ue(this,"once",(i,s)=>{this.events.once(i,s)}),Ue(this,"off",(i,s)=>{this.events.off(i,s)}),Ue(this,"removeListener",(i,s)=>{this.events.removeListener(i,s)}),this.logger=et(r,this.name)}get context(){return We(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 A1(e);if(typeof e=="number")return P1(e);const{message:r}=L("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}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(it.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=L("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}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 r=this.expirations.get(e);if(!r){const{message:i}=L("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;F.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(it.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(Rr.pulse,()=>this.checkExpirations()),this.events.on(it.created,e=>{const r=it.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(it.expired,e=>{const r=it.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(it.deleted,e=>{const r=it.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}}var AI=Object.defineProperty,PI=(t,e,r)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,pe=(t,e,r)=>PI(t,typeof e!="symbol"?e+"":e,r);class TI extends gg{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,pe(this,"name",T3),pe(this,"abortController"),pe(this,"isDevEnv"),pe(this,"verifyUrlV3",B3),pe(this,"storagePrefix",$t),pe(this,"version",Af),pe(this,"publicKey"),pe(this,"fetchPromise"),pe(this,"init",async()=>{var s;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&F.toMiliseconds((s=this.publicKey)==null?void 0:s.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),pe(this,"register",async s=>{if(!Qr()||this.isDevEnv)return;const n=window.location.origin,{id:o,decryptedId:a}=s,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${n}&id=${o}&decryptedId=${a}`;try{const u=Vt.getDocument(),l=this.startAbortTimer(F.ONE_SECOND*5),h=await new Promise((f,p)=>{const d=()=>{window.removeEventListener("message",g),u.body.removeChild(y),p("attestation aborted")};this.abortController.signal.addEventListener("abort",d);const y=u.createElement("iframe");y.src=c,y.style.display="none",y.addEventListener("error",d,{signal:this.abortController.signal});const g=b=>{if(b.data&&typeof b.data=="string")try{const m=JSON.parse(b.data);if(m.type==="verify_attestation"){if(Qn(m.attestation).payload.id!==o)return;clearInterval(l),u.body.removeChild(y),this.abortController.signal.removeEventListener("abort",d),window.removeEventListener("message",g),f(m.attestation===null?"":m.attestation)}}catch(m){this.logger.warn(m)}};u.body.appendChild(y),window.addEventListener("message",g,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(u){this.logger.warn(u)}return""}),pe(this,"resolve",async s=>{if(this.isDevEnv)return"";const{attestationId:n,hash:o,encryptedId:a}=s;if(n===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(n){if(Qn(n).payload.id!==a)return;const u=await this.isValidJwtAttestation(n);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(s?.verifyUrl);return this.fetchAttestation(o,c)}),pe(this,"fetchAttestation",async(s,n)=>{this.logger.debug(`resolving attestation: ${s} from url: ${n}`);const o=this.startAbortTimer(F.ONE_SECOND*5),a=await fetch(`${n}/attestation/${s}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),pe(this,"getVerifyUrl",s=>{let n=s||Ei;return C3.includes(n)||(this.logger.info(`verify url: ${n}, not included in trusted list, assigning default: ${Ei}`),n=Ei),n}),pe(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const s=this.startAbortTimer(F.FIVE_SECONDS),n=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(s),await n.json()}catch(s){this.logger.warn(s)}}),pe(this,"persistPublicKey",async s=>{this.logger.debug(s,"persisting public key to local storage"),await this.store.setItem(this.storeKey,s),this.publicKey=s}),pe(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),pe(this,"isValidJwtAttestation",async s=>{const n=await this.getPublicKey();try{if(n)return this.validateAttestation(s,n)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(s,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),pe(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),pe(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async n=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),n(o))});const s=await this.fetchPromise;return this.fetchPromise=void 0,s}),pe(this,"validateAttestation",(s,n)=>{const o=DE(s,n.publicKey),a={hasExpired:F.toMiliseconds(o.exp)<Date.now(),payload:o};if(a.hasExpired)throw this.logger.warn("resolve: jwt attestation expired"),new Error("JWT attestation expired");return{origin:a.payload.origin,isScam:a.payload.isScam,isVerified:a.payload.isVerified}}),this.logger=et(r,this.name),this.abortController=new AbortController,this.isDevEnv=Ho(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return We(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),F.toMiliseconds(e))}}var RI=Object.defineProperty,BI=(t,e,r)=>e in t?RI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Hu=(t,e,r)=>BI(t,typeof e!="symbol"?e+"":e,r);class CI extends yg{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,Hu(this,"context",U3),Hu(this,"registerDeviceToken",async i=>{const{clientId:s,token:n,notificationType:o,enableEncrypted:a=!1}=i,c=`${N3}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:s,type:o,token:n,always_raw:a})})}),this.logger=et(r,this.context)}}var UI=Object.defineProperty,Wu=Object.getOwnPropertySymbols,NI=Object.prototype.hasOwnProperty,kI=Object.prototype.propertyIsEnumerable,Oo=(t,e,r)=>e in t?UI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,di=(t,e)=>{for(var r in e||(e={}))NI.call(e,r)&&Oo(t,r,e[r]);if(Wu)for(var r of Wu(e))kI.call(e,r)&&Oo(t,r,e[r]);return t},Ee=(t,e,r)=>Oo(t,typeof e!="symbol"?e+"":e,r);class FI extends wg{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,Ee(this,"context",F3),Ee(this,"storagePrefix",$t),Ee(this,"storageVersion",k3),Ee(this,"events",new Map),Ee(this,"shouldPersist",!1),Ee(this,"init",async()=>{if(!Ho())try{const s={eventId:Pc(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:bh(this.core.relayer.protocol,this.core.relayer.version,vo)}}};await this.sendEvent([s])}catch(s){this.logger.warn(s)}}),Ee(this,"createEvent",s=>{const{event:n="ERROR",type:o="",properties:{topic:a,trace:c}}=s,u=Pc(),l=this.core.projectId||"",h=Date.now(),f=di({eventId:u,timestamp:h,props:{event:n,type:o,properties:{topic:a,trace:c}},bundleId:l,domain:this.getAppDomain()},this.setMethods(u));return this.telemetryEnabled&&(this.events.set(u,f),this.shouldPersist=!0),f}),Ee(this,"getEvent",s=>{const{eventId:n,topic:o}=s;if(n)return this.events.get(n);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return di(di({},a),this.setMethods(a.eventId))}),Ee(this,"deleteEvent",s=>{const{eventId:n}=s;this.events.delete(n),this.shouldPersist=!0}),Ee(this,"setEventListeners",()=>{this.core.heartbeat.on(Rr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(s=>{F.fromMiliseconds(Date.now())-F.fromMiliseconds(s.timestamp)>L3&&(this.events.delete(s.eventId),this.shouldPersist=!0)})})}),Ee(this,"setMethods",s=>({addTrace:n=>this.addTrace(s,n),setError:n=>this.setError(s,n)})),Ee(this,"addTrace",(s,n)=>{const o=this.events.get(s);o&&(o.props.properties.trace.push(n),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"setError",(s,n)=>{const o=this.events.get(s);o&&(o.props.type=n,o.timestamp=Date.now(),this.events.set(s,o),this.shouldPersist=!0)}),Ee(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),Ee(this,"restore",async()=>{try{const s=await this.core.storage.getItem(this.storageKey)||[];if(!s.length)return;s.forEach(n=>{this.events.set(n.eventId,di(di({},n),this.setMethods(n.eventId)))})}catch(s){this.logger.warn(s)}}),Ee(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const s=[];for(const[n,o]of this.events)o.props.type&&s.push(o);if(s.length!==0)try{if((await this.sendEvent(s)).ok)for(const n of s)this.events.delete(n.eventId),this.shouldPersist=!0}catch(n){this.logger.warn(n)}}),Ee(this,"sendEvent",async s=>{const n=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${M3}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${vo}${n}`,{method:"POST",body:JSON.stringify(s)})}),Ee(this,"getAppDomain",()=>wh().url),this.logger=et(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var LI=Object.defineProperty,Gu=Object.getOwnPropertySymbols,MI=Object.prototype.hasOwnProperty,jI=Object.prototype.propertyIsEnumerable,Ao=(t,e,r)=>e in t?LI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yu=(t,e)=>{for(var r in e||(e={}))MI.call(e,r)&&Ao(t,r,e[r]);if(Gu)for(var r of Gu(e))jI.call(e,r)&&Ao(t,r,e[r]);return t},ce=(t,e,r)=>Ao(t,typeof e!="symbol"?e+"":e,r);class oa extends sg{constructor(e){var r;super(e),ce(this,"protocol",Of),ce(this,"version",Af),ce(this,"name",mo),ce(this,"relayUrl"),ce(this,"projectId"),ce(this,"customStoragePrefix"),ce(this,"events",new Ot.EventEmitter),ce(this,"logger"),ce(this,"heartbeat"),ce(this,"relayer"),ce(this,"crypto"),ce(this,"storage"),ce(this,"history"),ce(this,"expirer"),ce(this,"pairing"),ce(this,"verify"),ce(this,"echoClient"),ce(this,"linkModeSupportedApps"),ce(this,"eventClient"),ce(this,"initialized",!1),ce(this,"logChunkController"),ce(this,"on",(a,c)=>this.events.on(a,c)),ce(this,"once",(a,c)=>this.events.once(a,c)),ce(this,"off",(a,c)=>this.events.off(a,c)),ce(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),ce(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:u})=>{if(!a||!c)return;const l={topic:a,message:c,publishedAt:Date.now(),transportType:ue.link_mode};this.relayer.onLinkMessageEvent(l,{sessionExists:u})});const i=this.getGlobalCore(e?.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e?.projectId,this.relayUrl=e?.relayUrl||Tf,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const s=Jp({level:typeof e?.logger=="string"&&e.logger?e.logger:a3.logger,name:mo}),{logger:n,chunkLoggerController:o}=ll({opts:s,maxSizeInBytes:e?.maxLogBlobSizeInBytes,loggerOverride:e?.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.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=et(n,this.name),this.heartbeat=new Cd,this.crypto=new g8(this,this.logger,e?.keychain),this.history=new SI(this,this.logger),this.expirer=new OI(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fp(Yu(Yu({},c3),e?.storageOptions)),this.relayer=new q8({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new xI(this,this.logger),this.verify=new TI(this,this.logger,this.storage),this.echoClient=new CI(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new FI(this,this.logger,e?.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new oa(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(x3,i),r}get context(){return We(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($u,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($u)||[],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 r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof at<"u"&&o3.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}}const qI=oa,Vf="wc",Kf=2,Hf="client",aa=`${Vf}@${Kf}:${Hf}:`,Fn={name:Hf,logger:"error"},Zu="WALLETCONNECT_DEEPLINK_CHOICE",zI="proposal",Ju="Proposal expired",VI="session",qr=F.SEVEN_DAYS,KI="engine",$e={wc_sessionPropose:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1104},res:{ttl:F.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1106},res:{ttl:F.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:F.FIVE_MINUTES*3,prompt:!0,tag:1108},res:{ttl:F.FIVE_MINUTES*3,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:F.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1112},res:{ttl:F.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:F.ONE_DAY,prompt:!1,tag:1114},res:{ttl:F.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:F.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:F.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:F.FIVE_MINUTES,prompt:!1,tag:1119}}},Ln={min:F.FIVE_MINUTES,max:F.SEVEN_DAYS},Et={idle:"IDLE",active:"ACTIVE"},HI={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:""}},WI="request",GI=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],YI="wc",ZI="auth",JI="authKeys",XI="pairingTopics",QI="requests",Ks=`${YI}@${1.5}:${ZI}:`,ls=`${Ks}:PUB_KEY`;var eS=Object.defineProperty,tS=Object.defineProperties,rS=Object.getOwnPropertyDescriptors,Xu=Object.getOwnPropertySymbols,iS=Object.prototype.hasOwnProperty,sS=Object.prototype.propertyIsEnumerable,Po=(t,e,r)=>e in t?eS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,re=(t,e)=>{for(var r in e||(e={}))iS.call(e,r)&&Po(t,r,e[r]);if(Xu)for(var r of Xu(e))sS.call(e,r)&&Po(t,r,e[r]);return t},Oe=(t,e)=>tS(t,rS(e)),C=(t,e,r)=>Po(t,typeof e!="symbol"?e+"":e,r);class nS extends Eg{constructor(e){super(e),C(this,"name",KI),C(this,"events",new Qu),C(this,"initialized",!1),C(this,"requestQueue",{state:Et.idle,queue:[]}),C(this,"sessionRequestQueue",{state:Et.idle,queue:[]}),C(this,"emittedSessionRequests",new L1({limit:500})),C(this,"requestQueueDelay",F.ONE_SECOND),C(this,"expectedPairingMethodMap",new Map),C(this,"recentlyDeletedMap",new Map),C(this,"recentlyDeletedLimit",200),C(this,"relayMessageCache",[]),C(this,"pendingSessions",new Map),C(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($e)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay)))}),C(this,"connect",async r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const s=Oe(re({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(s),s.optionalNamespaces=ZE(s.requiredNamespaces,s.optionalNamespaces),s.requiredNamespaces={};const{pairingTopic:n,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:u,relays:l,authentication:h,walletPay:f}=s,p=((i=h?.[0])==null?void 0:i.ttl)||$e.wc_sessionPropose.req.ttl||F.FIVE_MINUTES;this.validateRequestExpiry(p);let d=n,y,g=!1;try{if(d){const $=this.client.core.pairing.pairings.get(d);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),g=$.active}}catch($){throw this.client.logger.error(`connect() -> pairing.get(${d}) failed`),$}if(!d||!g){const{topic:$,uri:M}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});d=$,y=M}if(!d){const{message:$}=L("NO_MATCHING_KEY",`connect() pairing topic: ${d}`);throw new Error($)}const b=await this.client.core.crypto.generateKeyPair(),m=be(p),w=re(Oe(re(re({requiredNamespaces:o,optionalNamespaces:a,relays:l??[{protocol:Pf}],proposer:{publicKey:b,metadata:this.client.metadata},expiryTimestamp:m,pairingTopic:d},c&&{sessionProperties:c}),u&&{scopedProperties:u}),{id:_t()}),(h||f)&&{requests:{authentication:h?.map($=>{const{domain:M,chains:q,nonce:R,uri:_,exp:S,nbf:E,type:v,statement:D,requestId:P,resources:x,signatureTypes:A}=$;return{domain:M,chains:q,nonce:R,type:v??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:S,nbf:E,statement:D,requestId:P,resources:x,signatureTypes:A}}),walletPay:f}}),I=ne("session_connect",w.id),{reject:O,resolve:T,done:B}=xr(p,Ju),N=({id:$})=>{$===w.id&&(this.client.events.off("proposal_expire",N),this.pendingSessions.delete(w.id),this.events.emit(I,{error:{message:Ju,code:0}}))};return this.client.events.on("proposal_expire",N),this.events.once(I,({error:$,session:M})=>{this.client.events.off("proposal_expire",N),$?O($):M&&T(M)}),await this.setProposal(w.id,w),await this.sendProposeSession({proposal:w,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:w.id}}}).catch($=>{throw this.deleteProposal(w.id),$}),{uri:y,approval:B}}),C(this,"pair",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),C(this,"approve",async r=>{var i,s,n;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r?.id)==null?void 0:i.toString(),trace:[ht.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(M){throw o.setError(vr.no_internet_connection),M}try{await this.isValidProposalId(r?.id)}catch(M){throw this.client.logger.error(`approve() -> proposal.get(${r?.id}) failed`),o.setError(vr.proposal_not_found),M}try{await this.isValidApprove(r)}catch(M){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(vr.session_approve_namespace_validation_failure),M}const{id:a,relayProtocol:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=r,d=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:y,proposer:g,requiredNamespaces:b,optionalNamespaces:m}=d;let w=(s=this.client.core.eventClient)==null?void 0:s.getEvent({topic:y});w||(w=(n=this.client.core.eventClient)==null?void 0:n.createEvent({type:ht.session_approve_started,properties:{topic:y,trace:[ht.session_approve_started,ht.session_namespaces_validation_success]}}));const I=await this.client.core.crypto.generateKeyPair(),O=g.publicKey,T=await this.client.core.crypto.generateSharedKey(I,O),B=Oe(re(re(re({relay:{protocol:c??"irn"},namespaces:u,controller:{publicKey:I,metadata:this.client.metadata},expiry:be(qr)},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:p}),N=ue.relay;w.addTrace(ht.subscribing_session_topic);try{await this.client.core.relayer.subscribe(T,{transportType:N,internal:{skipSubscribe:!0}})}catch(M){throw w.setError(vr.subscribe_session_topic_failure),M}w.addTrace(ht.subscribe_session_topic_success);const $=Oe(re({},B),{topic:T,requiredNamespaces:b,optionalNamespaces:m,pairingTopic:y,acknowledged:!1,self:B.controller,peer:{publicKey:g.publicKey,metadata:g.metadata},controller:I,transportType:ue.relay,authentication:p?.authentication,walletPayResult:p?.walletPay});await this.client.session.set(T,$),w.addTrace(ht.store_session);try{await this.sendApproveSession({sessionTopic:T,proposal:d,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:I},sessionSettleRequest:B,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:re({correlationId:a},this.getTVFApproveParams($))}}),w.addTrace(ht.session_approve_publish_success)}catch(M){throw this.client.logger.error(M),this.client.session.delete(T,he("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(T),M}return this.client.core.eventClient.deleteEvent({eventId:w.eventId}),await this.client.core.pairing.updateMetadata({topic:y,metadata:g.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:y}),await this.setExpiry(T,be(qr)),{topic:T,acknowledged:()=>Promise.resolve(this.client.session.get(T))}}),C(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:s}=r;let n;try{n=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}n&&await this.sendError({id:i,topic:n,error:s,rpcOpts:$e.wc_sessionPropose.reject}),await this.deleteProposal(i)}),C(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:s}=r,{done:n,resolve:o,reject:a}=xr(F.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=_t(),u=cr().toString(),l=this.client.session.get(i).namespaces;return this.events.once(ne("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:s}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:s},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:u}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:l}),a(h)}),{acknowledged:n}}),C(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,s=_t(),{done:n,resolve:o,reject:a}=xr(F.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ne("session_extend",s),({error:c})=>{c?a(c):o()}),await this.setExpiry(i,be(qr)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:s,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:n}}),C(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(g){throw this.client.logger.error("request() -> isValidRequest() failed"),g}const{chainId:i,request:s,topic:n,expiry:o=$e.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(n);a?.transportType===ue.relay&&await this.confirmOnlineStateOrThrow();const c=_t(),u=cr().toString(),{done:l,resolve:h,reject:f}=xr(o,"Request expired. Please try again.");this.events.once(ne("session_request",c),({error:g,result:b})=>{g?f(g):h(b)});const p="wc_sessionRequest",d=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(d)return await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:{request:Oe(re({},s),{expiryTimestamp:be(o)}),chainId:i},expiry:o,throwOnFailedPublish:!0,appLink:d}).catch(g=>f(g)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),await l();const y={request:Oe(re({},s),{expiryTimestamp:be(o)}),chainId:i};return await Promise.all([new Promise(async g=>{await this.sendRequest({clientRpcId:c,relayRpcId:u,topic:n,method:p,params:y,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,y)}).catch(b=>f(b)),this.client.events.emit("session_request_sent",{topic:n,request:s,chainId:i,id:c}),g()}),new Promise(async g=>{var b;if(!((b=a.sessionConfig)!=null&&b.disableDeepLink)){const m=await C1(this.client.core.storage,Zu);await T1({id:c,topic:n,wcDeepLink:m})}g()}),l()]).then(g=>g[2])}),C(this,"respond",async r=>{var i,s;this.isInitialized();const n=this.client.core.eventClient.createEvent({properties:{topic:r?.topic||((s=(i=r?.response)==null?void 0:i.id)==null?void 0:s.toString()),trace:[ht.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw n.addTrace(h?.message),n.setError(vr.session_request_response_validation_failure),h}n.addTrace(ht.session_request_response_validation_success);const{topic:o,response:a}=r,{id:c}=a,u=this.client.session.get(o);u.transportType===ue.relay&&await this.confirmOnlineStateOrThrow();const l=this.getAppLinkIfEnabled(u.peer.metadata,u.transportType);try{n.addTrace(ht.session_request_response_publish_started),It(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:l}):nt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:l}),this.cleanupAfterResponse(r)}catch(h){throw n.addTrace(h?.message),n.setError(vr.session_request_response_publish_failure),h}}),C(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(s){throw this.client.logger.error("ping() -> isValidPing() failed"),s}const{topic:i}=r;if(this.client.session.keys.includes(i)){const s=_t(),n=cr().toString(),{done:o,resolve:a,reject:c}=xr(F.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ne("session_ping",s),({error:u})=>{u?c(u):a()}),await Promise.all([this.sendRequest({topic:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:s,relayRpcId:n}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(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:i}))}),C(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:s,chainId:n}=r,o=cr().toString(),a=_t();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:s,chainId:n},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),C(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:he("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:s}=L("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(s)}}),C(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>JE(i,r)))),C(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),C(this,"authenticate",async(r,i)=>{var s;this.isInitialized(),this.isValidAuthenticate(r);const n=i&&this.client.core.linkModeSupportedApps.includes(i)&&((s=this.client.metadata.redirect)==null?void 0:s.linkMode),o=n?ue.link_mode:ue.relay;o===ue.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:u,domain:l,nonce:h,type:f,exp:p,nbf:d,methods:y=[],expiry:g}=r,b=[...r.resources||[]],{topic:m,uri:w}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:m,uri:w}});const I=await this.client.core.crypto.generateKeyPair(),O=cs(I);if(await Promise.all([this.client.auth.authKeys.set(ls,{responseTopic:O,publicKey:I}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:m})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${m}`),y.length>0){const{namespace:x}=os(a[0]);let A=Xv(x,"request",y);as(b)&&(A=e2(A,b.pop())),b.push(A)}const T=g&&g>$e.wc_sessionAuthenticate.req.ttl?g:$e.wc_sessionAuthenticate.req.ttl,B={authPayload:{type:f??"caip122",chains:a,statement:c,aud:u,domain:l,version:"1",nonce:h,iat:new Date().toISOString(),exp:p,nbf:d,resources:b},requester:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:be(T)},N={eip155:{chains:a,methods:[...new Set(["personal_sign",...y])],events:["chainChanged","accountsChanged"]}},$={requiredNamespaces:{},optionalNamespaces:N,relays:[{protocol:"irn"}],pairingTopic:m,proposer:{publicKey:I,metadata:this.client.metadata},expiryTimestamp:be($e.wc_sessionPropose.req.ttl),id:_t()},{done:M,resolve:q,reject:R}=xr(T,"Request expired"),_=_t(),S=ne("session_connect",$.id),E=ne("session_request",_),v=async({error:x,session:A})=>{this.events.off(E,D),x?R(x):A&&q({session:A})},D=async x=>{var A,U,k;if(await this.deletePendingAuthRequest(_,{message:"fulfilled",code:0}),x.error){const W=he("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return x.error.code===W.code?void 0:(this.events.off(S,v),R(x.error.message))}await this.deleteProposal($.id),this.events.off(S,v);const{cacaos:K,responder:V}=x.result,z=[],H=[];for(const W of K){await jc({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),R(he("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:se}=W,ye=as(se.resources),Ge=[no(se.iss)],wt=vs(se.iss);if(ye){const At=qc(ye),Hs=zc(ye);z.push(...At),Ge.push(...Hs)}for(const At of Ge)H.push(`${At}:${wt}`)}const Y=await this.client.core.crypto.generateSharedKey(I,V.publicKey);let X;z.length>0&&(X={topic:Y,acknowledged:!0,self:{publicKey:I,metadata:this.client.metadata},peer:V,controller:V.publicKey,expiry:be(qr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:m,namespaces:pu([...new Set(z)],[...new Set(H)]),transportType:o},await this.client.core.relayer.subscribe(Y,{transportType:o}),await this.client.session.set(Y,X),m&&await this.client.core.pairing.updateMetadata({topic:m,metadata:V.metadata}),X=this.client.session.get(Y)),(A=this.client.metadata.redirect)!=null&&A.linkMode&&(U=V.metadata.redirect)!=null&&U.linkMode&&(k=V.metadata.redirect)!=null&&k.universal&&i&&(this.client.core.addLinkModeSupportedApp(V.metadata.redirect.universal),this.client.session.update(Y,{transportType:ue.link_mode})),q({auths:K,session:X})};this.events.once(S,v),this.events.once(E,D);let P;try{if(n){const x=Mt("wc_sessionAuthenticate",B,_);this.client.core.history.set(m,x);const A=await this.client.core.crypto.encode("",x,{type:Mi,encoding:or});P=rs(i,m,A)}else await Promise.all([this.sendRequest({topic:m,method:"wc_sessionAuthenticate",params:B,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),this.sendRequest({topic:m,method:"wc_sessionPropose",params:$,expiry:$e.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:$.id})])}catch(x){throw this.events.off(S,v),this.events.off(E,D),x}return await this.setProposal($.id,$),await this.setAuthRequest(_,{request:Oe(re({},B),{verifyContext:{}}),pairingTopic:m,transportType:o}),{uri:P??w,response:M}}),C(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:s}=r,n=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Er.authenticated_session_approve_started]}});try{this.isInitialized()}catch(g){throw n.setError(hi.no_internet_connection),g}const o=this.getPendingAuthRequest(i);if(!o)throw n.setError(hi.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);const a=o.transportType||ue.relay;a===ue.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,u=await this.client.core.crypto.generateKeyPair(),l=cs(c),h={type:zt,receiverPublicKey:c,senderPublicKey:u},f=[],p=[];for(const g of s){if(!await jc({cacao:g,projectId:this.client.core.projectId})){n.setError(hi.invalid_cacao);const O=he("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:l,error:O,encodeOpts:h}),new Error(O.message)}n.addTrace(Er.cacaos_verified);const{p:b}=g,m=as(b.resources),w=[no(b.iss)],I=vs(b.iss);if(m){const O=qc(m),T=zc(m);f.push(...O),w.push(...T)}for(const O of w)p.push(`${O}:${I}`)}const d=await this.client.core.crypto.generateSharedKey(u,c);n.addTrace(Er.create_authenticated_session_topic);let y;if(f?.length>0){y={topic:d,acknowledged:!0,self:{publicKey:u,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:be(qr),authentication:s,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:pu([...new Set(f)],[...new Set(p)]),transportType:a},n.addTrace(Er.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(d,{transportType:a})}catch(g){throw n.setError(hi.subscribe_authenticated_session_topic_failure),g}n.addTrace(Er.subscribe_authenticated_session_topic_success),await this.client.session.set(d,y),n.addTrace(Er.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}n.addTrace(Er.publishing_authenticated_session_approve);try{await this.sendResult({topic:l,id:i,result:{cacaos:s,responder:{publicKey:u,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(g){throw n.setError(hi.authenticated_session_approve_publish_failure),g}return await this.client.auth.requests.delete(i,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:n.eventId}),{session:y}}),C(this,"rejectSessionAuthenticate",async r=>{this.isInitialized();const{id:i,reason:s}=r,n=this.getPendingAuthRequest(i);if(!n)throw new Error(`Could not find pending auth request with id ${i}`);n.transportType===ue.relay&&await this.confirmOnlineStateOrThrow();const o=n.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=cs(o),u={type:zt,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,topic:c,error:s,encodeOpts:u,rpcOpts:$e.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(n.requester.metadata,n.transportType)}),await this.client.auth.requests.delete(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),C(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:s}=r;return kh(i,s)}),C(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),C(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.pairingTopic),s=this.client.core.pairing.pairings.getAll().filter(n=>{var o,a;return((o=n.peerMetadata)==null?void 0:o.url)&&((a=n.peerMetadata)==null?void 0:a.url)===r.peer.metadata.url&&n.topic&&n.topic!==i.topic});if(s.length===0)return;this.client.logger.info(`Cleaning up ${s.length} duplicate pairing(s)`),await Promise.all(s.map(n=>this.client.core.pairing.disconnect({topic:n.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(i){this.client.logger.error(i)}}),C(this,"deleteSession",async r=>{var i;const{topic:s,expirerHasDeleted:n=!1,emitEvent:o=!0,id:a=0}=r,{self:c}=this.client.session.get(s);await this.client.core.relayer.unsubscribe(s),await this.client.session.delete(s,he("USER_DISCONNECTED")),this.addToRecentlyDeleted(s,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(s)&&await this.client.core.crypto.deleteSymKey(s),n||this.client.core.expirer.del(s),this.client.core.storage.removeItem(Zu).catch(u=>this.client.logger.warn(u)),s===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.topic)&&(this.sessionRequestQueue.state=Et.idle),await Promise.all(this.getPendingSessionRequests().filter(u=>u.topic===s).map(u=>this.deletePendingSessionRequest(u.id,he("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:s})}),C(this,"deleteProposal",async(r,i)=>{if(i)try{const s=this.client.proposal.get(r);this.client.core.eventClient.getEvent({topic:s.pairingTopic})?.setError(vr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,he("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),C(this,"deletePendingSessionRequest",async(r,i,s=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(n=>n.id!==r),s&&(this.sessionRequestQueue.state=Et.idle,this.client.events.emit("session_request_expire",{id:r}))}),C(this,"deletePendingAuthRequest",async(r,i,s=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),s?Promise.resolve():this.client.core.expirer.del(r)])}),C(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),C(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,be($e.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),C(this,"setAuthRequest",async(r,i)=>{const{request:s,pairingTopic:n,transportType:o=ue.relay}=i;this.client.core.expirer.set(r,s.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:s.authPayload,requester:s.requester,expiryTimestamp:s.expiryTimestamp,id:r,pairingTopic:n,verifyContext:s.verifyContext,transportType:o})}),C(this,"setPendingSessionRequest",async r=>{const{id:i,topic:s,params:n,verifyContext:o}=r,a=n.request.expiryTimestamp||be($e.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:s,params:n,verifyContext:o})}),C(this,"sendRequest",async r=>{const{topic:i,method:s,params:n,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:u,appLink:l,tvf:h,publishOpts:f={}}=r,p=Mt(s,n,c);let d;const y=!!l;try{const m=y?or:Ve;d=await this.client.core.crypto.encode(i,p,{encoding:m})}catch(m){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),m}let g;if(GI.includes(s)){const m=st(JSON.stringify(p)),w=st(d);g=await this.client.core.verify.register({id:w,decryptedId:m})}const b=re(re({},$e[s].req),f);if(b.attestation=g,o&&(b.ttl=o),a&&(b.id=a),this.client.core.history.set(i,p),y){const m=rs(l,i,d);await G.Linking.openURL(m,this.client.name)}else b.tvf=Oe(re({},h),{correlationId:p.id}),u?(b.internal=Oe(re({},b.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,d,b)):this.client.core.relayer.publish(i,d,b).catch(m=>this.client.logger.error(m));return p.id}),C(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:s}=r,n=Mt("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,n);const o=await this.client.core.crypto.encode(i.pairingTopic,n,{encoding:Ve}),a=st(JSON.stringify(n)),c=st(o),u=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:i.pairingTopic,sessionProposal:o},opts:Oe(re({},s),{publishMethod:"wc_proposeSession",attestation:u})})}),C(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:s,proposal:n,sessionSettleRequest:o,publishOpts:a}=r,c=$s(n.id,s),u=await this.client.core.crypto.encode(n.pairingTopic,c,{encoding:Ve}),l=Mt("wc_sessionSettle",o,a?.id),h=await this.client.core.crypto.encode(i,l,{encoding:Ve});this.client.core.history.set(i,l),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:n.pairingTopic,sessionProposalResponse:u,sessionSettlementRequest:h},opts:Oe(re({},a),{publishMethod:"wc_approveSession"})})}),C(this,"sendResult",async r=>{const{id:i,topic:s,result:n,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,u=$s(i,n);let l;const h=c&&typeof(G==null?void 0:G.Linking)<"u";try{const d=h?or:Ve;l=await this.client.core.crypto.encode(s,u,Oe(re({},a||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${s} failed`),d}let f,p;try{f=await this.client.core.history.get(s,i);const d=f.request;try{p=this.getTVFParams(i,d.params,n)}catch(y){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${y?.message}`)}}catch(d){throw this.client.logger.error(`sendResult() -> history.get(${s}, ${i}) failed`),d}if(h){const d=rs(c,s,l);await G.Linking.openURL(d,this.client.name)}else{const d=f.request.method,y=$e[d].res;y.tvf=Oe(re({},p),{correlationId:i}),o?(y.internal=Oe(re({},y.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(s,l,y)):this.client.core.relayer.publish(s,l,y).catch(g=>this.client.logger.error(g))}await this.client.core.history.resolve(u)}),C(this,"sendError",async r=>{const{id:i,topic:s,error:n,encodeOpts:o,rpcOpts:a,appLink:c}=r,u=sa(i,n);let l;const h=c&&typeof(G==null?void 0:G.Linking)<"u";try{const p=h?or:Ve;l=await this.client.core.crypto.encode(s,u,Oe(re({},o||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${s} failed`),p}let f;try{f=await this.client.core.history.get(s,i)}catch(p){throw this.client.logger.error(`sendError() -> history.get(${s}, ${i}) failed`),p}if(h){const p=rs(c,s,l);await G.Linking.openURL(p,this.client.name)}else{const p=f.request.method,d=a||$e[p].res;this.client.core.relayer.publish(s,l,d)}await this.client.core.history.resolve(u)}),C(this,"cleanup",async()=>{const r=[],i=[];this.client.session.getAll().forEach(s=>{let n=!1;er(s.expiry)&&(n=!0),this.client.core.crypto.keychain.has(s.topic)||(n=!0),n&&r.push(s.topic)}),this.client.proposal.getAll().forEach(s=>{er(s.expiryTimestamp)&&i.push(s.id)}),await Promise.all([...r.map(s=>this.deleteSession({topic:s})),...i.map(s=>this.deleteProposal(s))])}),C(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),C(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),await this.processRequestsQueue()}),C(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===Et.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=Et.active;const r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=Et.idle}),C(this,"processRequest",async r=>{const{topic:i,payload:s,attestation:n,transportType:o,encryptedId:a}=r,c=s.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:s,attestation:n,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,s);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,s);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,s);case"wc_sessionPing":return await this.onSessionPingRequest(i,s);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,s);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,s);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:s,attestation:n,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),C(this,"onRelayEventResponse",async r=>{const{topic:i,payload:s,transportType:n}=r,o=(await this.client.core.history.get(i,s.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,s,n);case"wc_sessionSettle":return this.onSessionSettleResponse(i,s);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,s);case"wc_sessionExtend":return this.onSessionExtendResponse(i,s);case"wc_sessionPing":return this.onSessionPingResponse(i,s);case"wc_sessionRequest":return this.onSessionRequestResponse(i,s);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,s);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),C(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:s}=L("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(s)}),C(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:s}=r,n=this.expectedPairingMethodMap.get(i);return!n||n.includes(s)?!1:!!(n.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),C(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:s,attestation:n,encryptedId:o}=r,{params:a,id:c}=s;try{const u=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),u?.setError(kt.proposal_listener_not_found)),this.isValidConnect(re({},s.params));const l=a.expiryTimestamp||be($e.wc_sessionPropose.req.ttl),h=re({id:c,pairingTopic:i,expiryTimestamp:l,attestation:n,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:n,hash:st(JSON.stringify(s)),encryptedId:o,metadata:h.proposer.metadata});u?.addTrace(xt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(u){await this.sendError({id:c,topic:i,error:u,rpcOpts:$e.wc_sessionPropose.autoReject}),this.client.logger.error(u)}}),C(this,"onSessionProposeResponse",async(r,i,s)=>{const{id:n}=i;if(It(i)){const{result:o}=i;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(n);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(n,{sessionTopic:l,pairingTopic:r,proposalId:n,publicKey:c});const h=await this.client.core.relayer.subscribe(l,{transportType:s});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:r})}else if(nt(i)){await this.deleteProposal(n);const o=ne("session_connect",n);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:i.error})}}),C(this,"onSessionSettleRequest",async(r,i)=>{const{id:s,params:n}=i;try{this.isValidSessionSettleRequest(n);const{relay:o,controller:a,expiry:c,namespaces:u,sessionProperties:l,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:p}=i.params,d=[...this.pendingSessions.values()].find(b=>b.sessionTopic===r);if(!d)return this.client.logger.error(`Pending session not found for topic ${r}`);const y=this.client.proposal.get(d.proposalId),g=Oe(re(re(re({topic:r,relay:o,expiry:c,namespaces:u,acknowledged:!0,pairingTopic:d.pairingTopic,requiredNamespaces:y.requiredNamespaces,optionalNamespaces:y.optionalNamespaces,controller:a.publicKey,self:{publicKey:d.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},l&&{sessionProperties:l}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:ue.relay,authentication:p?.authentication,walletPayResult:p?.walletPay});await this.client.session.set(g.topic,g),await this.setExpiry(g.topic,g.expiry),await this.client.core.pairing.updateMetadata({topic:d.pairingTopic,metadata:g.peer.metadata}),this.pendingSessions.delete(d.proposalId),this.deleteProposal(d.proposalId,!1),this.cleanupDuplicatePairings(g),await this.sendResult({id:i.id,topic:r,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:g}),this.events.emit(ne("session_connect",d.proposalId),{session:g})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),C(this,"onSessionSettleResponse",async(r,i)=>{const{id:s}=i;It(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ne("session_approve",s),{})):nt(i)&&(await this.client.session.delete(r,he("USER_DISCONNECTED")),this.events.emit(ne("session_approve",s),{error:i.error}))}),C(this,"onSessionUpdateRequest",async(r,i)=>{const{params:s,id:n}=i;try{const o=`${r}_session_update`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.warn(`Discarding out of sync request - ${n}`),this.sendError({id:n,topic:r,error:he("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(re({topic:r},s));try{ui.set(o,n),await this.client.session.update(r,{namespaces:s.namespaces}),await this.sendResult({id:n,topic:r,result:!0})}catch(c){throw ui.delete(o),c}this.client.events.emit("session_update",{id:n,topic:r,params:s})}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),C(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),C(this,"onSessionUpdateResponse",(r,i)=>{const{id:s}=i,n=ne("session_update",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);It(i)?this.events.emit(ne("session_update",s),{}):nt(i)&&this.events.emit(ne("session_update",s),{error:i.error})}),C(this,"onSessionExtendRequest",async(r,i)=>{const{id:s}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,be(qr)),await this.sendResult({id:s,topic:r,result:!0}),this.client.events.emit("session_extend",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),C(this,"onSessionExtendResponse",(r,i)=>{const{id:s}=i,n=ne("session_extend",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);It(i)?this.events.emit(ne("session_extend",s),{}):nt(i)&&this.events.emit(ne("session_extend",s),{error:i.error})}),C(this,"onSessionPingRequest",async(r,i)=>{const{id:s}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:s,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:s,topic:r})}catch(n){await this.sendError({id:s,topic:r,error:n}),this.client.logger.error(n)}}),C(this,"onSessionPingResponse",(r,i)=>{const{id:s}=i,n=ne("session_ping",s);setTimeout(()=>{if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners 2176`);It(i)?this.events.emit(ne("session_ping",s),{}):nt(i)&&this.events.emit(ne("session_ping",s),{error:i.error})},500)}),C(this,"onSessionDeleteRequest",async(r,i)=>{const{id:s}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:he("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:s})}catch(n){this.client.logger.error(n)}}),C(this,"onSessionRequest",async r=>{var i,s,n;const{topic:o,payload:a,attestation:c,encryptedId:u,transportType:l}=r,{id:h,params:f}=a;try{await this.isValidRequest(re({topic:o},f));const p=this.client.session.get(o),d=await this.getVerifyContext({attestationId:c,hash:st(JSON.stringify(Mt("wc_sessionRequest",f,h))),encryptedId:u,metadata:p.peer.metadata,transportType:l}),y={id:h,topic:o,params:f,verifyContext:d};await this.setPendingSessionRequest(y),l===ue.link_mode&&(i=p.peer.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp((s=p.peer.metadata.redirect)==null?void 0:s.universal),(n=this.client.signConfig)!=null&&n.disableRequestQueue?this.emitSessionRequest(y):(this.addSessionRequestToSessionRequestQueue(y),this.processSessionRequestQueue())}catch(p){await this.sendError({id:h,topic:o,error:p}),this.client.logger.error(p)}}),C(this,"onSessionRequestResponse",(r,i)=>{const{id:s}=i,n=ne("session_request",s);if(this.events.listenerCount(n)===0)throw new Error(`emitting ${n} without any listeners`);It(i)?this.events.emit(ne("session_request",s),{result:i.result}):nt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),C(this,"onSessionEventRequest",async(r,i)=>{const{id:s,params:n}=i;try{const o=`${r}_session_event_${n.event.name}`,a=ui.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.info(`Discarding out of sync request - ${s}`);return}this.isValidEmit(re({topic:r},n)),this.client.events.emit("session_event",{id:s,topic:r,params:n}),ui.set(o,s)}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),C(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:s}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),It(i)?this.events.emit(ne("session_request",s),{result:i.result}):nt(i)&&this.events.emit(ne("session_request",s),{error:i.error})}),C(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:s,payload:n,attestation:o,encryptedId:a,transportType:c}=r;try{const{requester:u,authPayload:l,expiryTimestamp:h}=n.params,f=await this.getVerifyContext({attestationId:o,hash:st(JSON.stringify(n)),encryptedId:a,metadata:u.metadata,transportType:c}),p={requester:u,pairingTopic:s,id:n.id,authPayload:l,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(n.id,{request:p,pairingTopic:s,transportType:c}),c===ue.link_mode&&(i=u.metadata.redirect)!=null&&i.universal&&this.client.core.addLinkModeSupportedApp(u.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:s,params:n.params,id:n.id,verifyContext:f})}catch(u){this.client.logger.error(u);const l=n.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(n.params.requester.metadata,c),p={type:zt,receiverPublicKey:l,senderPublicKey:h};await this.sendError({id:n.id,topic:s,error:u,encodeOpts:p,rpcOpts:$e.wc_sessionAuthenticate.autoReject,appLink:f})}}),C(this,"addSessionRequestToSessionRequestQueue",r=>{this.sessionRequestQueue.queue.push(r)}),C(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=Et.idle,this.processSessionRequestQueue()},F.toMiliseconds(this.requestQueueDelay))}),C(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const s=this.client.core.history.pending;s.length>0&&s.filter(n=>n.topic===r&&n.request.method==="wc_sessionRequest").forEach(n=>{this.events.emit(ne("session_request",n.request.id),{error:i})})}),C(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===Et.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),C(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=Et.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),C(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(s=>s.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Mt("wc_sessionPropose",Oe(re({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),C(this,"isValidConnect",async r=>{if(!qe(r)){const{message:u}=L("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(u)}const{pairingTopic:i,requiredNamespaces:s,optionalNamespaces:n,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!ux(c)){const{message:u}=L("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(u)}if(s&&!_e(s)&&Oi(s)!==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(s,"requiredNamespaces")}if(n&&!_e(n)&&Oi(n)!==0&&this.validateNamespaces(n,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const u=Object.keys(s||{}).concat(Object.keys(n||{}));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)}`)}}),C(this,"validateNamespaces",(r,i)=>{const s=cx(r,"connect()",i);if(s)throw new Error(s.message)}),C(this,"isValidApprove",async r=>{if(!qe(r))throw new Error(L("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:s,relayProtocol:n,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),u=Rn(s,"approve()");if(u)throw new Error(u.message);const l=wo(c.requiredNamespaces,s,"approve()");if(l)throw new Error(l.message);if(!ge(n,!0)){const{message:h}=L("MISSING_OR_INVALID",`approve() relayProtocol: ${n}`);throw new Error(h)}if(o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(s));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),C(this,"isValidReject",async r=>{if(!qe(r)){const{message:n}=L("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(n)}const{id:i,reason:s}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!hx(s)){const{message:n}=L("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(s)}`);throw new Error(n)}}),C(this,"isValidSessionSettleRequest",r=>{if(!qe(r)){const{message:u}=L("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(u)}const{relay:i,controller:s,namespaces:n,expiry:o}=r;if(!_f(i)){const{message:u}=L("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(u)}const a=rx(s,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Rn(n,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(er(o)){const{message:u}=L("EXPIRED","onSessionSettleRequest()");throw new Error(u)}}),C(this,"isValidUpdate",async r=>{if(!qe(r)){const{message:c}=L("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:s}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const n=this.client.session.get(i),o=Rn(s,"update()");if(o)throw new Error(o.message);const a=wo(n.requiredNamespaces,s,"update()");if(a)throw new Error(a.message)}),C(this,"isValidExtend",async r=>{if(!qe(r)){const{message:s}=L("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(s)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),C(this,"isValidRequest",async r=>{if(!qe(r)){const{message:c}=L("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:s,chainId:n,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!yu(a,n)){const{message:c}=L("MISSING_OR_INVALID",`request() chainId: ${n}`);throw new Error(c)}if(!fx(s)){const{message:c}=L("MISSING_OR_INVALID",`request() ${JSON.stringify(s)}`);throw new Error(c)}if(!gx(a,n,s.method)){const{message:c}=L("MISSING_OR_INVALID",`request() method: ${s.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),C(this,"isValidRespond",async r=>{var i;if(!qe(r)){const{message:a}=L("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:s,response:n}=r;try{await this.isValidSessionTopic(s)}catch(a){throw(i=r?.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!dx(n)){const{message:a}=L("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(n)}`);throw new Error(a)}const o=this.client.pendingRequest.get(n.id);if(o.topic!==s){const{message:a}=L("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${n.id}, expected topic: ${o.topic}, received topic: ${s}`);throw new Error(a)}}),C(this,"isValidPing",async r=>{if(!qe(r)){const{message:s}=L("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),C(this,"isValidEmit",async r=>{if(!qe(r)){const{message:a}=L("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:s,chainId:n}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!yu(o,n)){const{message:a}=L("MISSING_OR_INVALID",`emit() chainId: ${n}`);throw new Error(a)}if(!px(s)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}if(!yx(o,n,s.name)){const{message:a}=L("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(s)}`);throw new Error(a)}}),C(this,"isValidDisconnect",async r=>{if(!qe(r)){const{message:s}=L("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),C(this,"isValidAuthenticate",r=>{const{chains:i,uri:s,domain:n,nonce:o}=r;if(!Array.isArray(i)||i.length===0)throw new Error("chains is required and must be a non-empty array");if(!ge(s,!1))throw new Error("uri is required parameter");if(!ge(n,!1))throw new Error("domain is required parameter");if(!ge(o,!1))throw new Error("nonce is required parameter");if([...new Set(i.map(c=>os(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=os(i[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),C(this,"getVerifyContext",async r=>{const{attestationId:i,hash:s,encryptedId:n,metadata:o,transportType:a}=r,c={verified:{verifyUrl:o.verifyUrl||Ei,validation:"UNKNOWN",origin:o.url||""}};try{if(a===ue.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:i,hash:s,encryptedId:n,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}),C(this,"validateSessionProps",(r,i)=>{Object.values(r).forEach((s,n)=>{if(s==null){const{message:o}=L("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${s} for key ${Object.keys(r)[n]}`);throw new Error(o)}})}),C(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),C(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let s=0;const n=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(s++>=n)break;this.recentlyDeletedMap.delete(o)}}}),C(this,"checkRecentlyDeleted",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:s}=L("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(s)}}),C(this,"isLinkModeEnabled",(r,i)=>{var s,n,o,a,c,u,l,h,f;return!r||i!==ue.link_mode?!1:((n=(s=this.client.metadata)==null?void 0:s.redirect)==null?void 0:n.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=r?.redirect)==null?void 0:l.universal)!==void 0&&((h=r?.redirect)==null?void 0:h.universal)!==""&&((f=r?.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(G==null?void 0:G.Linking)<"u"}),C(this,"getAppLinkIfEnabled",(r,i)=>{var s;return this.isLinkModeEnabled(r,i)?(s=r?.redirect)==null?void 0:s.universal:void 0}),C(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Ac(r,"topic")||"",s=decodeURIComponent(Ac(r,"wc_ev")||""),n=this.client.session.keys.includes(i);n&&this.client.session.update(i,{transportType:ue.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:s,sessionExists:n})}),C(this,"registerLinkModeListeners",async()=>{var r;if(Ho()||gr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=G==null?void 0:G.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const s=await i.getInitialURL();s&&setTimeout(()=>{this.handleLinkModeMessage({url:s})},50)}}}),C(this,"getTVFApproveParams",r=>{try{const i=vf(r.namespaces),s=VE(r.namespaces),n=KE(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:s,approvedEvents:n,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),C(this,"getTVFParams",(r,i,s)=>{var n,o,a;if(!((n=i.request)!=null&&n.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const u=this.extractTxHashesFromResult(i.request,s);c.txHashes=u,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.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}),C(this,"isValidContractData",r=>{var i;if(!r)return!1;try{const s=r?.data||((i=r?.[0])==null?void 0:i.data);if(!s.startsWith("0x"))return!1;const n=s.slice(2);return/^[0-9a-fA-F]*$/.test(n)?n.length%2===0:!1}catch{}return!1}),C(this,"extractTxHashesFromResult",(r,i)=>{var s;try{if(!i)return[];const n=r.method,o=HI[n];if(n==="sui_signTransaction")return[Bv(i.transactionBytes)];if(n==="near_signTransaction")return[kc(i)];if(n==="near_signTransactions")return i.map(c=>kc(c));if(n==="xrpl_signTransactionFor"||n==="xrpl_signTransaction")return[(s=i.tx_json)==null?void 0:s.hash];if(n==="polkadot_signTransaction")return[Cx({transaction:r.params.transactionPayload,signature:i.signature})];if(n==="algo_signTxn")return Jr(i)?i.map(c=>Fc(c)):[Fc(i)];if(n==="cosmos_signDirect")return[Uv(i)];if(n==="wallet_sendCalls")return Nv(i);if(typeof i=="string")return[i];const a=i[o.key];if(Jr(a))return n==="solana_signAllTransactions"?a.map(c=>Rv(c)):a;if(typeof a=="string")return[a]}catch(n){this.client.logger.warn(n,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,s]of Object.entries(r))for(const n of s)try{await this.onProviderMessageEvent({topic:i,message:n,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, message: ${n}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=L("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(fe.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:r,message:i,attestation:s,transportType:n}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ls)?this.client.auth.authKeys.get(ls):{publicKey:void 0};try{const a=await this.client.core.crypto.decode(r,i,{receiverPublicKey:o,encoding:n===ue.link_mode?or:Ve});na(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:s,transportType:n,encryptedId:st(i)})):zs(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:n}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:n})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(it.expired,async e=>{const{topic:r,id:i}=vh(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,L("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,L("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Ir.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Ir.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!ge(e,!1)){const{message:r}=L("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=L("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(er(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=L("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!ge(e,!1)){const{message:r}=L("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=L("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(er(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=L("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=L("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(ge(e,!1)){const{message:r}=L("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=L("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!lx(e)){const{message:r}=L("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=L("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(er(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=L("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!mx(e,Ln)){const{message:r}=L("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${Ln.min} and ${Ln.max}`);throw new Error(r)}}}class oS extends Cr{constructor(e,r){super(e,r,zI,aa),this.core=e,this.logger=r}}class aS extends Cr{constructor(e,r){super(e,r,VI,aa),this.core=e,this.logger=r}}class cS extends Cr{constructor(e,r){super(e,r,WI,aa,i=>i.id),this.core=e,this.logger=r}}class uS extends Cr{constructor(e,r){super(e,r,JI,Ks,()=>ls),this.core=e,this.logger=r}}class lS extends Cr{constructor(e,r){super(e,r,XI,Ks),this.core=e,this.logger=r}}class hS extends Cr{constructor(e,r){super(e,r,QI,Ks,i=>i.id),this.core=e,this.logger=r}}var fS=Object.defineProperty,dS=(t,e,r)=>e in t?fS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Mn=(t,e,r)=>dS(t,typeof e!="symbol"?e+"":e,r);class pS{constructor(e,r){this.core=e,this.logger=r,Mn(this,"authKeys"),Mn(this,"pairingTopics"),Mn(this,"requests"),this.authKeys=new uS(this.core,this.logger),this.pairingTopics=new lS(this.core,this.logger),this.requests=new hS(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var gS=Object.defineProperty,yS=(t,e,r)=>e in t?gS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>yS(t,typeof e!="symbol"?e+"":e,r);class ca extends vg{constructor(e){super(e),ee(this,"protocol",Vf),ee(this,"version",Kf),ee(this,"name",Fn.name),ee(this,"metadata"),ee(this,"core"),ee(this,"logger"),ee(this,"events",new Ot.EventEmitter),ee(this,"engine"),ee(this,"session"),ee(this,"proposal"),ee(this,"pendingRequest"),ee(this,"auth"),ee(this,"signConfig"),ee(this,"on",(i,s)=>this.events.on(i,s)),ee(this,"once",(i,s)=>this.events.once(i,s)),ee(this,"off",(i,s)=>this.events.off(i,s)),ee(this,"removeListener",(i,s)=>this.events.removeListener(i,s)),ee(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),ee(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"update",async i=>{try{return await this.engine.update(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"request",async i=>{try{return await this.engine.request(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"find",i=>{try{return this.engine.find(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),ee(this,"authenticate",async(i,s)=>{try{return await this.engine.authenticate(i,s)}catch(n){throw this.logger.error(n.message),n}}),ee(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),ee(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(s){throw this.logger.error(s.message),s}}),this.name=e?.name||Fn.name,this.metadata=S1(e?.metadata),this.signConfig=e?.signConfig;const r=If({logger:e?.logger||Fn.logger,name:this.name});this.logger=r,this.core=e?.core||new qI(e),this.session=new aS(this.core,this.logger),this.proposal=new oS(this.core,this.logger),this.pendingRequest=new cS(this.core,this.logger),this.engine=new nS(this),this.auth=new pS(this.core,this.logger)}static async init(e){const r=new ca(e);return await r.initialize(),r}get context(){return We(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 sD=ca;export{ZS as E,rD as G,he as V,sD as Y,u1 as b,ES as i,o1 as r};
