@dcl/vesting-dashboard 3.7.0 → 3.7.1-19868070294.commit-e76f047
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/PhArrowCircleDown-b4d1b9f0.js +14 -0
- package/assets/PhArrowClockwise-35e72491.js +14 -0
- package/assets/PhArrowDown-57c22b7e.js +14 -0
- package/assets/PhArrowLeft-f48f6a32.js +14 -0
- package/assets/PhArrowRight-86fee956.js +14 -0
- package/assets/PhArrowSquareOut-7b8bc76d.js +14 -0
- package/assets/PhArrowUp-cb14a0b1.js +14 -0
- package/assets/PhArrowUpRight-72a93a0e.js +14 -0
- package/assets/PhArrowsClockwise-ecc02e05.js +14 -0
- package/assets/PhArrowsDownUp-336a1435.js +14 -0
- package/assets/PhArrowsLeftRight-fbdccc02.js +14 -0
- package/assets/PhBank-31d2eba3.js +14 -0
- package/assets/PhBrowser-90d21d12.js +14 -0
- package/assets/PhCaretDown-3aabbdc5.js +14 -0
- package/assets/PhCaretLeft-282326ec.js +14 -0
- package/assets/PhCaretRight-7b09ae84.js +14 -0
- package/assets/PhCaretUp-e4584d94.js +14 -0
- package/assets/PhCheck-5730aae2.js +14 -0
- package/assets/PhCircleHalf-7d16bc06.js +14 -0
- package/assets/PhClock-8b060e99.js +14 -0
- package/assets/PhCompass-45d3bde6.js +14 -0
- package/assets/PhCopy-f77992ef.js +14 -0
- package/assets/PhCreditCard-c353277e.js +14 -0
- package/assets/PhCurrencyDollar-510272c7.js +14 -0
- package/assets/PhDesktop-49e8128e.js +14 -0
- package/assets/PhDeviceMobile-cfdf19ef.js +14 -0
- package/assets/PhDotsThree-69a484e4.js +14 -0
- package/assets/PhEnvelope-fc3dd2a0.js +14 -0
- package/assets/PhFunnelSimple-5abe9858.js +14 -0
- package/assets/PhGlobe-a1b4ca91.js +14 -0
- package/assets/PhIdentificationCard-80541484.js +14 -0
- package/assets/PhImage-6bbac6b7.js +14 -0
- package/assets/PhInfo-3481abef.js +14 -0
- package/assets/PhLightbulb-26b52ed2.js +14 -0
- package/assets/PhMagnifyingGlass-4dfb76cc.js +14 -0
- package/assets/PhPaperPlaneRight-e6cf54ef.js +14 -0
- package/assets/PhPlus-f5753116.js +14 -0
- package/assets/PhPower-8bf5c9c7.js +14 -0
- package/assets/PhPuzzlePiece-93f1c92b.js +14 -0
- package/assets/PhQrCode-03aa9f8a.js +14 -0
- package/assets/PhQuestion-6c2bd1ad.js +14 -0
- package/assets/PhQuestionMark-820f14af.js +14 -0
- package/assets/PhSealCheck-137e0b1b.js +14 -0
- package/assets/PhSignOut-ed65c268.js +14 -0
- package/assets/PhSpinner-19f53f69.js +14 -0
- package/assets/PhTrash-acb3ad59.js +14 -0
- package/assets/PhUser-92aa32ba.js +14 -0
- package/assets/PhVault-ed94ef20.js +14 -0
- package/assets/PhWarning-b2396b99.js +14 -0
- package/assets/PhWarningCircle-0f363973.js +14 -0
- package/assets/PhX-522d79dd.js +14 -0
- package/assets/basic-eeeaaaeb.js +1435 -0
- package/assets/core-84b3ed1e.js +254 -0
- package/assets/features-21cad012.js +5 -0
- package/assets/{fortmatic-544d83cd.js → fortmatic-f30106eb.js} +1 -1
- package/assets/{index-c655b8a4.js → index-04415554.js} +1 -1
- package/assets/index-069f2f19.js +40 -0
- package/assets/index-388893ce.js +1321 -0
- package/assets/index-516a1ffc.js +26 -0
- package/assets/{index-083f8aea.css → index-91d98a83.css} +7 -7
- package/assets/{index-4f5a2d6d.js → index-be0620a9.js} +1 -1
- package/assets/{index-eabed5f8.js → index-cf405d3f.js} +1 -1
- package/assets/index-ec27bc27.js +7 -0
- package/assets/{index-fa03581b.js → index-fec77d48.js} +136 -130
- package/assets/native-bf1092f7.js +1 -0
- package/assets/property-70d704fc.js +27 -0
- package/assets/w3m-modal-4a2f6c0b.js +1209 -0
- package/index.html +4 -4
- package/package.json +3 -3
- package/assets/add-acf9b1b4.js +0 -15
- package/assets/all-wallets-8da20287.js +0 -6
- package/assets/app-store-e67aed93.js +0 -17
- package/assets/apple-729c27b3.js +0 -18
- package/assets/arrow-bottom-circle-813b263a.js +0 -11
- package/assets/arrow-bottom-d6bb311f.js +0 -8
- package/assets/arrow-left-3f704ffa.js +0 -8
- package/assets/arrow-right-17ab2e3f.js +0 -8
- package/assets/arrow-top-54da8ce5.js +0 -8
- package/assets/bank-e1f4c3fc.js +0 -14
- package/assets/basic-ad614917.js +0 -2128
- package/assets/browser-eb97127f.js +0 -14
- package/assets/card-b0c5c8c1.js +0 -14
- package/assets/checkmark-bf5ef01d.js +0 -11
- package/assets/checkmark-bold-7e354e06.js +0 -8
- package/assets/chevron-bottom-d89d2664.js +0 -8
- package/assets/chevron-left-c5f39fe4.js +0 -8
- package/assets/chevron-right-d3c55332.js +0 -8
- package/assets/chevron-top-d80ad128.js +0 -8
- package/assets/chrome-store-d9e64081.js +0 -61
- package/assets/clock-e0f81e9c.js +0 -8
- package/assets/close-27f760b9.js +0 -8
- package/assets/coinPlaceholder-7de9c936.js +0 -8
- package/assets/compass-b58b98ec.js +0 -8
- package/assets/copy-be90f370.js +0 -15
- package/assets/core-22576ab2.js +0 -910
- package/assets/cursor-57ee0abd.js +0 -3
- package/assets/cursor-transparent-57538744.js +0 -12
- package/assets/desktop-5acc8b3e.js +0 -9
- package/assets/disconnect-d3f01128.js +0 -8
- package/assets/discord-8dae2632.js +0 -17
- package/assets/etherscan-81f5f92a.js +0 -6
- package/assets/exclamation-triangle-886b7149.js +0 -4
- package/assets/extension-0e9ba8a4.js +0 -8
- package/assets/external-link-b676fc52.js +0 -8
- package/assets/facebook-8d75c929.js +0 -26
- package/assets/farcaster-aa884f8f.js +0 -12
- package/assets/filters-90e66ffd.js +0 -8
- package/assets/github-693f2bd4.js +0 -18
- package/assets/google-484b54cf.js +0 -18
- package/assets/help-circle-45787a88.js +0 -12
- package/assets/id-3b4cbdd1.js +0 -12
- package/assets/image-96c3f9d0.js +0 -4
- package/assets/index-22afa741.js +0 -7
- package/assets/index-f40605ee.js +0 -394
- package/assets/index.es-6a347079.js +0 -26
- package/assets/info-165d435a.js +0 -3
- package/assets/info-circle-5b599100.js +0 -12
- package/assets/lightbulb-c8f2bf4d.js +0 -3
- package/assets/mail-30ba2d81.js +0 -8
- package/assets/mobile-e938b174.js +0 -9
- package/assets/more-4e55b5a2.js +0 -11
- package/assets/network-placeholder-9e336806.js +0 -14
- package/assets/nftPlaceholder-8e616704.js +0 -8
- package/assets/off-a0926c5e.js +0 -8
- package/assets/play-store-dc96d93b.js +0 -32
- package/assets/plus-db04badc.js +0 -13
- package/assets/qr-code-e9ab5aef.js +0 -6
- package/assets/recycle-horizontal-e5f00cf2.js +0 -9
- package/assets/refresh-6674ef4c.js +0 -8
- package/assets/reown-logo-377bcb99.js +0 -12
- package/assets/search-3013ef36.js +0 -8
- package/assets/secp256k1-20c931a5.js +0 -1
- package/assets/secp256k1-c7caed23.js +0 -1
- package/assets/send-042fe740.js +0 -15
- package/assets/swapHorizontal-cdd26797.js +0 -8
- package/assets/swapHorizontalBold-c0c1ec1e.js +0 -8
- package/assets/swapHorizontalMedium-12dd3e75.js +0 -16
- package/assets/swapHorizontalRoundedBold-d4067e2b.js +0 -8
- package/assets/swapVertical-2c2ae8b1.js +0 -8
- package/assets/telegram-c0a71203.js +0 -16
- package/assets/three-dots-8119300b.js +0 -5
- package/assets/twitch-8d0de139.js +0 -18
- package/assets/twitterIcon-26917bdd.js +0 -6
- package/assets/verify-a135ffbd.js +0 -8
- package/assets/verify-filled-29fa924e.js +0 -8
- package/assets/w3m-modal-742fa0d2.js +0 -642
- package/assets/wallet-5649743f.js +0 -8
- package/assets/wallet-placeholder-32773694.js +0 -14
- package/assets/walletconnect-3189ad6b.js +0 -30
- package/assets/warning-circle-37a8b22f.js +0 -12
- package/assets/x-ee5c9ccd.js +0 -12
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import{p as xt,g as $0,a as D0,b as Y,B as ie,e as St,c as pr,x as lc,o as ll,_ as O0}from"./index-fec77d48.js";var ul=globalThis&&globalThis.__spreadArray||function(t,e,i){if(i||arguments.length===2)for(var r=0,n=e.length,s;r<n;r++)(s||!(r in e))&&(s||(s=Array.prototype.slice.call(e,0,r)),s[r]=e[r]);return t.concat(s||Array.prototype.slice.call(e))},A0=function(){function t(e,i,r){this.name=e,this.version=i,this.os=r,this.type="browser"}return t}(),P0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),C0=function(){function t(e,i,r,n){this.name=e,this.version=i,this.os=r,this.bot=n,this.type="bot-device"}return t}(),B0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),T0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),R0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,F0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,hl=3,N0=[["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",R0]],fl=[["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 U0(t){return t?dl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new T0:typeof navigator<"u"?dl(navigator.userAgent):L0()}function k0(t){return t!==""&&N0.reduce(function(e,i){var r=i[0],n=i[1];if(e)return e;var s=n.exec(t);return!!s&&[r,s]},!1)}function dl(t){var e=k0(t);if(!e)return null;var i=e[0],r=e[1];if(i==="searchbot")return new B0;var n=r[1]&&r[1].split(".").join("_").split("_").slice(0,3);n?n.length<hl&&(n=ul(ul([],n,!0),M0(hl-n.length),!0)):n=[];var s=n.join("."),o=j0(t),a=F0.exec(t);return a&&a[1]?new C0(i,s,o,a[1]):new A0(i,s,o)}function j0(t){for(var e=0,i=fl.length;e<i;e++){var r=fl[e],n=r[0],s=r[1],o=s.exec(t);if(o)return n}return null}function L0(){var t=typeof xt<"u"&&xt.version;return t?new P0(xt.version.slice(1)):null}function M0(t){for(var e=[],i=0;i<t;i++)e.push("0");return e}var L={};/*! *****************************************************************************
|
|
2
|
+
Copyright (c) Microsoft Corporation.
|
|
3
|
+
|
|
4
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
5
|
+
purpose with or without fee is hereby granted.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
8
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
9
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
10
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
11
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
12
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
13
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
14
|
+
***************************************************************************** */var da=function(t,e){return da=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(i,r){i.__proto__=r}||function(i,r){for(var n in r)r.hasOwnProperty(n)&&(i[n]=r[n])},da(t,e)};function q0(t,e){da(t,e);function i(){this.constructor=t}t.prototype=e===null?Object.create(e):(i.prototype=e.prototype,new i)}var pa=function(){return pa=Object.assign||function(e){for(var i,r=1,n=arguments.length;r<n;r++){i=arguments[r];for(var s in i)Object.prototype.hasOwnProperty.call(i,s)&&(e[s]=i[s])}return e},pa.apply(this,arguments)};function z0(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(t);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(i[r[n]]=t[r[n]]);return i}function V0(t,e,i,r){var n=arguments.length,s=n<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,i):r,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,i,r);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,i,s):o(e,i))||s);return n>3&&s&&Object.defineProperty(e,i,s),s}function H0(t,e){return function(i,r){e(i,r,t)}}function K0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function W0(t,e,i,r){function n(s){return s instanceof i?s:new i(function(o){o(s)})}return new(i||(i=Promise))(function(s,o){function a(u){try{l(r.next(u))}catch(h){o(h)}}function c(u){try{l(r.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((r=r.apply(t,e||[])).next())})}function G0(t,e){var i={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},r,n,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(l){return function(u){return c([l,u])}}function c(l){if(r)throw new TypeError("Generator is already executing.");for(;i;)try{if(r=1,n&&(s=l[0]&2?n.return:l[0]?n.throw||((s=n.return)&&s.call(n),0):n.next)&&!(s=s.call(n,l[1])).done)return s;switch(n=0,s&&(l=[l[0]&2,s.value]),l[0]){case 0:case 1:s=l;break;case 4:return i.label++,{value:l[1],done:!1};case 5:i.label++,n=l[1],l=[0];continue;case 7:l=i.ops.pop(),i.trys.pop();continue;default:if(s=i.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){i=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){i.label=l[1];break}if(l[0]===6&&i.label<s[1]){i.label=s[1],s=l;break}if(s&&i.label<s[2]){i.label=s[2],i.ops.push(l);break}s[2]&&i.ops.pop(),i.trys.pop();continue}l=e.call(t,i)}catch(u){l=[6,u],n=0}finally{r=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function Y0(t,e,i,r){r===void 0&&(r=i),t[r]=e[i]}function Z0(t,e){for(var i in t)i!=="default"&&!e.hasOwnProperty(i)&&(e[i]=t[i])}function ga(t){var e=typeof Symbol=="function"&&Symbol.iterator,i=e&&t[e],r=0;if(i)return i.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Bf(t,e){var i=typeof Symbol=="function"&&t[Symbol.iterator];if(!i)return t;var r=i.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=r.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(i=r.return)&&i.call(r)}finally{if(o)throw o.error}}return s}function J0(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Bf(arguments[e]));return t}function X0(){for(var t=0,e=0,i=arguments.length;e<i;e++)t+=arguments[e].length;for(var r=Array(t),n=0,e=0;e<i;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)r[n]=s[o];return r}function wn(t){return this instanceof wn?(this.v=t,this):new wn(t)}function Q0(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){r[f]&&(n[f]=function(d){return new Promise(function(p,g){s.push([f,d,p,g])>1||a(f,d)})})}function a(f,d){try{c(r[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof wn?Promise.resolve(f.value.v).then(l,u):h(s[0][2],f)}function l(f){a("next",f)}function u(f){a("throw",f)}function h(f,d){f(d),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ey(t){var e,i;return e={},r("next"),r("throw",function(n){throw n}),r("return"),e[Symbol.iterator]=function(){return this},e;function r(n,s){e[n]=t[n]?function(o){return(i=!i)?{value:wn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function ty(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],i;return e?e.call(t):(t=typeof ga=="function"?ga(t):t[Symbol.iterator](),i={},r("next"),r("throw"),r("return"),i[Symbol.asyncIterator]=function(){return this},i);function r(s){i[s]=t[s]&&function(o){return new Promise(function(a,c){o=t[s](o),n(a,c,o.done,o.value)})}}function n(s,o,a,c){Promise.resolve(c).then(function(l){s({value:l,done:a})},o)}}function iy(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function ry(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var i in t)Object.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e.default=t,e}function ny(t){return t&&t.__esModule?t:{default:t}}function sy(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function oy(t,e,i){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,i),i}const ay=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return pa},__asyncDelegator:ey,__asyncGenerator:Q0,__asyncValues:ty,__await:wn,__awaiter:W0,__classPrivateFieldGet:sy,__classPrivateFieldSet:oy,__createBinding:Y0,__decorate:V0,__exportStar:Z0,__extends:q0,__generator:G0,__importDefault:ny,__importStar:ry,__makeTemplateObject:iy,__metadata:K0,__param:H0,__read:Bf,__rest:z0,__spread:J0,__spreadArrays:X0,__values:ga},Symbol.toStringTag,{value:"Module"})),$n=$0(ay);var fo={},zr={},pl;function cy(){if(pl)return zr;pl=1,Object.defineProperty(zr,"__esModule",{value:!0}),zr.delay=void 0;function t(e){return new Promise(i=>{setTimeout(()=>{i(!0)},e)})}return zr.delay=t,zr}var Li={},po={},Mi={},gl;function ly(){return gl||(gl=1,Object.defineProperty(Mi,"__esModule",{value:!0}),Mi.ONE_THOUSAND=Mi.ONE_HUNDRED=void 0,Mi.ONE_HUNDRED=100,Mi.ONE_THOUSAND=1e3),Mi}var go={},yl;function uy(){return yl||(yl=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}(go)),go}var wl;function Tf(){return wl||(wl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(ly(),t),e.__exportStar(uy(),t)}(po)),po}var ml;function hy(){if(ml)return Li;ml=1,Object.defineProperty(Li,"__esModule",{value:!0}),Li.fromMiliseconds=Li.toMiliseconds=void 0;const t=Tf();function e(r){return r*t.ONE_THOUSAND}Li.toMiliseconds=e;function i(r){return Math.floor(r/t.ONE_THOUSAND)}return Li.fromMiliseconds=i,Li}var bl;function fy(){return bl||(bl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(cy(),t),e.__exportStar(hy(),t)}(fo)),fo}var gr={},vl;function dy(){if(vl)return gr;vl=1,Object.defineProperty(gr,"__esModule",{value:!0}),gr.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(i){if(this.timestamps.has(i))throw new Error(`Watch already started for label: ${i}`);this.timestamps.set(i,{started:Date.now()})}stop(i){const r=this.get(i);if(typeof r.elapsed<"u")throw new Error(`Watch already stopped for label: ${i}`);const n=Date.now()-r.started;this.timestamps.set(i,{started:r.started,elapsed:n})}get(i){const r=this.timestamps.get(i);if(typeof r>"u")throw new Error(`No timestamp found for label: ${i}`);return r}elapsed(i){const r=this.get(i);return r.elapsed||Date.now()-r.started}}return gr.Watch=t,gr.default=t,gr}var yo={},Vr={},El;function py(){if(El)return Vr;El=1,Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.IWatch=void 0;class t{}return Vr.IWatch=t,Vr}var xl;function gy(){return xl||(xl=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),$n.__exportStar(py(),t)}(yo)),yo}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(fy(),t),e.__exportStar(dy(),t),e.__exportStar(gy(),t),e.__exportStar(Tf(),t)})(L);var ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=Rf=ue.getLocation=ue.getLocationOrThrow=uc=ue.getNavigator=ue.getNavigatorOrThrow=rr=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function cr(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=cr;function jr(t){const e=cr(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=jr;function yy(){return jr("document")}ue.getDocumentOrThrow=yy;function wy(){return cr("document")}var rr=ue.getDocument=wy;function my(){return jr("navigator")}ue.getNavigatorOrThrow=my;function by(){return cr("navigator")}var uc=ue.getNavigator=by;function vy(){return jr("location")}ue.getLocationOrThrow=vy;function Ey(){return cr("location")}var Rf=ue.getLocation=Ey;function xy(){return jr("crypto")}ue.getCryptoOrThrow=xy;function Iy(){return cr("crypto")}ue.getCrypto=Iy;function _y(){return jr("localStorage")}ue.getLocalStorageOrThrow=_y;function Sy(){return cr("localStorage")}ue.getLocalStorage=Sy;var hc={};Object.defineProperty(hc,"__esModule",{value:!0});var Ff=hc.getWindowMetadata=void 0;const Il=ue;function $y(){let t,e;try{t=Il.getDocumentOrThrow(),e=Il.getLocationOrThrow()}catch{return null}function i(){const h=t.getElementsByTagName("link"),f=[];for(let d=0;d<h.length;d++){const p=h[d],g=p.getAttribute("rel");if(g&&g.toLowerCase().indexOf("icon")>-1){const w=p.getAttribute("href");if(w)if(w.toLowerCase().indexOf("https:")===-1&&w.toLowerCase().indexOf("http:")===-1&&w.indexOf("//")!==0){let _=e.protocol+"//"+e.host;if(w.indexOf("/")===0)_+=w;else{const C=e.pathname.split("/");C.pop();const b=C.join("/");_+=b+"/"+w}f.push(_)}else if(w.indexOf("//")===0){const _=e.protocol+w;f.push(_)}else f.push(w)}}return f}function r(...h){const f=t.getElementsByTagName("meta");for(let d=0;d<f.length;d++){const p=f[d],g=["itemprop","property","name"].map(w=>p.getAttribute(w)).filter(w=>w?h.includes(w):!1);if(g.length&&g){const w=p.getAttribute("content");if(w)return w}}return""}function n(){let h=r("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return r("description","og:description","twitter:description","keywords")}const o=n(),a=s(),c=e.origin,l=i();return{description:a,url:c,icons:l,name:o}}Ff=hc.getWindowMetadata=$y;const Dy="0.1.1";function Oy(){return Dy}class de extends Error{constructor(e,i={}){const r=(()=>{var c;if(i.cause instanceof de){if(i.cause.details)return i.cause.details;if(i.cause.shortMessage)return i.cause.shortMessage}return i.cause&&"details"in i.cause&&typeof i.cause.details=="string"?i.cause.details:(c=i.cause)!=null&&c.message?i.cause.message:i.details})(),n=(()=>i.cause instanceof de&&i.cause.docsPath||i.docsPath)(),o=`https://oxlib.sh${n??""}`,a=[e||"An error occurred.",...i.metaMessages?["",...i.metaMessages]:[],...r||n?["",r?`Details: ${r}`:void 0,n?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
15
|
+
`);super(a,i.cause?{cause:i.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@${Oy()}`}),this.cause=i.cause,this.details=r,this.docs=o,this.docsPath=n,this.shortMessage=e}walk(e){return Nf(this,e)}}function Nf(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?Nf(t.cause,e):e?null:t}const yr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ay(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function mn(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function nr(t,...e){if(!Ay(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 Py(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");mn(t.outputLen),mn(t.blockLen)}function Fr(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Uf(t,e){nr(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function Cy(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Nr(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function wo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Rt(t,e){return t<<32-e|t>>>e}const By=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function Ty(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function Ry(t){for(let e=0;e<t.length;e++)t[e]=Ty(t[e]);return t}const _l=By?t=>t:Ry;function Fy(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ms(t){return typeof t=="string"&&(t=Fy(t)),nr(t),t}function Ny(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];nr(n),e+=n.length}const i=new Uint8Array(e);for(let r=0,n=0;r<t.length;r++){const s=t[r];i.set(s,n),n+=s.length}return i}class fc{}function kf(t){const e=r=>t().update(Ms(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function Uy(t=32){if(yr&&typeof yr.getRandomValues=="function")return yr.getRandomValues(new Uint8Array(t));if(yr&&typeof yr.randomBytes=="function")return Uint8Array.from(yr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function ky(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const n=BigInt(32),s=BigInt(4294967295),o=Number(i>>n&s),a=Number(i&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function jy(t,e,i){return t&e^~t&i}function Ly(t,e,i){return t&e^t&i^e&i}class My extends fc{constructor(e,i,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=wo(this.buffer)}update(e){Fr(this),e=Ms(e),nr(e);const{view:i,buffer:r,blockLen:n}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=wo(e);for(;n<=s-o;o+=n)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fr(this),Uf(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:n,isLE:s}=this;let{pos:o}=this;i[o++]=128,Nr(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let h=o;h<n;h++)i[h]=0;ky(r,n-8,BigInt(this.length*8),s),this.process(r,0);const a=wo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],s)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%i&&e.buffer.set(r),e}clone(){return this._cloneInto()}}const pi=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jn=BigInt(2**32-1),Sl=BigInt(32);function qy(t,e=!1){return e?{h:Number(t&jn),l:Number(t>>Sl&jn)}:{h:Number(t>>Sl&jn)|0,l:Number(t&jn)|0}}function zy(t,e=!1){const i=t.length;let r=new Uint32Array(i),n=new Uint32Array(i);for(let s=0;s<i;s++){const{h:o,l:a}=qy(t[s],e);[r[s],n[s]]=[o,a]}return[r,n]}const Vy=(t,e,i)=>t<<i|e>>>32-i,Hy=(t,e,i)=>e<<i|t>>>32-i,Ky=(t,e,i)=>e<<i-32|t>>>64-i,Wy=(t,e,i)=>t<<i-32|e>>>64-i,Gy=BigInt(0),Hr=BigInt(1),Yy=BigInt(2),Zy=BigInt(7),Jy=BigInt(256),Xy=BigInt(113),jf=[],Lf=[],Mf=[];for(let t=0,e=Hr,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],jf.push(2*(5*r+i)),Lf.push((t+1)*(t+2)/2%64);let n=Gy;for(let s=0;s<7;s++)e=(e<<Hr^(e>>Zy)*Xy)%Jy,e&Yy&&(n^=Hr<<(Hr<<BigInt(s))-Hr);Mf.push(n)}const qf=zy(Mf,!0),Qy=qf[0],ew=qf[1],$l=(t,e,i)=>i>32?Ky(t,e,i):Vy(t,e,i),Dl=(t,e,i)=>i>32?Wy(t,e,i):Hy(t,e,i);function tw(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=i[c],u=i[c+1],h=$l(l,u,1)^i[a],f=Dl(l,u,1)^i[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let n=t[2],s=t[3];for(let o=0;o<24;o++){const a=Lf[o],c=$l(n,s,a),l=Dl(n,s,a),u=jf[o];n=t[u],s=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=Qy[r],t[1]^=ew[r]}Nr(i)}class dc extends fc{constructor(e,i,r,n=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=i,this.outputLen=r,this.enableXOF=n,this.rounds=s,mn(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Cy(this.state)}clone(){return this._cloneInto()}keccak(){_l(this.state32),tw(this.state32,this.rounds),_l(this.state32),this.posOut=0,this.pos=0}update(e){Fr(this),e=Ms(e),nr(e);const{blockLen:i,state:r}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(i-this.pos,n-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:n}=this;e[r]^=i,i&128&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Fr(this,!1),nr(e),this.finish();const i=this.state,{blockLen:r}=this;for(let n=0,s=e.length;n<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-n);e.set(i.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=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 mn(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(Uf(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,Nr(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new dc(i,r,n,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const iw=(t,e,i)=>kf(()=>new dc(e,t,i)),rw=(()=>iw(1,136,256/8))(),nw=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]),gi=new Uint32Array(64);class sw extends My{constructor(e=32){super(64,e,8,!1),this.A=pi[0]|0,this.B=pi[1]|0,this.C=pi[2]|0,this.D=pi[3]|0,this.E=pi[4]|0,this.F=pi[5]|0,this.G=pi[6]|0,this.H=pi[7]|0}get(){const{A:e,B:i,C:r,D:n,E:s,F:o,G:a,H:c}=this;return[e,i,r,n,s,o,a,c]}set(e,i,r,n,s,o,a,c){this.A=e|0,this.B=i|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,i){for(let h=0;h<16;h++,i+=4)gi[h]=e.getUint32(i,!1);for(let h=16;h<64;h++){const f=gi[h-15],d=gi[h-2],p=Rt(f,7)^Rt(f,18)^f>>>3,g=Rt(d,17)^Rt(d,19)^d>>>10;gi[h]=g+gi[h-7]+p+gi[h-16]|0}let{A:r,B:n,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=Rt(a,6)^Rt(a,11)^Rt(a,25),d=u+f+jy(a,c,l)+nw[h]+gi[h]|0,g=(Rt(r,2)^Rt(r,13)^Rt(r,22))+Ly(r,n,s)|0;u=l,l=c,c=a,a=o+d|0,o=s,s=n,n=r,r=d+g|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,n,s,o,a,c,l,u)}roundClean(){Nr(gi)}destroy(){this.set(0,0,0,0,0,0,0,0),Nr(this.buffer)}}const ow=kf(()=>new sw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const pc=BigInt(0),ya=BigInt(1);function Dn(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function gc(t){if(!Dn(t))throw new Error("Uint8Array expected")}function bn(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}function Ln(t){const e=t.toString(16);return e.length&1?"0"+e:e}function zf(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?pc:BigInt("0x"+t)}const Vf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",aw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vn(t){if(gc(t),Vf)return t.toHex();let e="";for(let i=0;i<t.length;i++)e+=aw[t[i]];return e}const Gt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ol(t){if(t>=Gt._0&&t<=Gt._9)return t-Gt._0;if(t>=Gt.A&&t<=Gt.F)return t-(Gt.A-10);if(t>=Gt.a&&t<=Gt.f)return t-(Gt.a-10)}function ms(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Vf)return Uint8Array.fromHex(t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let n=0,s=0;n<i;n++,s+=2){const o=Ol(t.charCodeAt(s)),a=Ol(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[n]=o*16+a}return r}function ir(t){return zf(vn(t))}function Hf(t){return gc(t),zf(vn(Uint8Array.from(t).reverse()))}function On(t,e){return ms(t.toString(16).padStart(e*2,"0"))}function Kf(t,e){return On(t,e).reverse()}function mt(t,e,i){let r;if(typeof e=="string")try{r=ms(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Dn(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=r.length;if(typeof i=="number"&&n!==i)throw new Error(t+" of length "+i+" expected, got "+n);return r}function bs(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];gc(n),e+=n.length}const i=new Uint8Array(e);for(let r=0,n=0;r<t.length;r++){const s=t[r];i.set(s,n),n+=s.length}return i}const mo=t=>typeof t=="bigint"&&pc<=t;function yc(t,e,i){return mo(t)&&mo(e)&&mo(i)&&e<=t&&t<i}function Ar(t,e,i,r){if(!yc(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function cw(t){let e;for(e=0;t>pc;t>>=ya,e+=1);return e}const qs=t=>(ya<<BigInt(t))-ya,bo=t=>new Uint8Array(t),Al=t=>Uint8Array.from(t);function lw(t,e,i){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 i!="function")throw new Error("hmacFn must be a function");let r=bo(t),n=bo(t),s=0;const o=()=>{r.fill(1),n.fill(0),s=0},a=(...h)=>i(n,r,...h),c=(h=bo(0))=>{n=a(Al([0]),h),r=a(),h.length!==0&&(n=a(Al([1]),h),r=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){r=a();const d=r.slice();f.push(d),h+=r.length}return bs(...f)};return(h,f)=>{o(),c(h);let d;for(;!(d=f(l()));)c();return o(),d}}const uw={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"||Dn(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 zs(t,e,i={}){const r=(n,s,o)=>{const a=uw[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[n];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(n)+" is invalid. Expected "+s+", got "+c)};for(const[n,s]of Object.entries(e))r(n,s,!1);for(const[n,s]of Object.entries(i))r(n,s,!0);return t}function Pl(t){const e=new WeakMap;return(i,...r)=>{const n=e.get(i);if(n!==void 0)return n;const s=t(i,...r);return e.set(i,s),s}}function hw(t,e){if(Rl(t)>e)throw new Bw({givenSize:Rl(t),maxSize:e})}const Yt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Cl(t){if(t>=Yt.zero&&t<=Yt.nine)return t-Yt.zero;if(t>=Yt.A&&t<=Yt.F)return t-(Yt.A-10);if(t>=Yt.a&&t<=Yt.f)return t-(Yt.a-10)}function fw(t,e={}){const{dir:i,size:r=32}=e;if(r===0)return t;if(t.length>r)throw new Tw({size:t.length,targetSize:r,type:"Bytes"});const n=new Uint8Array(r);for(let s=0;s<r;s++){const o=i==="right";n[o?s:r-s-1]=t[o?s:t.length-s-1]}return n}function Wf(t,e){if(Ni(t)>e)throw new xw({givenSize:Ni(t),maxSize:e})}function dw(t,e){if(typeof e=="number"&&e>0&&e>Ni(t)-1)throw new Zf({offset:e,position:"start",size:Ni(t)})}function pw(t,e,i){if(typeof e=="number"&&typeof i=="number"&&Ni(t)!==i-e)throw new Zf({offset:i,position:"end",size:Ni(t)})}function Gf(t,e={}){const{dir:i,size:r=32}=e;if(r===0)return t;const n=t.replace("0x","");if(n.length>r*2)throw new Iw({size:Math.ceil(n.length/2),targetSize:r,type:"Hex"});return`0x${n[i==="right"?"padEnd":"padStart"](r*2,"0")}`}const gw="#__bigint";function wc(t,e,i){return JSON.stringify(t,(r,n)=>typeof e=="function"?e(r,n):typeof n=="bigint"?n.toString()+gw:n,i)}const yw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function ww(t,e={}){const{strict:i=!1}=e;if(!t)throw new Bl(t);if(typeof t!="string")throw new Bl(t);if(i&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Tl(t);if(!t.startsWith("0x"))throw new Tl(t)}function mw(...t){return`0x${t.reduce((e,i)=>e+i.replace("0x",""),"")}`}function mc(t){return t instanceof Uint8Array?vs(t):Array.isArray(t)?vs(new Uint8Array(t)):t}function vs(t,e={}){let i="";for(let n=0;n<t.length;n++)i+=yw[t[n]];const r=`0x${i}`;return typeof e.size=="number"?(Wf(r,e.size),Yf(r,e.size)):r}function vo(t,e={}){const{signed:i,size:r}=e,n=BigInt(t);let s;r?i?s=(1n<<BigInt(r)*8n-1n)-1n:s=2n**(BigInt(r)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&i?-s-1n:0;if(s&&n>s||n<o){const l=typeof t=="bigint"?"n":"";throw new Ew({max:s?`${s}${l}`:void 0,min:`${o}${l}`,signed:i,size:r,value:`${t}${l}`})}const c=`0x${(i&&n<0?(1n<<BigInt(r*8))+BigInt(n):n).toString(16)}`;return r?bw(c,r):c}function bw(t,e){return Gf(t,{dir:"left",size:e})}function Yf(t,e){return Gf(t,{dir:"right",size:e})}function ri(t,e,i,r={}){const{strict:n}=r;dw(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(i??t.length)*2)}`;return n&&pw(s,e,i),s}function Ni(t){return Math.ceil((t.length-2)/2)}function vw(t,e={}){const{strict:i=!1}=e;try{return ww(t,{strict:i}),!0}catch{return!1}}class Ew extends de{constructor({max:e,min:i,signed:r,size:n,value:s}){super(`Number \`${s}\` is not in safe${n?` ${n*8}-bit`:""}${r?" signed":" unsigned"} integer range ${e?`(\`${i}\` to \`${e}\`)`:`(above \`${i}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Bl extends de{constructor(e){super(`Value \`${typeof e=="object"?wc(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 Tl extends de{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 xw=class extends de{constructor({givenSize:e,maxSize:i}){super(`Size cannot exceed \`${i}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class Zf extends de{constructor({offset:e,position:i,size:r}){super(`Slice ${i==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let Iw=class extends de{constructor({size:e,targetSize:i,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const _w=new TextEncoder;function Sw(t){if(!(t instanceof Uint8Array)){if(!t)throw new Mn(t);if(typeof t!="object")throw new Mn(t);if(!("BYTES_PER_ELEMENT"in t))throw new Mn(t);if(t.BYTES_PER_ELEMENT!==1||t.constructor.name!=="Uint8Array")throw new Mn(t)}}function $w(t){return t instanceof Uint8Array?t:typeof t=="string"?Ow(t):Dw(t)}function Dw(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Ow(t,e={}){const{size:i}=e;let r=t;i&&(Wf(t,i),r=Yf(t,i));let n=r.slice(2);n.length%2&&(n=`0${n}`);const s=n.length/2,o=new Uint8Array(s);for(let a=0,c=0;a<s;a++){const l=Cl(n.charCodeAt(c++)),u=Cl(n.charCodeAt(c++));if(l===void 0||u===void 0)throw new de(`Invalid byte sequence ("${n[c-2]}${n[c-1]}" in "${n}").`);o[a]=l*16+u}return o}function Aw(t,e={}){const{size:i}=e,r=_w.encode(t);return typeof i=="number"?(hw(r,i),Pw(r,i)):r}function Pw(t,e){return fw(t,{dir:"right",size:e})}function Rl(t){return t.length}function Cw(t){try{return Sw(t),!0}catch{return!1}}class Mn extends de{constructor(e){super(`Value \`${typeof e=="object"?wc(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 Bw extends de{constructor({givenSize:e,maxSize:i}){super(`Size cannot exceed \`${i}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class Tw extends de{constructor({size:e,targetSize:i,type:r}){super(`${r.charAt(0).toUpperCase()}${r.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function Jf(t,e={}){const{as:i=typeof t=="string"?"Hex":"Bytes"}=e,r=rw($w(t));return i==="Bytes"?r:vs(r)}class Rw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const i=super.get(e);return super.has(e)&&i!==void 0&&(this.delete(e),super.set(e,i)),i}set(e,i){if(super.set(e,i),this.maxSize&&this.size>this.maxSize){const r=this.keys().next().value;r&&this.delete(r)}return this}}const Fw={checksum:new Rw(8192)},Eo=Fw.checksum;function Xf(t,e={}){const{compressed:i}=e,{prefix:r,x:n,y:s}=t;if(i===!1||typeof n=="bigint"&&typeof s=="bigint"){if(r!==4)throw new Fl({prefix:r,cause:new Mw});return}if(i===!0||typeof n=="bigint"&&typeof s>"u"){if(r!==3&&r!==2)throw new Fl({prefix:r,cause:new Lw});return}throw new jw({publicKey:t})}function Nw(t){const e=(()=>{if(vw(t))return Qf(t);if(Cw(t))return Uw(t);const{prefix:i,x:r,y:n}=t;return typeof r=="bigint"&&typeof n=="bigint"?{prefix:i??4,x:r,y:n}:{prefix:i,x:r}})();return Xf(e),e}function Uw(t){return Qf(vs(t))}function Qf(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new qw({publicKey:t});if(t.length===130){const r=BigInt(ri(t,0,32)),n=BigInt(ri(t,32,64));return{prefix:4,x:r,y:n}}if(t.length===132){const r=Number(ri(t,0,1)),n=BigInt(ri(t,1,33)),s=BigInt(ri(t,33,65));return{prefix:r,x:n,y:s}}const e=Number(ri(t,0,1)),i=BigInt(ri(t,1,33));return{prefix:e,x:i}}function kw(t,e={}){Xf(t);const{prefix:i,x:r,y:n}=t,{includePrefix:s=!0}=e;return mw(s?vo(i,{size:1}):"0x",vo(r,{size:32}),typeof n=="bigint"?vo(n,{size:32}):"0x")}class jw extends de{constructor({publicKey:e}){super(`Value \`${wc(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 Fl extends de{constructor({prefix:e,cause:i}){super(`Prefix "${e}" is invalid.`,{cause:i}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Lw extends de{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 Mw extends de{constructor(){super("Prefix must be 4 for uncompressed public keys."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidUncompressedPrefixError"})}}let qw=class extends de{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 ${Ni(mc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const zw=/^0x[a-fA-F0-9]{40}$/;function ed(t,e={}){const{strict:i=!0}=e;if(!zw.test(t))throw new Nl({address:t,cause:new Kw});if(i){if(t.toLowerCase()===t)return;if(td(t)!==t)throw new Nl({address:t,cause:new Ww})}}function td(t){if(Eo.has(t))return Eo.get(t);ed(t,{strict:!1});const e=t.substring(2).toLowerCase(),i=Jf(Aw(e),{as:"Bytes"}),r=e.split("");for(let s=0;s<40;s+=2)i[s>>1]>>4>=8&&r[s]&&(r[s]=r[s].toUpperCase()),(i[s>>1]&15)>=8&&r[s+1]&&(r[s+1]=r[s+1].toUpperCase());const n=`0x${r.join("")}`;return Eo.set(t,n),n}function Vw(t,e={}){const{checksum:i=!1}=e;return ed(t),i?td(t):t}function Hw(t,e={}){const i=Jf(`0x${kw(t).slice(4)}`).substring(26);return Vw(`0x${i}`,e)}class Nl extends de{constructor({address:e,cause:i}){super(`Address "${e}" is invalid.`,{cause:i}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Kw extends de{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 Ww extends de{constructor(){super("Address does not match its checksum counterpart."),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidChecksumError"})}}class id extends fc{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,Py(e);const r=Ms(i);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 n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),Nr(s)}update(e){return Fr(this),this.iHash.update(e),this}digestInto(e){Fr(this),nr(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:i,iHash:r,finished:n,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=i._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const rd=(t,e,i)=>new id(t,e).update(i).digest();rd.create=(t,e)=>new id(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const it=BigInt(0),Ke=BigInt(1),Ji=BigInt(2),Gw=BigInt(3),nd=BigInt(4),sd=BigInt(5),od=BigInt(8);function Qe(t,e){const i=t%e;return i>=it?i:e+i}function pt(t,e,i){let r=t;for(;e-- >it;)r*=r,r%=i;return r}function wa(t,e){if(t===it)throw new Error("invert: expected non-zero number");if(e<=it)throw new Error("invert: expected positive modulus, got "+e);let i=Qe(t,e),r=e,n=it,s=Ke;for(;i!==it;){const a=r/i,c=r%i,l=n-s*a;r=i,i=c,n=s,s=l}if(r!==Ke)throw new Error("invert: does not exist");return Qe(n,e)}function ad(t,e){const i=(t.ORDER+Ke)/nd,r=t.pow(e,i);if(!t.eql(t.sqr(r),e))throw new Error("Cannot find square root");return r}function Yw(t,e){const i=(t.ORDER-sd)/od,r=t.mul(e,Ji),n=t.pow(r,i),s=t.mul(e,n),o=t.mul(t.mul(s,Ji),n),a=t.mul(s,t.sub(o,t.ONE));if(!t.eql(t.sqr(a),e))throw new Error("Cannot find square root");return a}function Zw(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ke,i=0;for(;e%Ji===it;)e/=Ji,i++;let r=Ji;const n=bc(t);for(;Ul(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(i===1)return ad;let s=n.pow(r,e);const o=(e+Ke)/Ji;return function(c,l){if(c.is0(l))return l;if(Ul(c,l)!==1)throw new Error("Cannot find square root");let u=i,h=c.mul(c.ONE,s),f=c.pow(l,e),d=c.pow(l,o);for(;!c.eql(f,c.ONE);){if(c.is0(f))return c.ZERO;let p=1,g=c.sqr(f);for(;!c.eql(g,c.ONE);)if(p++,g=c.sqr(g),p===u)throw new Error("Cannot find square root");const w=Ke<<BigInt(u-p-1),_=c.pow(h,w);u=p,h=c.sqr(_),f=c.mul(f,h),d=c.mul(d,_)}return d}}function Jw(t){return t%nd===Gw?ad:t%od===sd?Yw:Zw(t)}const Xw=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Qw(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},i=Xw.reduce((r,n)=>(r[n]="function",r),e);return zs(t,i)}function em(t,e,i){if(i<it)throw new Error("invalid exponent, negatives unsupported");if(i===it)return t.ONE;if(i===Ke)return e;let r=t.ONE,n=e;for(;i>it;)i&Ke&&(r=t.mul(r,n)),n=t.sqr(n),i>>=Ke;return r}function cd(t,e,i=!1){const r=new Array(e.length).fill(i?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Ul(t,e){const i=(t.ORDER-Ke)/Ji,r=t.pow(e,i),n=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function ld(t,e){e!==void 0&&mn(e);const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function bc(t,e,i=!1,r={}){if(t<=it)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=ld(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:i,BITS:n,BYTES:s,MASK:qs(n),ZERO:it,ONE:Ke,create:c=>Qe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return it<=c&&c<t},is0:c=>c===it,isOdd:c=>(c&Ke)===Ke,neg:c=>Qe(-c,t),eql:(c,l)=>c===l,sqr:c=>Qe(c*c,t),add:(c,l)=>Qe(c+l,t),sub:(c,l)=>Qe(c-l,t),mul:(c,l)=>Qe(c*l,t),pow:(c,l)=>em(a,c,l),div:(c,l)=>Qe(c*wa(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>wa(c,t),sqrt:r.sqrt||(c=>(o||(o=Jw(t)),o(a,c))),toBytes:c=>i?Kf(c,s):On(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return i?Hf(c):ir(c)},invertBatch:c=>cd(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function ud(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 hd(t){const e=ud(t);return e+Math.ceil(e/2)}function tm(t,e,i=!1){const r=t.length,n=ud(e),s=hd(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=i?Hf(t):ir(t),a=Qe(o,e-Ke)+Ke;return i?Kf(a,n):On(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const kl=BigInt(0),ma=BigInt(1);function xo(t,e){const i=e.negate();return t?i:e}function fd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Io(t,e){fd(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1),n=2**t,s=qs(t),o=BigInt(t);return{windows:i,windowSize:r,mask:s,maxNumber:n,shiftBy:o}}function jl(t,e,i){const{windowSize:r,mask:n,maxNumber:s,shiftBy:o}=i;let a=Number(t&n),c=t>>o;a>r&&(a-=s,c+=ma);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:l}}function im(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function rm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const _o=new WeakMap,dd=new WeakMap;function So(t){return dd.get(t)||1}function nm(t,e){return{constTimeNegate:xo,hasPrecomputes(i){return So(i)!==1},unsafeLadder(i,r,n=t.ZERO){let s=i;for(;r>kl;)r&ma&&(n=n.add(s)),s=s.double(),r>>=ma;return n},precomputeWindow(i,r){const{windows:n,windowSize:s}=Io(r,e),o=[];let a=i,c=a;for(let l=0;l<n;l++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(i,r,n){let s=t.ZERO,o=t.BASE;const a=Io(i,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:p}=jl(n,c,a);n=l,h?o=o.add(xo(d,r[p])):s=s.add(xo(f,r[u]))}return{p:s,f:o}},wNAFUnsafe(i,r,n,s=t.ZERO){const o=Io(i,e);for(let a=0;a<o.windows&&n!==kl;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=jl(n,a,o);if(n=c,!u){const f=r[l];s=s.add(h?f.negate():f)}}return s},getPrecomputes(i,r,n){let s=_o.get(r);return s||(s=this.precomputeWindow(r,i),i!==1&&_o.set(r,n(s))),s},wNAFCached(i,r,n){const s=So(i);return this.wNAF(s,this.getPrecomputes(s,i,n),r)},wNAFCachedUnsafe(i,r,n,s){const o=So(i);return o===1?this.unsafeLadder(i,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,i,n),r,s)},setWindowSize(i,r){fd(r,e),dd.set(i,r),_o.delete(i)}}}function sm(t,e,i,r){im(i,t),rm(r,e);const n=i.length,s=r.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=cw(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=qs(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){u.fill(o);for(let g=0;g<s;g++){const w=r[g],_=Number(w>>BigInt(d)&l);u[_]=u[_].add(i[g])}let p=o;for(let g=u.length-1,w=o;g>0;g--)w=w.add(u[g]),p=p.add(w);if(f=f.add(p),d!==0)for(let g=0;g<c;g++)f=f.double()}return f}function pd(t){return Qw(t.Fp),zs(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...ld(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ll(t){t.lowS!==void 0&&bn("lowS",t.lowS),t.prehash!==void 0&&bn("prehash",t.prehash)}function om(t){const e=pd(t);zs(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:i,Fp:r,a:n}=e;if(i){if(!r.eql(n,r.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof i!="object"||typeof i.beta!="bigint"||typeof i.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class am extends Error{constructor(e=""){super(e)}}const ni={Err:am,_tlv:{encode:(t,e)=>{const{Err:i}=ni;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length&1)throw new i("tlv.encode: unpadded data");const r=e.length/2,n=Ln(r);if(n.length/2&128)throw new i("tlv.encode: long form length too big");const s=r>127?Ln(n.length/2|128):"";return Ln(t)+s+n+e},decode(t,e){const{Err:i}=ni;let r=0;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new i("tlv.decode: wrong tlv");const n=e[r++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new i("tlv.decode(long): indefinite length not supported");if(c>4)throw new i("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new i("tlv.decode: length bytes not complete");if(l[0]===0)throw new i("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new i("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new i("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=ni;if(t<oi)throw new e("integer: negative integers are not allowed");let i=Ln(t);if(Number.parseInt(i[0],16)&8&&(i="00"+i),i.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return i},decode(t){const{Err:e}=ni;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 ir(t)}},toSig(t){const{Err:e,_int:i,_tlv:r}=ni,n=mt("signature",t),{v:s,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(l)}},hexFromSig(t){const{_tlv:e,_int:i}=ni,r=e.encode(2,i.encode(t.r)),n=e.encode(2,i.encode(t.s)),s=r+n;return e.encode(48,s)}};function $o(t,e){return vn(On(t,e))}const oi=BigInt(0),Oe=BigInt(1);BigInt(2);const Do=BigInt(3),cm=BigInt(4);function lm(t){const e=om(t),{Fp:i}=e,r=bc(e.n,e.nBitLength),n=e.toBytes||((b,v,O)=>{const P=v.toAffine();return bs(Uint8Array.from([4]),i.toBytes(P.x),i.toBytes(P.y))}),s=e.fromBytes||(b=>{const v=b.subarray(1),O=i.fromBytes(v.subarray(0,i.BYTES)),P=i.fromBytes(v.subarray(i.BYTES,2*i.BYTES));return{x:O,y:P}});function o(b){const{a:v,b:O}=e,P=i.sqr(b),T=i.mul(P,b);return i.add(i.add(T,i.mul(b,v)),O)}function a(b,v){const O=i.sqr(v),P=o(b);return i.eql(O,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=i.mul(i.pow(e.a,Do),cm),l=i.mul(i.sqr(e.b),BigInt(27));if(i.is0(i.add(c,l)))throw new Error("bad curve params: a or b");function u(b){return yc(b,Oe,e.n)}function h(b){const{allowedPrivateKeyLengths:v,nByteLength:O,wrapPrivateKey:P,n:T}=e;if(v&&typeof b!="bigint"){if(Dn(b)&&(b=vn(b)),typeof b!="string"||!v.includes(b.length))throw new Error("invalid private key");b=b.padStart(O*2,"0")}let R;try{R=typeof b=="bigint"?b:ir(mt("private key",b,O))}catch{throw new Error("invalid private key, expected hex or "+O+" bytes, got "+typeof b)}return P&&(R=Qe(R,T)),Ar("private key",R,Oe,T),R}function f(b){if(!(b instanceof g))throw new Error("ProjectivePoint expected")}const d=Pl((b,v)=>{const{px:O,py:P,pz:T}=b;if(i.eql(T,i.ONE))return{x:O,y:P};const R=b.is0();v==null&&(v=R?i.ONE:i.inv(T));const A=i.mul(O,v),U=i.mul(P,v),j=i.mul(T,v);if(R)return{x:i.ZERO,y:i.ZERO};if(!i.eql(j,i.ONE))throw new Error("invZ was invalid");return{x:A,y:U}}),p=Pl(b=>{if(b.is0()){if(e.allowInfinityPoint&&!i.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:v,y:O}=b.toAffine();if(!i.isValid(v)||!i.isValid(O))throw new Error("bad point: x or y not FE");if(!a(v,O))throw new Error("bad point: equation left != right");if(!b.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});class g{constructor(v,O,P){if(v==null||!i.isValid(v))throw new Error("x required");if(O==null||!i.isValid(O)||i.is0(O))throw new Error("y required");if(P==null||!i.isValid(P))throw new Error("z required");this.px=v,this.py=O,this.pz=P,Object.freeze(this)}static fromAffine(v){const{x:O,y:P}=v||{};if(!v||!i.isValid(O)||!i.isValid(P))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const T=R=>i.eql(R,i.ZERO);return T(O)&&T(P)?g.ZERO:new g(O,P,i.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const O=cd(i,v.map(P=>P.pz));return v.map((P,T)=>P.toAffine(O[T])).map(g.fromAffine)}static fromHex(v){const O=g.fromAffine(s(mt("pointHex",v)));return O.assertValidity(),O}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,O){return sm(g,r,v,O)}_setWindowSize(v){C.setWindowSize(this,v)}assertValidity(){p(this)}hasEvenY(){const{y:v}=this.toAffine();if(i.isOdd)return!i.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:O,py:P,pz:T}=this,{px:R,py:A,pz:U}=v,j=i.eql(i.mul(O,U),i.mul(R,T)),B=i.eql(i.mul(P,U),i.mul(A,T));return j&&B}negate(){return new g(this.px,i.neg(this.py),this.pz)}double(){const{a:v,b:O}=e,P=i.mul(O,Do),{px:T,py:R,pz:A}=this;let U=i.ZERO,j=i.ZERO,B=i.ZERO,I=i.mul(T,T),D=i.mul(R,R),m=i.mul(A,A),y=i.mul(T,R);return y=i.add(y,y),B=i.mul(T,A),B=i.add(B,B),U=i.mul(v,B),j=i.mul(P,m),j=i.add(U,j),U=i.sub(D,j),j=i.add(D,j),j=i.mul(U,j),U=i.mul(y,U),B=i.mul(P,B),m=i.mul(v,m),y=i.sub(I,m),y=i.mul(v,y),y=i.add(y,B),B=i.add(I,I),I=i.add(B,I),I=i.add(I,m),I=i.mul(I,y),j=i.add(j,I),m=i.mul(R,A),m=i.add(m,m),I=i.mul(m,y),U=i.sub(U,I),B=i.mul(m,D),B=i.add(B,B),B=i.add(B,B),new g(U,j,B)}add(v){f(v);const{px:O,py:P,pz:T}=this,{px:R,py:A,pz:U}=v;let j=i.ZERO,B=i.ZERO,I=i.ZERO;const D=e.a,m=i.mul(e.b,Do);let y=i.mul(O,R),x=i.mul(P,A),$=i.mul(T,U),E=i.add(O,P),S=i.add(R,A);E=i.mul(E,S),S=i.add(y,x),E=i.sub(E,S),S=i.add(O,T);let F=i.add(R,U);return S=i.mul(S,F),F=i.add(y,$),S=i.sub(S,F),F=i.add(P,T),j=i.add(A,U),F=i.mul(F,j),j=i.add(x,$),F=i.sub(F,j),I=i.mul(D,S),j=i.mul(m,$),I=i.add(j,I),j=i.sub(x,I),I=i.add(x,I),B=i.mul(j,I),x=i.add(y,y),x=i.add(x,y),$=i.mul(D,$),S=i.mul(m,S),x=i.add(x,$),$=i.sub(y,$),$=i.mul(D,$),S=i.add(S,$),y=i.mul(x,S),B=i.add(B,y),y=i.mul(F,S),j=i.mul(E,j),j=i.sub(j,y),y=i.mul(E,x),I=i.mul(F,I),I=i.add(I,y),new g(j,B,I)}subtract(v){return this.add(v.negate())}is0(){return this.equals(g.ZERO)}wNAF(v){return C.wNAFCached(this,v,g.normalizeZ)}multiplyUnsafe(v){const{endo:O,n:P}=e;Ar("scalar",v,oi,P);const T=g.ZERO;if(v===oi)return T;if(this.is0()||v===Oe)return this;if(!O||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:R,k1:A,k2neg:U,k2:j}=O.splitScalar(v),B=T,I=T,D=this;for(;A>oi||j>oi;)A&Oe&&(B=B.add(D)),j&Oe&&(I=I.add(D)),D=D.double(),A>>=Oe,j>>=Oe;return R&&(B=B.negate()),U&&(I=I.negate()),I=new g(i.mul(I.px,O.beta),I.py,I.pz),B.add(I)}multiply(v){const{endo:O,n:P}=e;Ar("scalar",v,Oe,P);let T,R;if(O){const{k1neg:A,k1:U,k2neg:j,k2:B}=O.splitScalar(v);let{p:I,f:D}=this.wNAF(U),{p:m,f:y}=this.wNAF(B);I=C.constTimeNegate(A,I),m=C.constTimeNegate(j,m),m=new g(i.mul(m.px,O.beta),m.py,m.pz),T=I.add(m),R=D.add(y)}else{const{p:A,f:U}=this.wNAF(v);T=A,R=U}return g.normalizeZ([T,R])[0]}multiplyAndAddUnsafe(v,O,P){const T=g.BASE,R=(U,j)=>j===oi||j===Oe||!U.equals(T)?U.multiplyUnsafe(j):U.multiply(j),A=R(this,O).add(R(v,P));return A.is0()?void 0:A}toAffine(v){return d(this,v)}isTorsionFree(){const{h:v,isTorsionFree:O}=e;if(v===Oe)return!0;if(O)return O(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:O}=e;return v===Oe?this:O?O(g,this):this.multiplyUnsafe(e.h)}toRawBytes(v=!0){return bn("isCompressed",v),this.assertValidity(),n(g,this,v)}toHex(v=!0){return bn("isCompressed",v),vn(this.toRawBytes(v))}}g.BASE=new g(e.Gx,e.Gy,i.ONE),g.ZERO=new g(i.ZERO,i.ONE,i.ZERO);const{endo:w,nBitLength:_}=e,C=nm(g,w?Math.ceil(_/2):_);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function um(t){const e=pd(t);return zs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function hm(t){const e=um(t),{Fp:i,n:r,nByteLength:n,nBitLength:s}=e,o=i.BYTES+1,a=2*i.BYTES+1;function c(m){return Qe(m,r)}function l(m){return wa(m,r)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:d}=lm({...e,toBytes(m,y,x){const $=y.toAffine(),E=i.toBytes($.x),S=bs;return bn("isCompressed",x),x?S(Uint8Array.from([y.hasEvenY()?2:3]),E):S(Uint8Array.from([4]),E,i.toBytes($.y))},fromBytes(m){const y=m.length,x=m[0],$=m.subarray(1);if(y===o&&(x===2||x===3)){const E=ir($);if(!yc(E,Oe,i.ORDER))throw new Error("Point is not on curve");const S=f(E);let F;try{F=i.sqrt(S)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const N=(F&Oe)===Oe;return(x&1)===1!==N&&(F=i.neg(F)),{x:E,y:F}}else if(y===a&&x===4){const E=i.fromBytes($.subarray(0,i.BYTES)),S=i.fromBytes($.subarray(i.BYTES,2*i.BYTES));return{x:E,y:S}}else{const E=o,S=a;throw new Error("invalid Point, expected length of "+E+", or uncompressed "+S+", got "+y)}}});function p(m){const y=r>>Oe;return m>y}function g(m){return p(m)?c(-m):m}const w=(m,y,x)=>ir(m.slice(y,x));class _{constructor(y,x,$){Ar("r",y,Oe,r),Ar("s",x,Oe,r),this.r=y,this.s=x,$!=null&&(this.recovery=$),Object.freeze(this)}static fromCompact(y){const x=n;return y=mt("compactSignature",y,x*2),new _(w(y,0,x),w(y,x,2*x))}static fromDER(y){const{r:x,s:$}=ni.toSig(mt("DER",y));return new _(x,$)}assertValidity(){}addRecoveryBit(y){return new _(this.r,this.s,y)}recoverPublicKey(y){const{r:x,s:$,recovery:E}=this,S=T(mt("msgHash",y));if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");const F=E===2||E===3?x+e.n:x;if(F>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");const N=E&1?"03":"02",H=u.fromHex(N+$o(F,i.BYTES)),z=l(F),q=c(-S*z),K=c($*z),G=u.BASE.multiplyAndAddUnsafe(H,q,K);if(!G)throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return p(this.s)}normalizeS(){return this.hasHighS()?new _(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ms(this.toDERHex())}toDERHex(){return ni.hexFromSig(this)}toCompactRawBytes(){return ms(this.toCompactHex())}toCompactHex(){const y=n;return $o(this.r,y)+$o(this.s,y)}}const C={isValidPrivateKey(m){try{return h(m),!0}catch{return!1}},normPrivateKeyToScalar:h,randomPrivateKey:()=>{const m=hd(e.n);return tm(e.randomBytes(m),e.n)},precompute(m=8,y=u.BASE){return y._setWindowSize(m),y.multiply(BigInt(3)),y}};function b(m,y=!0){return u.fromPrivateKey(m).toRawBytes(y)}function v(m){if(typeof m=="bigint")return!1;if(m instanceof u)return!0;const x=mt("key",m).length,$=i.BYTES,E=$+1,S=2*$+1;if(!(e.allowedPrivateKeyLengths||n===E))return x===E||x===S}function O(m,y,x=!0){if(v(m)===!0)throw new Error("first arg must be private key");if(v(y)===!1)throw new Error("second arg must be public key");return u.fromHex(y).multiply(h(m)).toRawBytes(x)}const P=e.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const y=ir(m),x=m.length*8-s;return x>0?y>>BigInt(x):y},T=e.bits2int_modN||function(m){return c(P(m))},R=qs(s);function A(m){return Ar("num < 2^"+s,m,oi,R),On(m,n)}function U(m,y,x=j){if(["recovered","canonical"].some(W=>W in x))throw new Error("sign() legacy options not supported");const{hash:$,randomBytes:E}=e;let{lowS:S,prehash:F,extraEntropy:N}=x;S==null&&(S=!0),m=mt("msgHash",m),Ll(x),F&&(m=mt("prehashed msgHash",$(m)));const H=T(m),z=h(y),q=[A(z),A(H)];if(N!=null&&N!==!1){const W=N===!0?E(i.BYTES):N;q.push(mt("extraEntropy",W))}const K=bs(...q),G=H;function X(W){const Q=P(W);if(!d(Q))return;const pe=l(Q),ve=u.BASE.multiply(Q).toAffine(),_e=c(ve.x);if(_e===oi)return;const He=c(pe*c(G+_e*z));if(He===oi)return;let Wt=(ve.x===_e?0:2)|Number(ve.y&Oe),di=He;return S&&p(He)&&(di=g(He),Wt^=1),new _(_e,di,Wt)}return{seed:K,k2sig:X}}const j={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function I(m,y,x=j){const{seed:$,k2sig:E}=U(m,y,x),S=e;return lw(S.hash.outputLen,S.nByteLength,S.hmac)($,E)}u.BASE._setWindowSize(8);function D(m,y,x,$=B){var Wt;const E=m;y=mt("msgHash",y),x=mt("publicKey",x);const{lowS:S,prehash:F,format:N}=$;if(Ll($),"strict"in $)throw new Error("options.strict was renamed to lowS");if(N!==void 0&&N!=="compact"&&N!=="der")throw new Error("format must be compact or der");const H=typeof E=="string"||Dn(E),z=!H&&!N&&typeof E=="object"&&E!==null&&typeof E.r=="bigint"&&typeof E.s=="bigint";if(!H&&!z)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");let q,K;try{if(z&&(q=new _(E.r,E.s)),H){try{N!=="compact"&&(q=_.fromDER(E))}catch(di){if(!(di instanceof ni.Err))throw di}!q&&N!=="der"&&(q=_.fromCompact(E))}K=u.fromHex(x)}catch{return!1}if(!q||S&&q.hasHighS())return!1;F&&(y=e.hash(y));const{r:G,s:X}=q,W=T(y),Q=l(X),pe=c(W*Q),ve=c(G*Q),_e=(Wt=u.BASE.multiplyAndAddUnsafe(K,pe,ve))==null?void 0:Wt.toAffine();return _e?c(_e.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:O,sign:I,verify:D,ProjectivePoint:u,Signature:_,utils:C}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function fm(t){return{hash:t,hmac:(e,...i)=>rd(t,e,Ny(...i)),randomBytes:Uy}}function dm(t,e){const i=r=>hm({...t,...fm(r)});return{...i(e),create:i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const gd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Ml=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),pm=BigInt(0),gm=BigInt(1),ba=BigInt(2),ql=(t,e)=>(t+e/ba)/e;function ym(t){const e=gd,i=BigInt(3),r=BigInt(6),n=BigInt(11),s=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=t*t*t%e,u=l*l*t%e,h=pt(u,i,e)*u%e,f=pt(h,i,e)*u%e,d=pt(f,ba,e)*l%e,p=pt(d,n,e)*d%e,g=pt(p,s,e)*p%e,w=pt(g,a,e)*g%e,_=pt(w,c,e)*w%e,C=pt(_,a,e)*g%e,b=pt(C,i,e)*u%e,v=pt(b,o,e)*p%e,O=pt(v,r,e)*l%e,P=pt(O,ba,e);if(!va.eql(va.sqr(P),t))throw new Error("Cannot find square root");return P}const va=bc(gd,void 0,void 0,{sqrt:ym}),wm=dm({a:pm,b:BigInt(7),Fp:va,n:Ml,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Ml,i=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),r=-gm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=i,o=BigInt("0x100000000000000000000000000000000"),a=ql(s*t,e),c=ql(-r*t,e);let l=Qe(t-a*i-c*n,e),u=Qe(-a*r-c*s,e);const h=l>o,f=u>o;if(h&&(l=e-l),f&&(u=e-u),l>o||u>o)throw new Error("splitScalar: Endomorphism failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}}},ow);function mm(t){if(t.length!==130&&t.length!==132)throw new vm({signature:t});const e=BigInt(ri(t,0,32)),i=BigInt(ri(t,32,64)),r=(()=>{const n=+`0x${t.slice(130)}`;if(!Number.isNaN(n))try{return bm(n)}catch{throw new Em({value:n})}})();return typeof r>"u"?{r:e,s:i}:{r:e,s:i,yParity:r}}function bm(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 xm({value:t})}class vm extends de{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Ni(mc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class Em extends de{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 xm extends de{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"})}}function Im(t){return Hw(_m(t))}function _m(t){const{payload:e,signature:i}=t,{r,s:n,yParity:s}=i,a=new wm.Signature(BigInt(r),BigInt(n)).addRecoveryBit(s).recoverPublicKey(mc(e).substring(2));return Nw(a)}function Sm(t){if(t.length>=255)throw new TypeError("Alphabet too long");const e=new Uint8Array(256);for(let l=0;l<e.length;l++)e[l]=255;for(let l=0;l<t.length;l++){const u=t.charAt(l),h=u.charCodeAt(0);if(e[h]!==255)throw new TypeError(u+" is ambiguous");e[h]=l}const i=t.length,r=t.charAt(0),n=Math.log(i)/Math.log(256),s=Math.log(256)/Math.log(i);function o(l){if(l instanceof Uint8Array||(ArrayBuffer.isView(l)?l=new Uint8Array(l.buffer,l.byteOffset,l.byteLength):Array.isArray(l)&&(l=Uint8Array.from(l))),!(l instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(l.length===0)return"";let u=0,h=0,f=0;const d=l.length;for(;f!==d&&l[f]===0;)f++,u++;const p=(d-f)*s+1>>>0,g=new Uint8Array(p);for(;f!==d;){let C=l[f],b=0;for(let v=p-1;(C!==0||b<h)&&v!==-1;v--,b++)C+=256*g[v]>>>0,g[v]=C%i>>>0,C=C/i>>>0;if(C!==0)throw new Error("Non-zero carry");h=b,f++}let w=p-h;for(;w!==p&&g[w]===0;)w++;let _=r.repeat(u);for(;w<p;++w)_+=t.charAt(g[w]);return _}function a(l){if(typeof l!="string")throw new TypeError("Expected String");if(l.length===0)return new Uint8Array;let u=0,h=0,f=0;for(;l[u]===r;)h++,u++;const d=(l.length-u)*n+1>>>0,p=new Uint8Array(d);for(;u<l.length;){const C=l.charCodeAt(u);if(C>255)return;let b=e[C];if(b===255)return;let v=0;for(let O=d-1;(b!==0||v<f)&&O!==-1;O--,v++)b+=i*p[O]>>>0,p[O]=b%256>>>0,b=b/256>>>0;if(b!==0)throw new Error("Non-zero carry");f=v,u++}let g=d-f;for(;g!==d&&p[g]===0;)g++;const w=new Uint8Array(h+(d-g));let _=h;for(;g!==d;)w[_++]=p[g++];return w}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+i+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var $m="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const An=Sm($m);function Dm(t){const e=t.length;let i=0,r=0;for(;r<e;){let n=t.charCodeAt(r++);if(n&4294967168)if(!(n&4294965248))i+=2;else{if(n>=55296&&n<=56319&&r<e){const s=t.charCodeAt(r);(s&64512)===56320&&(++r,n=((n&1023)<<10)+(s&1023)+65536)}n&4294901760?i+=4:i+=3}else{i++;continue}}return i}function Om(t,e,i){const r=t.length;let n=i,s=0;for(;s<r;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<r){const a=t.charCodeAt(s);(a&64512)===56320&&(++s,o=((o&1023)<<10)+(a&1023)+65536)}o&4294901760?(e[n++]=o>>18&7|240,e[n++]=o>>12&63|128,e[n++]=o>>6&63|128):(e[n++]=o>>12&15|224,e[n++]=o>>6&63|128)}else{e[n++]=o;continue}e[n++]=o&63|128}}const Am=new TextEncoder,Pm=50;function Cm(t,e,i){Am.encodeInto(t,e.subarray(i))}function Bm(t,e,i){t.length>Pm?Cm(t,e,i):Om(t,e,i)}const Tm=4096;function yd(t,e,i){let r=e;const n=r+i,s=[];let o="";for(;r<n;){const a=t[r++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[r++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[r++]&63,l=t[r++]&63;s.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[r++]&63,l=t[r++]&63,u=t[r++]&63;let h=(a&7)<<18|c<<12|l<<6|u;h>65535&&(h-=65536,s.push(h>>>10&1023|55296),h=56320|h&1023),s.push(h)}else s.push(a);s.length>=Tm&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Rm=new TextDecoder,Fm=200;function Nm(t,e,i){const r=t.subarray(e,e+i);return Rm.decode(r)}function Um(t,e,i){return i>Fm?Nm(t,e,i):yd(t,e,i)}class qn{constructor(e,i){this.type=e,this.data=i}}class ut extends Error{constructor(e){super(e);const i=Object.create(ut.prototype);Object.setPrototypeOf(this,i),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ut.name})}}const Kr=4294967295;function km(t,e,i){const r=i/4294967296,n=i;t.setUint32(e,r),t.setUint32(e+4,n)}function wd(t,e,i){const r=Math.floor(i/4294967296),n=i;t.setUint32(e,r),t.setUint32(e+4,n)}function md(t,e){const i=t.getInt32(e),r=t.getUint32(e+4);return i*4294967296+r}function jm(t,e){const i=t.getUint32(e),r=t.getUint32(e+4);return i*4294967296+r}const Lm=-1,Mm=4294967296-1,qm=17179869184-1;function zm({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=qm)if(e===0&&t<=Mm){const i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,t),i}else{const i=t/4294967296,r=t&4294967295,n=new Uint8Array(8),s=new DataView(n.buffer);return s.setUint32(0,e<<2|i&3),s.setUint32(4,r),n}else{const i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,e),wd(r,4,t),i}}function Vm(t){const e=t.getTime(),i=Math.floor(e/1e3),r=(e-i*1e3)*1e6,n=Math.floor(r/1e9);return{sec:i+n,nsec:r-n*1e9}}function Hm(t){if(t instanceof Date){const e=Vm(t);return zm(e)}else return null}function Km(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 i=e.getUint32(0),r=e.getUint32(4),n=(i&3)*4294967296+r,s=i>>>2;return{sec:n,nsec:s}}case 12:{const i=md(e,4),r=e.getUint32(0);return{sec:i,nsec:r}}default:throw new ut(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Wm(t){const e=Km(t);return new Date(e.sec*1e3+e.nsec/1e6)}const Gm={type:Lm,encode:Hm,decode:Wm};class Es{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(Gm)}register({type:e,encode:i,decode:r}){if(e>=0)this.encoders[e]=i,this.decoders[e]=r;else{const n=-1-e;this.builtInEncoders[n]=i,this.builtInDecoders[n]=r}}tryToEncode(e,i){for(let r=0;r<this.builtInEncoders.length;r++){const n=this.builtInEncoders[r];if(n!=null){const s=n(e,i);if(s!=null){const o=-1-r;return new qn(o,s)}}}for(let r=0;r<this.encoders.length;r++){const n=this.encoders[r];if(n!=null){const s=n(e,i);if(s!=null){const o=r;return new qn(o,s)}}}return e instanceof qn?e:null}decode(e,i,r){const n=i<0?this.builtInDecoders[-1-i]:this.decoders[i];return n?n(e,i,r):new qn(i,e)}}Es.defaultCodec=new Es;function Ym(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ea(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Ym(t)?new Uint8Array(t):Uint8Array.from(t)}const Zm=100,Jm=2048;let Xm=class bd{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Es.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.maxDepth=(e==null?void 0:e.maxDepth)??Zm,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??Jm,this.sortKeys=(e==null?void 0:e.sortKeys)??!1,this.forceFloat32=(e==null?void 0:e.forceFloat32)??!1,this.ignoreUndefined=(e==null?void 0:e.ignoreUndefined)??!1,this.forceIntegerToFloat=(e==null?void 0:e.forceIntegerToFloat)??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new bd({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,i){if(i>this.maxDepth)throw new Error(`Too deep objects in depth ${i}`);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,i)}ensureBufferSizeToWrite(e){const i=this.pos+e;this.view.byteLength<i&&this.resizeBuffer(i*2)}resizeBuffer(e){const i=new ArrayBuffer(e),r=new Uint8Array(i),n=new DataView(i);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const r=Dm(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),Bm(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,i){const r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,i);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,i);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const i=e.byteLength;if(i<256)this.writeU8(196),this.writeU8(i);else if(i<65536)this.writeU8(197),this.writeU16(i);else if(i<4294967296)this.writeU8(198),this.writeU32(i);else throw new Error(`Too large binary: ${i}`);const r=Ea(e);this.writeU8a(r)}encodeArray(e,i){const r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(const n of e)this.doEncode(n,i+1)}countWithoutUndefined(e,i){let r=0;for(const n of i)e[n]!==void 0&&r++;return r}encodeMap(e,i){const r=Object.keys(e);this.sortKeys&&r.sort();const n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(const s of r){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,i+1))}}encodeExtension(e){if(typeof e.data=="function"){const r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(r);return}const i=e.data.length;if(i===1)this.writeU8(212);else if(i===2)this.writeU8(213);else if(i===4)this.writeU8(214);else if(i===8)this.writeU8(215);else if(i===16)this.writeU8(216);else if(i<256)this.writeU8(199),this.writeU8(i);else if(i<65536)this.writeU8(200),this.writeU16(i);else if(i<4294967296)this.writeU8(201),this.writeU32(i);else throw new Error(`Too large extension object: ${i}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const i=e.length;this.ensureBufferSizeToWrite(i),this.bytes.set(e,this.pos),this.pos+=i}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),km(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),wd(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 Qm(t,e){return new Xm(e).encodeSharedRef(t)}function Oo(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const e1=16,t1=16;class i1{constructor(e=e1,i=t1){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=i,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,i,r){const n=this.caches[r-1];e:for(const s of n){const o=s.bytes;for(let a=0;a<r;a++)if(o[a]!==e[i+a])continue e;return s.str}return null}store(e,i){const r=this.caches[e.length-1],n={bytes:e,str:i};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,i,r){const n=this.find(e,i,r);if(n!=null)return this.hit++,n;this.miss++;const s=yd(e,i,r),o=Uint8Array.prototype.slice.call(e,i,i+r);return this.store(o,s),s}}const xa="array",hn="map_key",vd="map_value",r1=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new ut("The type of key must be string or number but "+typeof t)};class n1{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const i=this.getUninitializedStateFromPool();i.type=xa,i.position=0,i.size=e,i.array=new Array(e)}pushMapState(e){const i=this.getUninitializedStateFromPool();i.type=hn,i.readCount=0,i.size=e,i.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===xa){const r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===hn||e.type===vd){const r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wr=-1,vc=new DataView(new ArrayBuffer(0)),s1=new Uint8Array(vc.buffer);try{vc.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 zl=new RangeError("Insufficient data"),o1=new i1;let a1=class Ed{constructor(e){this.totalPos=0,this.pos=0,this.view=vc,this.bytes=s1,this.headByte=Wr,this.stack=new n1,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Es.defaultCodec,this.context=e==null?void 0:e.context,this.useBigInt64=(e==null?void 0:e.useBigInt64)??!1,this.rawStrings=(e==null?void 0:e.rawStrings)??!1,this.maxStrLength=(e==null?void 0:e.maxStrLength)??Kr,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Kr,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Kr,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Kr,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Kr,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:o1,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??r1}clone(){return new Ed({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=Wr,this.stack.reset()}setBuffer(e){const i=Ea(e);this.bytes=i,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wr&&!this.hasRemaining(1))this.setBuffer(e);else{const i=this.bytes.subarray(this.pos),r=Ea(e),n=new Uint8Array(i.length+r.length);n.set(i),n.set(r,i.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:i,pos:r}=this;return new RangeError(`Extra ${i.byteLength-r} of ${i.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 i=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return i}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 i=!1,r;for await(const a of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{r=this.doDecodeSync(),i=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}const{headByte:n,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Oo(n)} at ${o} (${s} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,i){if(this.entered){yield*this.clone().decodeMultiAsync(e,i);return}try{this.entered=!0;let r=i,n=-1;for await(const s of e){if(i&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==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 i;if(e>=224)i=e-256;else if(e<192)if(e<128)i=e;else if(e<144){const n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e<160){const n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else{const n=e-160;i=this.decodeString(n,0)}else if(e===192)i=null;else if(e===194)i=!1;else if(e===195)i=!0;else if(e===202)i=this.readF32();else if(e===203)i=this.readF64();else if(e===204)i=this.readU8();else if(e===205)i=this.readU16();else if(e===206)i=this.readU32();else if(e===207)this.useBigInt64?i=this.readU64AsBigInt():i=this.readU64();else if(e===208)i=this.readI8();else if(e===209)i=this.readI16();else if(e===210)i=this.readI32();else if(e===211)this.useBigInt64?i=this.readI64AsBigInt():i=this.readI64();else if(e===217){const n=this.lookU8();i=this.decodeString(n,1)}else if(e===218){const n=this.lookU16();i=this.decodeString(n,2)}else if(e===219){const n=this.lookU32();i=this.decodeString(n,4)}else if(e===220){const n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(e===221){const n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(e===222){const n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e===223){const n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e===196){const n=this.lookU8();i=this.decodeBinary(n,1)}else if(e===197){const n=this.lookU16();i=this.decodeBinary(n,2)}else if(e===198){const n=this.lookU32();i=this.decodeBinary(n,4)}else if(e===212)i=this.decodeExtension(1,0);else if(e===213)i=this.decodeExtension(2,0);else if(e===214)i=this.decodeExtension(4,0);else if(e===215)i=this.decodeExtension(8,0);else if(e===216)i=this.decodeExtension(16,0);else if(e===199){const n=this.lookU8();i=this.decodeExtension(n,1)}else if(e===200){const n=this.lookU16();i=this.decodeExtension(n,2)}else if(e===201){const n=this.lookU32();i=this.decodeExtension(n,4)}else throw new ut(`Unrecognized type byte: ${Oo(e)}`);this.complete();const r=this.stack;for(;r.length>0;){const n=r.top();if(n.type===xa)if(n.array[n.position]=i,n.position++,n.position===n.size)i=n.array,r.release(n);else continue e;else if(n.type===hn){if(i==="__proto__")throw new ut("The key __proto__ is not allowed");n.key=this.mapKeyConverter(i),n.type=vd;continue e}else if(n.map[n.key]=i,n.readCount++,n.readCount===n.size)i=n.map,r.release(n);else{n.key=null,n.type=hn;continue e}}return i}}readHeadByte(){return this.headByte===Wr&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wr}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 ut(`Unrecognized array type byte: ${Oo(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new ut(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new ut(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,i){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,i):this.decodeBinary(e,i)}decodeUtf8String(e,i){var s;if(e>this.maxStrLength)throw new ut(`Max length exceeded: UTF-8 byte length (${e}) > maxStrLength (${this.maxStrLength})`);if(this.bytes.byteLength<this.pos+i+e)throw zl;const r=this.pos+i;let n;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?n=this.keyDecoder.decode(this.bytes,r,e):n=Um(this.bytes,r,e),this.pos+=i+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hn:!1}decodeBinary(e,i){if(e>this.maxBinLength)throw new ut(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+i))throw zl;const r=this.pos+i,n=this.bytes.subarray(r,r+e);return this.pos+=i+e,n}decodeExtension(e,i){if(e>this.maxExtLength)throw new ut(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const r=this.view.getInt8(this.pos+i),n=this.decodeBinary(e,i+1);return this.extensionCodec.decode(n,r,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=jm(this.view,this.pos);return this.pos+=8,e}readI64(){const e=md(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 c1(t,e){return new a1(e).decode(t)}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function l1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function xd(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(i=>typeof i=="string"):e.every(i=>Number.isSafeInteger(i)):!1}function xs(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Ec(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function Ia(t){if(!Array.isArray(t))throw new Error("array expected")}function Is(t,e){if(!xd(!0,e))throw new Error(`${t}: array of strings expected`)}function u1(t,e){if(!xd(!1,e))throw new Error(`${t}: array of numbers expected`)}function h1(...t){const e=s=>s,i=(s,o)=>a=>s(o(a)),r=t.map(s=>s.encode).reduceRight(i,e),n=t.map(s=>s.decode).reduce(i,e);return{encode:r,decode:n}}function f1(t){const e=typeof t=="string"?t.split(""):t,i=e.length;Is("alphabet",e);const r=new Map(e.map((n,s)=>[n,s]));return{encode:n=>(Ia(n),n.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=i)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:n=>(Ia(n),n.map(s=>{xs("alphabet.decode",s);const o=r.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function d1(t=""){return xs("join",t),{encode:e=>(Is("join.decode",e),e.join(t)),decode:e=>(xs("join.decode",e),e.split(t))}}function p1(t,e="="){return Ec(t),xs("padding",e),{encode(i){for(Is("padding.encode",i);i.length*t%8;)i.push(e);return i},decode(i){Is("padding.decode",i);let r=i.length;if(r*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;r>0&&i[r-1]===e;r--)if((r-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return i.slice(0,r)}}}const Id=(t,e)=>e===0?t:Id(e,t%e),_s=(t,e)=>t+(e-Id(t,e)),Ao=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Vl(t,e,i,r){if(Ia(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(i<=0||i>32)throw new Error(`convertRadix2: wrong to=${i}`);if(_s(e,i)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${i} carryBits=${_s(e,i)}`);let n=0,s=0;const o=Ao[e],a=Ao[i]-1,c=[];for(const l of t){if(Ec(l),l>=o)throw new Error(`convertRadix2: invalid data word=${l} from=${e}`);if(n=n<<e|l,s+e>32)throw new Error(`convertRadix2: carry overflow pos=${s} from=${e}`);for(s+=e;s>=i;s-=i)c.push((n>>s-i&a)>>>0);const u=Ao[s];if(u===void 0)throw new Error("invalid carry");n&=u-1}if(n=n<<i-s&a,!r&&s>=e)throw new Error("Excess padding");if(!r&&n>0)throw new Error(`Non-zero padding: ${n}`);return r&&s>0&&c.push(n>>>0),c}function g1(t,e=!1){if(Ec(t),t<=0||t>32)throw new Error("radix2: bits should be in (0..32]");if(_s(8,t)>32||_s(t,8)>32)throw new Error("radix2: carry overflow");return{encode:i=>{if(!l1(i))throw new Error("radix2.encode input should be Uint8Array");return Vl(Array.from(i),8,t,!e)},decode:i=>(u1("radix2.decode",i),Uint8Array.from(Vl(i,t,8,e)))}}const y1=h1(g1(5),f1("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),p1(5),d1("")),w1=t=>JSON.stringify(t,(e,i)=>typeof i=="bigint"?i.toString()+"n":i),m1=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,i=t.replace(e,'$1"$2n"$3');return JSON.parse(i,(r,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function sr(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return m1(t)}catch{return t}}function ui(t){return typeof t=="string"?t:w1(t)||""}function b1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _d(t,...e){if(!b1(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 Hl(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 v1(t,e){_d(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}const wr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Po=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);function E1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Sd(t){return typeof t=="string"&&(t=E1(t)),_d(t),t}let x1=class{clone(){return this._cloneInto()}};function I1(t){const e=r=>t().update(Sd(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function $d(t=32){if(wr&&typeof wr.getRandomValues=="function")return wr.getRandomValues(new Uint8Array(t));if(wr&&typeof wr.randomBytes=="function")return wr.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function _1(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const n=BigInt(32),s=BigInt(4294967295),o=Number(i>>n&s),a=Number(i&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}let S1=class extends x1{constructor(e,i,r,n){super(),this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=n,this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.buffer=new Uint8Array(e),this.view=Po(this.buffer)}update(e){Hl(this);const{view:i,buffer:r,blockLen:n}=this;e=Sd(e);const s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=Po(e);for(;n<=s-o;o+=n)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Hl(this),v1(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:n,isLE:s}=this;let{pos:o}=this;i[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(r,0),o=0);for(let h=o;h<n;h++)i[h]=0;_1(r,n-8,BigInt(this.length*8),s),this.process(r,0);const a=Po(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],s)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:n,finished:s,destroyed:o,pos:a}=this;return e.length=n,e.pos=a,e.finished=s,e.destroyed=o,n%i&&e.buffer.set(r),e}};const zn=BigInt(2**32-1),_a=BigInt(32);function Dd(t,e=!1){return e?{h:Number(t&zn),l:Number(t>>_a&zn)}:{h:Number(t>>_a&zn)|0,l:Number(t&zn)|0}}function $1(t,e=!1){let i=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let n=0;n<t.length;n++){const{h:s,l:o}=Dd(t[n],e);[i[n],r[n]]=[s,o]}return[i,r]}const D1=(t,e)=>BigInt(t>>>0)<<_a|BigInt(e>>>0),O1=(t,e,i)=>t>>>i,A1=(t,e,i)=>t<<32-i|e>>>i,P1=(t,e,i)=>t>>>i|e<<32-i,C1=(t,e,i)=>t<<32-i|e>>>i,B1=(t,e,i)=>t<<64-i|e>>>i-32,T1=(t,e,i)=>t>>>i-32|e<<64-i,R1=(t,e)=>e,F1=(t,e)=>t,N1=(t,e,i)=>t<<i|e>>>32-i,U1=(t,e,i)=>e<<i|t>>>32-i,k1=(t,e,i)=>e<<i-32|t>>>64-i,j1=(t,e,i)=>t<<i-32|e>>>64-i;function L1(t,e,i,r){const n=(e>>>0)+(r>>>0);return{h:t+i+(n/2**32|0)|0,l:n|0}}const M1=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),q1=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,z1=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),V1=(t,e,i,r,n)=>e+i+r+n+(t/2**32|0)|0,H1=(t,e,i,r,n)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(n>>>0),K1=(t,e,i,r,n,s)=>e+i+r+n+s+(t/2**32|0)|0,J={fromBig:Dd,split:$1,toBig:D1,shrSH:O1,shrSL:A1,rotrSH:P1,rotrSL:C1,rotrBH:B1,rotrBL:T1,rotr32H:R1,rotr32L:F1,rotlSH:N1,rotlSL:U1,rotlBH:k1,rotlBL:j1,add:L1,add3L:M1,add3H:q1,add4L:z1,add4H:V1,add5H:K1,add5L:H1},[W1,G1]=(()=>J.split(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(t=>BigInt(t))))(),yi=new Uint32Array(80),wi=new Uint32Array(80);let Y1=class extends S1{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:i,Bh:r,Bl:n,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,i){for(let b=0;b<16;b++,i+=4)yi[b]=e.getUint32(i),wi[b]=e.getUint32(i+=4);for(let b=16;b<80;b++){const v=yi[b-15]|0,O=wi[b-15]|0,P=J.rotrSH(v,O,1)^J.rotrSH(v,O,8)^J.shrSH(v,O,7),T=J.rotrSL(v,O,1)^J.rotrSL(v,O,8)^J.shrSL(v,O,7),R=yi[b-2]|0,A=wi[b-2]|0,U=J.rotrSH(R,A,19)^J.rotrBH(R,A,61)^J.shrSH(R,A,6),j=J.rotrSL(R,A,19)^J.rotrBL(R,A,61)^J.shrSL(R,A,6),B=J.add4L(T,j,wi[b-7],wi[b-16]),I=J.add4H(B,P,U,yi[b-7],yi[b-16]);yi[b]=I|0,wi[b]=B|0}let{Ah:r,Al:n,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:d,Fl:p,Gh:g,Gl:w,Hh:_,Hl:C}=this;for(let b=0;b<80;b++){const v=J.rotrSH(h,f,14)^J.rotrSH(h,f,18)^J.rotrBH(h,f,41),O=J.rotrSL(h,f,14)^J.rotrSL(h,f,18)^J.rotrBL(h,f,41),P=h&d^~h&g,T=f&p^~f&w,R=J.add5L(C,O,T,G1[b],wi[b]),A=J.add5H(R,_,v,P,W1[b],yi[b]),U=R|0,j=J.rotrSH(r,n,28)^J.rotrBH(r,n,34)^J.rotrBH(r,n,39),B=J.rotrSL(r,n,28)^J.rotrBL(r,n,34)^J.rotrBL(r,n,39),I=r&s^r&a^s&a,D=n&o^n&c^o&c;_=g|0,C=w|0,g=d|0,w=p|0,d=h|0,p=f|0,{h,l:f}=J.add(l|0,u|0,A|0,U|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=n|0;const m=J.add3L(U,B,D);r=J.add3H(m,A,j,I),n=m|0}({h:r,l:n}=J.add(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:o}=J.add(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=J.add(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=J.add(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=J.add(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=J.add(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=J.add(this.Gh|0,this.Gl|0,g|0,w|0),{h:_,l:C}=J.add(this.Hh|0,this.Hl|0,_|0,C|0),this.set(r,n,s,o,a,c,l,u,h,f,d,p,g,w,_,C)}roundClean(){yi.fill(0),wi.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 Z1=I1(()=>new Y1);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const xc=BigInt(0),Od=BigInt(1),J1=BigInt(2);function Ic(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _c(t){if(!Ic(t))throw new Error("Uint8Array expected")}function Co(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const X1=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Sc(t){_c(t);let e="";for(let i=0;i<t.length;i++)e+=X1[t[i]];return e}function Ad(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?xc:BigInt("0x"+t)}const Zt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Kl(t){if(t>=Zt._0&&t<=Zt._9)return t-Zt._0;if(t>=Zt.A&&t<=Zt.F)return t-(Zt.A-10);if(t>=Zt.a&&t<=Zt.f)return t-(Zt.a-10)}function Pd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let n=0,s=0;n<i;n++,s+=2){const o=Kl(t.charCodeAt(s)),a=Kl(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[n]=o*16+a}return r}function Q1(t){return Ad(Sc(t))}function us(t){return _c(t),Ad(Sc(Uint8Array.from(t).reverse()))}function Cd(t,e){return Pd(t.toString(16).padStart(e*2,"0"))}function Sa(t,e){return Cd(t,e).reverse()}function Jt(t,e,i){let r;if(typeof e=="string")try{r=Pd(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Ic(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=r.length;if(typeof i=="number"&&n!==i)throw new Error(t+" of length "+i+" expected, got "+n);return r}function Wl(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];_c(n),e+=n.length}const i=new Uint8Array(e);for(let r=0,n=0;r<t.length;r++){const s=t[r];i.set(s,n),n+=s.length}return i}const Bo=t=>typeof t=="bigint"&&xc<=t;function eb(t,e,i){return Bo(t)&&Bo(e)&&Bo(i)&&e<=t&&t<i}function Gr(t,e,i,r){if(!eb(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function tb(t){let e;for(e=0;t>xc;t>>=Od,e+=1);return e}const ib=t=>(J1<<BigInt(t-1))-Od,rb={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"||Ic(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 $c(t,e,i={}){const r=(n,s,o)=>{const a=rb[s];if(typeof a!="function")throw new Error("invalid validator function");const c=t[n];if(!(o&&c===void 0)&&!a(c,t))throw new Error("param "+String(n)+" is invalid. Expected "+s+", got "+c)};for(const[n,s]of Object.entries(e))r(n,s,!1);for(const[n,s]of Object.entries(i))r(n,s,!0);return t}function Gl(t){const e=new WeakMap;return(i,...r)=>{const n=e.get(i);if(n!==void 0)return n;const s=t(i,...r);return e.set(i,s),s}}const Ae=BigInt(0),ge=BigInt(1),Gi=BigInt(2),nb=BigInt(3),$a=BigInt(4),Yl=BigInt(5),Zl=BigInt(8);function xe(t,e){const i=t%e;return i>=Ae?i:e+i}function sb(t,e,i){if(e<Ae)throw new Error("invalid exponent, negatives unsupported");if(i<=Ae)throw new Error("invalid modulus");if(i===ge)return Ae;let r=ge;for(;e>Ae;)e&ge&&(r=r*t%i),t=t*t%i,e>>=ge;return r}function Ft(t,e,i){let r=t;for(;e-- >Ae;)r*=r,r%=i;return r}function Jl(t,e){if(t===Ae)throw new Error("invert: expected non-zero number");if(e<=Ae)throw new Error("invert: expected positive modulus, got "+e);let i=xe(t,e),r=e,n=Ae,s=ge;for(;i!==Ae;){const o=r/i,a=r%i,c=n-s*o;r=i,i=a,n=s,s=c}if(r!==ge)throw new Error("invert: does not exist");return xe(n,e)}function ob(t){const e=(t-ge)/Gi;let i,r,n;for(i=t-ge,r=0;i%Gi===Ae;i/=Gi,r++);for(n=Gi;n<t&&sb(n,e,t)!==t-ge;n++)if(n>1e3)throw new Error("Cannot find square root: likely non-prime P");if(r===1){const o=(t+ge)/$a;return function(a,c){const l=a.pow(c,o);if(!a.eql(a.sqr(l),c))throw new Error("Cannot find square root");return l}}const s=(i+ge)/Gi;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=r,l=o.pow(o.mul(o.ONE,n),i),u=o.pow(a,s),h=o.pow(a,i);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let p=o.sqr(h);f<c&&!o.eql(p,o.ONE);f++)p=o.sqr(p);const d=o.pow(l,ge<<BigInt(c-f-1));l=o.sqr(d),u=o.mul(u,d),h=o.mul(h,l),c=f}return u}}function ab(t){if(t%$a===nb){const e=(t+ge)/$a;return function(i,r){const n=i.pow(r,e);if(!i.eql(i.sqr(n),r))throw new Error("Cannot find square root");return n}}if(t%Zl===Yl){const e=(t-Yl)/Zl;return function(i,r){const n=i.mul(r,Gi),s=i.pow(n,e),o=i.mul(r,s),a=i.mul(i.mul(o,Gi),s),c=i.mul(o,i.sub(a,i.ONE));if(!i.eql(i.sqr(c),r))throw new Error("Cannot find square root");return c}}return ob(t)}const cb=(t,e)=>(xe(t,e)&ge)===ge,lb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function ub(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},i=lb.reduce((r,n)=>(r[n]="function",r),e);return $c(t,i)}function hb(t,e,i){if(i<Ae)throw new Error("invalid exponent, negatives unsupported");if(i===Ae)return t.ONE;if(i===ge)return e;let r=t.ONE,n=e;for(;i>Ae;)i&ge&&(r=t.mul(r,n)),n=t.sqr(n),i>>=ge;return r}function fb(t,e){const i=new Array(e.length),r=e.reduce((s,o,a)=>t.is0(o)?s:(i[a]=s,t.mul(s,o)),t.ONE),n=t.inv(r);return e.reduceRight((s,o,a)=>t.is0(o)?s:(i[a]=t.mul(s,i[a]),t.mul(s,o)),n),i}function Bd(t,e){const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function Td(t,e,i=!1,r={}){if(t<=Ae)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=Bd(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:i,BITS:n,BYTES:s,MASK:ib(n),ZERO:Ae,ONE:ge,create:c=>xe(c,t),isValid:c=>{if(typeof c!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof c);return Ae<=c&&c<t},is0:c=>c===Ae,isOdd:c=>(c&ge)===ge,neg:c=>xe(-c,t),eql:(c,l)=>c===l,sqr:c=>xe(c*c,t),add:(c,l)=>xe(c+l,t),sub:(c,l)=>xe(c-l,t),mul:(c,l)=>xe(c*l,t),pow:(c,l)=>hb(a,c,l),div:(c,l)=>xe(c*Jl(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>Jl(c,t),sqrt:r.sqrt||(c=>(o||(o=ab(t)),o(a,c))),invertBatch:c=>fb(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>i?Sa(c,s):Cd(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return i?us(c):Q1(c)}});return Object.freeze(a)}const Xl=BigInt(0),Vn=BigInt(1);function To(t,e){const i=e.negate();return t?i:e}function Rd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ro(t,e){Rd(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1);return{windows:i,windowSize:r}}function db(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function pb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const Fo=new WeakMap,Fd=new WeakMap;function No(t){return Fd.get(t)||1}function gb(t,e){return{constTimeNegate:To,hasPrecomputes(i){return No(i)!==1},unsafeLadder(i,r,n=t.ZERO){let s=i;for(;r>Xl;)r&Vn&&(n=n.add(s)),s=s.double(),r>>=Vn;return n},precomputeWindow(i,r){const{windows:n,windowSize:s}=Ro(r,e),o=[];let a=i,c=a;for(let l=0;l<n;l++){c=a,o.push(c);for(let u=1;u<s;u++)c=c.add(a),o.push(c);a=c.double()}return o},wNAF(i,r,n){const{windows:s,windowSize:o}=Ro(i,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**i-1),u=2**i,h=BigInt(i);for(let f=0;f<s;f++){const d=f*o;let p=Number(n&l);n>>=h,p>o&&(p-=u,n+=Vn);const g=d,w=d+Math.abs(p)-1,_=f%2!==0,C=p<0;p===0?c=c.add(To(_,r[g])):a=a.add(To(C,r[w]))}return{p:a,f:c}},wNAFUnsafe(i,r,n,s=t.ZERO){const{windows:o,windowSize:a}=Ro(i,e),c=BigInt(2**i-1),l=2**i,u=BigInt(i);for(let h=0;h<o;h++){const f=h*a;if(n===Xl)break;let d=Number(n&c);if(n>>=u,d>a&&(d-=l,n+=Vn),d===0)continue;let p=r[f+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(i,r,n){let s=Fo.get(r);return s||(s=this.precomputeWindow(r,i),i!==1&&Fo.set(r,n(s))),s},wNAFCached(i,r,n){const s=No(i);return this.wNAF(s,this.getPrecomputes(s,i,n),r)},wNAFCachedUnsafe(i,r,n,s){const o=No(i);return o===1?this.unsafeLadder(i,r,s):this.wNAFUnsafe(o,this.getPrecomputes(o,i,n),r,s)},setWindowSize(i,r){Rd(r,e),Fd.set(i,r),Fo.delete(i)}}}function yb(t,e,i,r){if(db(i,t),pb(r,e),i.length!==r.length)throw new Error("arrays of points and scalars must have equal length");const n=t.ZERO,s=tb(BigInt(i.length)),o=s>12?s-3:s>4?s-2:s?2:1,a=(1<<o)-1,c=new Array(a+1).fill(n),l=Math.floor((e.BITS-1)/o)*o;let u=n;for(let h=l;h>=0;h-=o){c.fill(n);for(let d=0;d<r.length;d++){const p=r[d],g=Number(p>>BigInt(h)&BigInt(a));c[g]=c[g].add(i[d])}let f=n;for(let d=c.length-1,p=n;d>0;d--)p=p.add(c[d]),f=f.add(p);if(u=u.add(f),h!==0)for(let d=0;d<o;d++)u=u.double()}return u}function wb(t){return ub(t.Fp),$c(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...Bd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const $t=BigInt(0),Ye=BigInt(1),Hn=BigInt(2),mb=BigInt(8),bb={zip215:!0};function vb(t){const e=wb(t);return $c(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function Eb(t){const e=vb(t),{Fp:i,n:r,prehash:n,hash:s,randomBytes:o,nByteLength:a,h:c}=e,l=Hn<<BigInt(a*8)-Ye,u=i.create,h=Td(e.n,e.nBitLength),f=e.uvRatio||((m,y)=>{try{return{isValid:!0,value:i.sqrt(m*i.inv(y))}}catch{return{isValid:!1,value:$t}}}),d=e.adjustScalarBytes||(m=>m),p=e.domain||((m,y,x)=>{if(Co("phflag",x),y.length||x)throw new Error("Contexts/pre-hash are not supported");return m});function g(m,y){Gr("coordinate "+m,y,$t,l)}function w(m){if(!(m instanceof b))throw new Error("ExtendedPoint expected")}const _=Gl((m,y)=>{const{ex:x,ey:$,ez:E}=m,S=m.is0();y==null&&(y=S?mb:i.inv(E));const F=u(x*y),N=u($*y),H=u(E*y);if(S)return{x:$t,y:Ye};if(H!==Ye)throw new Error("invZ was invalid");return{x:F,y:N}}),C=Gl(m=>{const{a:y,d:x}=e;if(m.is0())throw new Error("bad point: ZERO");const{ex:$,ey:E,ez:S,et:F}=m,N=u($*$),H=u(E*E),z=u(S*S),q=u(z*z),K=u(N*y),G=u(z*u(K+H)),X=u(q+u(x*u(N*H)));if(G!==X)throw new Error("bad point: equation left != right (1)");const W=u($*E),Q=u(S*F);if(W!==Q)throw new Error("bad point: equation left != right (2)");return!0});class b{constructor(y,x,$,E){this.ex=y,this.ey=x,this.ez=$,this.et=E,g("x",y),g("y",x),g("z",$),g("t",E),Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(y){if(y instanceof b)throw new Error("extended point not allowed");const{x,y:$}=y||{};return g("x",x),g("y",$),new b(x,$,Ye,u(x*$))}static normalizeZ(y){const x=i.invertBatch(y.map($=>$.ez));return y.map(($,E)=>$.toAffine(x[E])).map(b.fromAffine)}static msm(y,x){return yb(b,h,y,x)}_setWindowSize(y){P.setWindowSize(this,y)}assertValidity(){C(this)}equals(y){w(y);const{ex:x,ey:$,ez:E}=this,{ex:S,ey:F,ez:N}=y,H=u(x*N),z=u(S*E),q=u($*N),K=u(F*E);return H===z&&q===K}is0(){return this.equals(b.ZERO)}negate(){return new b(u(-this.ex),this.ey,this.ez,u(-this.et))}double(){const{a:y}=e,{ex:x,ey:$,ez:E}=this,S=u(x*x),F=u($*$),N=u(Hn*u(E*E)),H=u(y*S),z=x+$,q=u(u(z*z)-S-F),K=H+F,G=K-N,X=H-F,W=u(q*G),Q=u(K*X),pe=u(q*X),ve=u(G*K);return new b(W,Q,ve,pe)}add(y){w(y);const{a:x,d:$}=e,{ex:E,ey:S,ez:F,et:N}=this,{ex:H,ey:z,ez:q,et:K}=y;if(x===BigInt(-1)){const il=u((S-E)*(z+H)),rl=u((S+E)*(z-H)),ho=u(rl-il);if(ho===$t)return this.double();const nl=u(F*Hn*K),sl=u(N*Hn*q),ol=sl+nl,al=rl+il,cl=sl-nl,x0=u(ol*ho),I0=u(al*cl),_0=u(ol*cl),S0=u(ho*al);return new b(x0,I0,S0,_0)}const G=u(E*H),X=u(S*z),W=u(N*$*K),Q=u(F*q),pe=u((E+S)*(H+z)-G-X),ve=Q-W,_e=Q+W,He=u(X-x*G),Wt=u(pe*ve),di=u(_e*He),v0=u(pe*He),E0=u(ve*_e);return new b(Wt,di,E0,v0)}subtract(y){return this.add(y.negate())}wNAF(y){return P.wNAFCached(this,y,b.normalizeZ)}multiply(y){const x=y;Gr("scalar",x,Ye,r);const{p:$,f:E}=this.wNAF(x);return b.normalizeZ([$,E])[0]}multiplyUnsafe(y,x=b.ZERO){const $=y;return Gr("scalar",$,$t,r),$===$t?O:this.is0()||$===Ye?this:P.wNAFCachedUnsafe(this,$,b.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,r).is0()}toAffine(y){return _(this,y)}clearCofactor(){const{h:y}=e;return y===Ye?this:this.multiplyUnsafe(y)}static fromHex(y,x=!1){const{d:$,a:E}=e,S=i.BYTES;y=Jt("pointHex",y,S),Co("zip215",x);const F=y.slice(),N=y[S-1];F[S-1]=N&-129;const H=us(F),z=x?l:i.ORDER;Gr("pointHex.y",H,$t,z);const q=u(H*H),K=u(q-Ye),G=u($*q-E);let{isValid:X,value:W}=f(K,G);if(!X)throw new Error("Point.fromHex: invalid y coordinate");const Q=(W&Ye)===Ye,pe=(N&128)!==0;if(!x&&W===$t&&pe)throw new Error("Point.fromHex: x=0 and x_0=1");return pe!==Q&&(W=u(-W)),b.fromAffine({x:W,y:H})}static fromPrivateKey(y){return A(y).point}toRawBytes(){const{x:y,y:x}=this.toAffine(),$=Sa(x,i.BYTES);return $[$.length-1]|=y&Ye?128:0,$}toHex(){return Sc(this.toRawBytes())}}b.BASE=new b(e.Gx,e.Gy,Ye,u(e.Gx*e.Gy)),b.ZERO=new b($t,Ye,Ye,$t);const{BASE:v,ZERO:O}=b,P=gb(b,a*8);function T(m){return xe(m,r)}function R(m){return T(us(m))}function A(m){const y=i.BYTES;m=Jt("private key",m,y);const x=Jt("hashed private key",s(m),2*y),$=d(x.slice(0,y)),E=x.slice(y,2*y),S=R($),F=v.multiply(S),N=F.toRawBytes();return{head:$,prefix:E,scalar:S,point:F,pointBytes:N}}function U(m){return A(m).pointBytes}function j(m=new Uint8Array,...y){const x=Wl(...y);return R(s(p(x,Jt("context",m),!!n)))}function B(m,y,x={}){m=Jt("message",m),n&&(m=n(m));const{prefix:$,scalar:E,pointBytes:S}=A(y),F=j(x.context,$,m),N=v.multiply(F).toRawBytes(),H=j(x.context,N,S,m),z=T(F+H*E);Gr("signature.s",z,$t,r);const q=Wl(N,Sa(z,i.BYTES));return Jt("result",q,i.BYTES*2)}const I=bb;function D(m,y,x,$=I){const{context:E,zip215:S}=$,F=i.BYTES;m=Jt("signature",m,2*F),y=Jt("message",y),x=Jt("publicKey",x,F),S!==void 0&&Co("zip215",S),n&&(y=n(y));const N=us(m.slice(F,2*F));let H,z,q;try{H=b.fromHex(x,S),z=b.fromHex(m.slice(0,F),S),q=v.multiplyUnsafe(N)}catch{return!1}if(!S&&H.isSmallOrder())return!1;const K=j(E,z.toRawBytes(),H.toRawBytes(),y);return z.add(H.multiplyUnsafe(K)).subtract(q).clearCofactor().equals(b.ZERO)}return v._setWindowSize(8),{CURVE:e,getPublicKey:U,sign:B,verify:D,ExtendedPoint:b,utils:{getExtendedPublicKey:A,randomPrivateKey:()=>o(i.BYTES),precompute(m=8,y=b.BASE){return y._setWindowSize(m),y.multiply(BigInt(3)),y}}}}BigInt(0),BigInt(1);const Dc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),Ql=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const xb=BigInt(1),eu=BigInt(2);BigInt(3);const Ib=BigInt(5),_b=BigInt(8);function Sb(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),n=BigInt(80),s=Dc,o=t*t%s*t%s,a=Ft(o,eu,s)*o%s,c=Ft(a,xb,s)*t%s,l=Ft(c,Ib,s)*c%s,u=Ft(l,e,s)*l%s,h=Ft(u,i,s)*u%s,f=Ft(h,r,s)*h%s,d=Ft(f,n,s)*f%s,p=Ft(d,n,s)*f%s,g=Ft(p,e,s)*l%s;return{pow_p_5_8:Ft(g,eu,s)*t%s,b2:o}}function $b(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Db(t,e){const i=Dc,r=xe(e*e*e,i),n=xe(r*r*e,i),s=Sb(t*n).pow_p_5_8;let o=xe(t*r*s,i);const a=xe(e*o*o,i),c=o,l=xe(o*Ql,i),u=a===t,h=a===xe(-t,i),f=a===xe(-t*Ql,i);return u&&(o=c),(h||f)&&(o=l),cb(o,i)&&(o=xe(-o,i)),{isValid:u||h,value:o}}const Ob=(()=>Td(Dc,void 0,!0))(),Ab=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Ob,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:_b,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:Z1,randomBytes:$d,adjustScalarBytes:$b,uvRatio:Db}))(),Nd=(()=>Eb(Ab))(),Pb="EdDSA",Cb="JWT",Ss=".",Vs="base64url",Ud="utf8",kd="utf8",Bb=":",Tb="did",Rb="key",tu="base58btc",Fb="z",Nb="K36",Ub=32;function Oc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function jd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Oc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Ld(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const i=jd(e);let r=0;for(const n of t)i.set(n,r),r+=n.length;return Oc(i)}function kb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(i[o]!==255)throw new TypeError(s+" is ambiguous");i[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,_=0,C=p.length;_!==C&&p[_]===0;)_++,g++;for(var b=(C-_)*u+1>>>0,v=new Uint8Array(b);_!==C;){for(var O=p[_],P=0,T=b-1;(O!==0||P<w)&&T!==-1;T--,P++)O+=256*v[T]>>>0,v[T]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=P,_++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,_=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=i[p.charCodeAt(g)];if(v===255)return;for(var O=0,P=C-1;(v!==0||O<_)&&P!==-1;P--,O++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=O,g++}if(p[g]!==" "){for(var T=C-_;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var jb=kb,Lb=jb;const Md=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")},Mb=t=>new TextEncoder().encode(t),qb=t=>new TextDecoder().decode(t);let zb=class{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Vb=class{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return qd(this,e)}},Hb=class{constructor(e){this.decoders=e}or(e){return qd(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const qd=(t,e)=>new Hb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Kb=class{constructor(e,i,r,n){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=n,this.encoder=new zb(e,i,r),this.decoder=new Vb(e,i,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Hs=({name:t,prefix:e,encode:i,decode:r})=>new Kb(t,e,i,r),Pn=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:n}=Lb(i,e);return Hs({prefix:t,name:e,encode:r,decode:s=>Md(n(s))})},Wb=(t,e,i,r)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*i/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const h=n[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|h,a+=i,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Gb=(t,e,i)=>{const r=e[e.length-1]==="=",n=(1<<i)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,s+=e[n&a>>o];if(o&&(s+=e[n&a<<i-o]),r)for(;s.length*i&7;)s+="=";return s},Fe=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>Hs({prefix:e,name:t,encode(n){return Gb(n,r,i)},decode(n){return Wb(n,r,i,t)}}),Yb=Hs({prefix:"\0",name:"identity",encode:t=>qb(t),decode:t=>Mb(t)});var Zb=Object.freeze({__proto__:null,identity:Yb});const Jb=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var Xb=Object.freeze({__proto__:null,base2:Jb});const Qb=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var ev=Object.freeze({__proto__:null,base8:Qb});const tv=Pn({prefix:"9",name:"base10",alphabet:"0123456789"});var iv=Object.freeze({__proto__:null,base10:tv});const rv=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),nv=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var sv=Object.freeze({__proto__:null,base16:rv,base16upper:nv});const ov=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),av=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),cv=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),lv=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),uv=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),hv=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),fv=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),dv=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),pv=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var gv=Object.freeze({__proto__:null,base32:ov,base32upper:av,base32pad:cv,base32padupper:lv,base32hex:uv,base32hexupper:hv,base32hexpad:fv,base32hexpadupper:dv,base32z:pv});const yv=Pn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),wv=Pn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var mv=Object.freeze({__proto__:null,base36:yv,base36upper:wv});const bv=Pn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),vv=Pn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var Ev=Object.freeze({__proto__:null,base58btc:bv,base58flickr:vv});const xv=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Iv=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),_v=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Sv=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var $v=Object.freeze({__proto__:null,base64:xv,base64pad:Iv,base64url:_v,base64urlpad:Sv});const zd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Dv=zd.reduce((t,e,i)=>(t[i]=e,t),[]),Ov=zd.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function Av(t){return t.reduce((e,i)=>(e+=Dv[i],e),"")}function Pv(t){const e=[];for(const i of t){const r=Ov[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const Cv=Hs({prefix:"🚀",name:"base256emoji",encode:Av,decode:Pv});var Bv=Object.freeze({__proto__:null,base256emoji:Cv}),Tv=Vd,iu=128,Rv=127,Fv=~Rv,Nv=Math.pow(2,31);function Vd(t,e,i){e=e||[],i=i||0;for(var r=i;t>=Nv;)e[i++]=t&255|iu,t/=128;for(;t&Fv;)e[i++]=t&255|iu,t>>>=7;return e[i]=t|0,Vd.bytes=i-r+1,e}var Uv=Da,kv=128,ru=127;function Da(t,r){var i=0,r=r||0,n=0,s=r,o,a=t.length;do{if(s>=a)throw Da.bytes=0,new RangeError("Could not decode varint");o=t[s++],i+=n<28?(o&ru)<<n:(o&ru)*Math.pow(2,n),n+=7}while(o>=kv);return Da.bytes=s-r,i}var jv=Math.pow(2,7),Lv=Math.pow(2,14),Mv=Math.pow(2,21),qv=Math.pow(2,28),zv=Math.pow(2,35),Vv=Math.pow(2,42),Hv=Math.pow(2,49),Kv=Math.pow(2,56),Wv=Math.pow(2,63),Gv=function(t){return t<jv?1:t<Lv?2:t<Mv?3:t<qv?4:t<zv?5:t<Vv?6:t<Hv?7:t<Kv?8:t<Wv?9:10},Yv={encode:Tv,decode:Uv,encodingLength:Gv},Hd=Yv;const nu=(t,e,i=0)=>(Hd.encode(t,e,i),e),su=t=>Hd.encodingLength(t),Oa=(t,e)=>{const i=e.byteLength,r=su(t),n=r+su(i),s=new Uint8Array(n+i);return nu(t,s,0),nu(i,s,r),s.set(e,n),new Zv(t,i,e,s)};let Zv=class{constructor(e,i,r,n){this.code=e,this.size=i,this.digest=r,this.bytes=n}};const Kd=({name:t,code:e,encode:i})=>new Jv(t,e,i);let Jv=class{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Oa(this.code,i):i.then(r=>Oa(this.code,r))}else throw Error("Unknown type, must be binary type")}};const Wd=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),Xv=Kd({name:"sha2-256",code:18,encode:Wd("SHA-256")}),Qv=Kd({name:"sha2-512",code:19,encode:Wd("SHA-512")});var e2=Object.freeze({__proto__:null,sha256:Xv,sha512:Qv});const Gd=0,t2="identity",Yd=Md,i2=t=>Oa(Gd,Yd(t)),r2={code:Gd,name:t2,encode:Yd,digest:i2};var n2=Object.freeze({__proto__:null,identity:r2});new TextEncoder,new TextDecoder;const ou={...Zb,...Xb,...ev,...iv,...sv,...gv,...mv,...Ev,...$v,...Bv};({...e2,...n2});function Zd(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const au=Zd("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Uo=Zd("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=jd(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),Jd={utf8:au,"utf-8":au,hex:ou.base16,latin1:Uo,ascii:Uo,binary:Uo,...ou};function Ks(t,e="utf8"){const i=Jd[e];if(!i)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"):i.encoder.encode(t).substring(1)}function Lr(t,e="utf8"){const i=Jd[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Oc(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function cu(t){return sr(Ks(Lr(t,Vs),Ud))}function $s(t){return Ks(Lr(ui(t),Ud),Vs)}function Xd(t){const e=Lr(Nb,tu),i=Fb+Ks(Ld([e,t]),tu);return[Tb,Rb,i].join(Bb)}function s2(t){return Ks(t,Vs)}function o2(t){return Lr(t,Vs)}function a2(t){return Lr([$s(t.header),$s(t.payload)].join(Ss),kd)}function c2(t){return[$s(t.header),$s(t.payload),s2(t.signature)].join(Ss)}function Aa(t){const e=t.split(Ss),i=cu(e[0]),r=cu(e[1]),n=o2(e[2]),s=Lr(e.slice(0,2).join(Ss),kd);return{header:i,payload:r,signature:n,data:s}}function lu(t=$d(Ub)){const e=Nd.getPublicKey(t);return{secretKey:Ld([t,e]),publicKey:e}}async function l2(t,e,i,r,n=L.fromMiliseconds(Date.now())){const s={alg:Pb,typ:Cb},o=Xd(r.publicKey),a=n+i,c={iss:o,sub:t,aud:e,iat:n,exp:a},l=a2({header:s,payload:c}),u=Nd.sign(l,r.secretKey.slice(0,32));return c2({header:s,payload:c,signature:u})}function Ac(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Qd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Ac(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fn(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const i=Qd(e);let r=0;for(const n of t)i.set(n,r),r+=n.length;return Ac(i)}function u2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(i[o]!==255)throw new TypeError(s+" is ambiguous");i[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,_=0,C=p.length;_!==C&&p[_]===0;)_++,g++;for(var b=(C-_)*u+1>>>0,v=new Uint8Array(b);_!==C;){for(var O=p[_],P=0,T=b-1;(O!==0||P<w)&&T!==-1;T--,P++)O+=256*v[T]>>>0,v[T]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=P,_++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,_=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=i[p.charCodeAt(g)];if(v===255)return;for(var O=0,P=C-1;(v!==0||O<_)&&P!==-1;P--,O++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=O,g++}if(p[g]!==" "){for(var T=C-_;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var h2=u2,f2=h2;const d2=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")},p2=t=>new TextEncoder().encode(t),g2=t=>new TextDecoder().decode(t);class y2{constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class w2{constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ep(this,e)}}class m2{constructor(e){this.decoders=e}or(e){return ep(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ep=(t,e)=>new m2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class b2{constructor(e,i,r,n){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=n,this.encoder=new y2(e,i,r),this.decoder=new w2(e,i,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Ws=({name:t,prefix:e,encode:i,decode:r})=>new b2(t,e,i,r),Cn=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:n}=f2(i,e);return Ws({prefix:t,name:e,encode:r,decode:s=>d2(n(s))})},v2=(t,e,i,r)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*i/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const h=n[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|h,a+=i,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},E2=(t,e,i)=>{const r=e[e.length-1]==="=",n=(1<<i)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,s+=e[n&a>>o];if(o&&(s+=e[n&a<<i-o]),r)for(;s.length*i&7;)s+="=";return s},Ne=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>Ws({prefix:e,name:t,encode(n){return E2(n,r,i)},decode(n){return v2(n,r,i,t)}}),x2=Ws({prefix:"\0",name:"identity",encode:t=>g2(t),decode:t=>p2(t)}),I2=Object.freeze(Object.defineProperty({__proto__:null,identity:x2},Symbol.toStringTag,{value:"Module"})),_2=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),S2=Object.freeze(Object.defineProperty({__proto__:null,base2:_2},Symbol.toStringTag,{value:"Module"})),$2=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),D2=Object.freeze(Object.defineProperty({__proto__:null,base8:$2},Symbol.toStringTag,{value:"Module"})),O2=Cn({prefix:"9",name:"base10",alphabet:"0123456789"}),A2=Object.freeze(Object.defineProperty({__proto__:null,base10:O2},Symbol.toStringTag,{value:"Module"})),P2=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),C2=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),B2=Object.freeze(Object.defineProperty({__proto__:null,base16:P2,base16upper:C2},Symbol.toStringTag,{value:"Module"})),T2=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),R2=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),F2=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),N2=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),U2=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),k2=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),j2=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),L2=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),M2=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),q2=Object.freeze(Object.defineProperty({__proto__:null,base32:T2,base32hex:U2,base32hexpad:j2,base32hexpadupper:L2,base32hexupper:k2,base32pad:F2,base32padupper:N2,base32upper:R2,base32z:M2},Symbol.toStringTag,{value:"Module"})),z2=Cn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),V2=Cn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),H2=Object.freeze(Object.defineProperty({__proto__:null,base36:z2,base36upper:V2},Symbol.toStringTag,{value:"Module"})),K2=Cn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),W2=Cn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),G2=Object.freeze(Object.defineProperty({__proto__:null,base58btc:K2,base58flickr:W2},Symbol.toStringTag,{value:"Module"})),Y2=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Z2=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),J2=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),X2=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),Q2=Object.freeze(Object.defineProperty({__proto__:null,base64:Y2,base64pad:Z2,base64url:J2,base64urlpad:X2},Symbol.toStringTag,{value:"Module"})),tp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),eE=tp.reduce((t,e,i)=>(t[i]=e,t),[]),tE=tp.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function iE(t){return t.reduce((e,i)=>(e+=eE[i],e),"")}function rE(t){const e=[];for(const i of t){const r=tE[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const nE=Ws({prefix:"🚀",name:"base256emoji",encode:iE,decode:rE}),sE=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:nE},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const uu={...I2,...S2,...D2,...A2,...B2,...q2,...H2,...G2,...Q2,...sE};function ip(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const hu=ip("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ko=ip("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=Qd(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),rp={utf8:hu,"utf-8":hu,hex:uu.base16,latin1:ko,ascii:ko,binary:ko,...uu};function Et(t,e="utf8"){const i=rp[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Ac(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}function nt(t,e="utf8"){const i=rp[e];if(!i)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"):i.encoder.encode(t).substring(1)}const oE={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"}},aE="Input must be an string, Buffer or Uint8Array";function cE(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(aE);return e}function lE(t){return Array.prototype.map.call(t,function(e){return(e<16?"0":"")+e.toString(16)}).join("")}function Kn(t){return(4294967296+t).toString(16).substring(1)}function uE(t,e,i){let r=`
|
|
16
|
+
`+t+" = ";for(let n=0;n<e.length;n+=2){if(i===32)r+=Kn(e[n]).toUpperCase(),r+=" ",r+=Kn(e[n+1]).toUpperCase();else if(i===64)r+=Kn(e[n+1]).toUpperCase(),r+=Kn(e[n]).toUpperCase();else throw new Error("Invalid size "+i);n%6===4?r+=`
|
|
17
|
+
`+new Array(t.length+4).join(" "):n<e.length-2&&(r+=" ")}console.log(r)}function hE(t,e,i){let r=new Date().getTime();const n=new Uint8Array(e);for(let o=0;o<e;o++)n[o]=o%256;const s=new Date().getTime();console.log("Generated random input in "+(s-r)+"ms"),r=s;for(let o=0;o<i;o++){const a=t(n),c=new Date().getTime(),l=c-r;r=c,console.log("Hashed in "+l+"ms: "+a.substring(0,20)+"..."),console.log(Math.round(e/(1<<20)/(l/1e3)*100)/100+" MB PER SECOND")}}var np={normalizeInput:cE,toHex:lE,debugPrint:uE,testSpeed:hE};const hs=np;function Wn(t,e,i){const r=t[e]+t[i];let n=t[e+1]+t[i+1];r>=4294967296&&n++,t[e]=r,t[e+1]=n}function fu(t,e,i,r){let n=t[e]+i;i<0&&(n+=4294967296);let s=t[e+1]+r;n>=4294967296&&s++,t[e]=n,t[e+1]=s}function sp(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function mi(t,e,i,r,n,s){const o=an[n],a=an[n+1],c=an[s],l=an[s+1];Wn(Z,t,e),fu(Z,t,o,a);let u=Z[r]^Z[t],h=Z[r+1]^Z[t+1];Z[r]=h,Z[r+1]=u,Wn(Z,i,r),u=Z[e]^Z[i],h=Z[e+1]^Z[i+1],Z[e]=u>>>24^h<<8,Z[e+1]=h>>>24^u<<8,Wn(Z,t,e),fu(Z,t,c,l),u=Z[r]^Z[t],h=Z[r+1]^Z[t+1],Z[r]=u>>>16^h<<16,Z[r+1]=h>>>16^u<<16,Wn(Z,i,r),u=Z[e]^Z[i],h=Z[e+1]^Z[i+1],Z[e]=h>>>31^u<<1,Z[e+1]=u>>>31^h<<1}const op=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),fE=[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],ke=new Uint8Array(fE.map(function(t){return t*2})),Z=new Uint32Array(32),an=new Uint32Array(32);function ap(t,e){let i=0;for(i=0;i<16;i++)Z[i]=t.h[i],Z[i+16]=op[i];for(Z[24]=Z[24]^t.t,Z[25]=Z[25]^t.t/4294967296,e&&(Z[28]=~Z[28],Z[29]=~Z[29]),i=0;i<32;i++)an[i]=sp(t.b,4*i);for(i=0;i<12;i++)mi(0,8,16,24,ke[i*16+0],ke[i*16+1]),mi(2,10,18,26,ke[i*16+2],ke[i*16+3]),mi(4,12,20,28,ke[i*16+4],ke[i*16+5]),mi(6,14,22,30,ke[i*16+6],ke[i*16+7]),mi(0,10,20,30,ke[i*16+8],ke[i*16+9]),mi(2,12,22,24,ke[i*16+10],ke[i*16+11]),mi(4,14,16,26,ke[i*16+12],ke[i*16+13]),mi(6,8,18,28,ke[i*16+14],ke[i*16+15]);for(i=0;i<16;i++)t.h[i]=t.h[i]^Z[i]^Z[i+16]}const bi=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 cp(t,e,i,r){if(t===0||t>64)throw new Error("Illegal output length, expected 0 < length <= 64");if(e&&e.length>64)throw new Error("Illegal key, expected Uint8Array with 0 < length <= 64");if(i&&i.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(r&&r.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const n={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};bi.fill(0),bi[0]=t,e&&(bi[1]=e.length),bi[2]=1,bi[3]=1,i&&bi.set(i,32),r&&bi.set(r,48);for(let s=0;s<16;s++)n.h[s]=op[s]^sp(bi,s*4);return e&&(Pc(n,e),n.c=128),n}function Pc(t,e){for(let i=0;i<e.length;i++)t.c===128&&(t.t+=t.c,ap(t,!1),t.c=0),t.b[t.c++]=e[i]}function lp(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;ap(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3);return e}function up(t,e,i,r,n){i=i||64,t=hs.normalizeInput(t),r&&(r=hs.normalizeInput(r)),n&&(n=hs.normalizeInput(n));const s=cp(i,e,r,n);return Pc(s,t),lp(s)}function dE(t,e,i,r,n){const s=up(t,e,i,r,n);return hs.toHex(s)}var pE={blake2b:up,blake2bHex:dE,blake2bInit:cp,blake2bUpdate:Pc,blake2bFinal:lp};const hp=np;function gE(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vi(t,e,i,r,n,s){se[t]=se[t]+se[e]+n,se[r]=Gn(se[r]^se[t],16),se[i]=se[i]+se[r],se[e]=Gn(se[e]^se[i],12),se[t]=se[t]+se[e]+s,se[r]=Gn(se[r]^se[t],8),se[i]=se[i]+se[r],se[e]=Gn(se[e]^se[i],7)}function Gn(t,e){return t>>>e^t<<32-e}const fp=new Uint32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),je=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]),se=new Uint32Array(16),Pe=new Uint32Array(16);function dp(t,e){let i=0;for(i=0;i<8;i++)se[i]=t.h[i],se[i+8]=fp[i];for(se[12]^=t.t,se[13]^=t.t/4294967296,e&&(se[14]=~se[14]),i=0;i<16;i++)Pe[i]=gE(t.b,4*i);for(i=0;i<10;i++)vi(0,4,8,12,Pe[je[i*16+0]],Pe[je[i*16+1]]),vi(1,5,9,13,Pe[je[i*16+2]],Pe[je[i*16+3]]),vi(2,6,10,14,Pe[je[i*16+4]],Pe[je[i*16+5]]),vi(3,7,11,15,Pe[je[i*16+6]],Pe[je[i*16+7]]),vi(0,5,10,15,Pe[je[i*16+8]],Pe[je[i*16+9]]),vi(1,6,11,12,Pe[je[i*16+10]],Pe[je[i*16+11]]),vi(2,7,8,13,Pe[je[i*16+12]],Pe[je[i*16+13]]),vi(3,4,9,14,Pe[je[i*16+14]],Pe[je[i*16+15]]);for(i=0;i<8;i++)t.h[i]^=se[i]^se[i+8]}function pp(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const i=e?e.length:0;if(e&&!(i>0&&i<=32))throw new Error("Incorrect key length, should be in [1, 32]");const r={h:new Uint32Array(fp),b:new Uint8Array(64),c:0,t:0,outlen:t};return r.h[0]^=16842752^i<<8^t,i>0&&(Cc(r,e),r.c=64),r}function Cc(t,e){for(let i=0;i<e.length;i++)t.c===64&&(t.t+=t.c,dp(t,!1),t.c=0),t.b[t.c++]=e[i]}function gp(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;dp(t,!0);const e=new Uint8Array(t.outlen);for(let i=0;i<t.outlen;i++)e[i]=t.h[i>>2]>>8*(i&3)&255;return e}function yp(t,e,i){i=i||32,t=hp.normalizeInput(t);const r=pp(i,e);return Cc(r,t),gp(r)}function yE(t,e,i){const r=yp(t,e,i);return hp.toHex(r)}var wE={blake2s:yp,blake2sHex:yE,blake2sInit:pp,blake2sUpdate:Cc,blake2sFinal:gp};const Yr=pE,Zr=wE;var mE={blake2b:Yr.blake2b,blake2bHex:Yr.blake2bHex,blake2bInit:Yr.blake2bInit,blake2bUpdate:Yr.blake2bUpdate,blake2bFinal:Yr.blake2bFinal,blake2s:Zr.blake2s,blake2sHex:Zr.blake2sHex,blake2sInit:Zr.blake2sInit,blake2sUpdate:Zr.blake2sUpdate,blake2sFinal:Zr.blake2sFinal},Gs={exports:{}};function bE(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var vE=EE;function EE(t,e,i){var r=i&&i.stringify||bE,n=1;if(typeof t=="object"&&t!==null){var s=e.length+n;if(s===1)return t;var o=new Array(s);o[0]=r(t);for(var a=1;a<s;a++)o[a]=r(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var l="",u=1-n,h=-1,f=t&&t.length||0,d=0;d<f;){if(t.charCodeAt(d)===37&&d+1<f){switch(h=h>-1?h:0,t.charCodeAt(d+1)){case 100:case 102:if(u>=c||e[u]==null)break;h<d&&(l+=t.slice(h,d)),l+=Number(e[u]),h=d+2,d++;break;case 105:if(u>=c||e[u]==null)break;h<d&&(l+=t.slice(h,d)),l+=Math.floor(Number(e[u])),h=d+2,d++;break;case 79:case 111:case 106:if(u>=c||e[u]===void 0)break;h<d&&(l+=t.slice(h,d));var p=typeof e[u];if(p==="string"){l+="'"+e[u]+"'",h=d+2,d++;break}if(p==="function"){l+=e[u].name||"<anonymous>",h=d+2,d++;break}l+=r(e[u]),h=d+2,d++;break;case 115:if(u>=c)break;h<d&&(l+=t.slice(h,d)),l+=String(e[u]),h=d+2,d++;break;case 37:h<d&&(l+=t.slice(h,d)),l+="%",h=d+2,d++,u--;break}++u}++d}return h===-1?t:(h<f&&(l+=t.slice(h)),l)}const du=vE;Gs.exports=hi;const En=NE().console||{},xE={mapHttpRequest:Yn,mapHttpResponse:Yn,wrapRequestSerializer:jo,wrapResponseSerializer:jo,wrapErrorSerializer:jo,req:Yn,res:Yn,err:gu,errWithCause:gu};function Ti(t,e){return t==="silent"?1/0:e.levels.values[t]}const Bc=Symbol("pino.logFuncs"),Pa=Symbol("pino.hierarchy"),IE={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function pu(t,e){const i={logger:e,parent:t[Pa]};e[Pa]=i}function _E(t,e,i){const r={};e.forEach(n=>{r[n]=i[n]?i[n]:En[n]||En[IE[n]||"log"]||Pr}),t[Bc]=r}function SE(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function hi(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 i=t.browser.write||En;t.browser.write&&(t.browser.asObject=!0);const r=t.serializers||{},n=SE(t.browser.serialize,r);let s=t.browser.serialize;Array.isArray(t.browser.serialize)&&t.browser.serialize.indexOf("!stdSerializers.err")>-1&&(s=!1);const o=Object.keys(t.customLevels||{}),a=["error","fatal","warn","info","debug","trace"].concat(o);typeof i=="function"&&a.forEach(function(g){i[g]=i}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(i);l.log||(l.log=Pr),_E(l,a,i),pu({},l),Object.defineProperty(l,"levelVal",{get:h}),Object.defineProperty(l,"level",{get:f,set:d});const u={transmit:e,serialize:n,asObject:t.browser.asObject,asObjectBindingsOnly:t.browser.asObjectBindingsOnly,formatters:t.browser.formatters,levels:a,timestamp:TE(t),messageKey:t.messageKey||"msg",onChild:t.onChild||Pr};l.levels=$E(t),l.level=c,l.isLevelEnabled=function(g){return this.levels.values[g]?this.levels.values[g]>=this.levels.values[this.level]:!1},l.setMaxListeners=l.getMaxListeners=l.emit=l.addListener=l.on=l.prependListener=l.once=l.prependOnceListener=l.removeListener=l.removeAllListeners=l.listeners=l.listenerCount=l.eventNames=l.write=l.flush=Pr,l.serializers=r,l._serialize=n,l._stdErrSerialize=s,l.child=function(...g){return p.call(this,u,...g)},e&&(l._logEvent=Ca());function h(){return Ti(this.level,this)}function f(){return this._level}function d(g){if(g!=="silent"&&!this.levels.values[g])throw Error("unknown level "+g);this._level=g,qi(this,u,l,"error"),qi(this,u,l,"fatal"),qi(this,u,l,"warn"),qi(this,u,l,"info"),qi(this,u,l,"debug"),qi(this,u,l,"trace"),o.forEach(w=>{qi(this,u,l,w)})}function p(g,w,_){if(!w)throw new Error("missing bindings for child Pino");_=_||{},n&&w.serializers&&(_.serializers=w.serializers);const C=_.serializers;if(n&&C){var b=Object.assign({},r,C),v=t.browser.serialize===!0?Object.keys(b):n;delete w.serializers,Tc([w],v,b,this._stdErrSerialize)}function O(T){this._childLevel=(T._childLevel|0)+1,this.bindings=w,b&&(this.serializers=b,this._serialize=v),e&&(this._logEvent=Ca([].concat(T._logEvent.bindings,w)))}O.prototype=this;const P=new O(this);return pu(this,P),P.child=function(...T){return p.call(this,g,...T)},P.level=_.level||this.level,g.onChild(P),P}return l}function $E(t){const e=t.customLevels||{},i=Object.assign({},hi.levels.values,e),r=Object.assign({},hi.levels.labels,DE(e));return{values:i,labels:r}}function DE(t){const e={};return Object.keys(t).forEach(function(i){e[t[i]]=i}),e}hi.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"}};hi.stdSerializers=xE;hi.stdTimeFunctions=Object.assign({},{nullTime:wp,epochTime:mp,unixTime:RE,isoTime:FE});function OE(t){const e=[];t.bindings&&e.push(t.bindings);let i=t[Pa];for(;i.parent;)i=i.parent,i.logger.bindings&&e.push(i.logger.bindings);return e.reverse()}function qi(t,e,i,r){if(Object.defineProperty(t,r,{value:Ti(t.level,i)>Ti(r,i)?Pr:i[Bc][r],writable:!0,enumerable:!0,configurable:!0}),t[r]===Pr){if(!e.transmit)return;const s=e.transmit.level||t.level,o=Ti(s,i);if(Ti(r,i)<o)return}t[r]=PE(t,e,i,r);const n=OE(t);n.length!==0&&(t[r]=AE(n,t[r]))}function AE(t,e){return function(){return e.apply(this,[...t,...arguments])}}function PE(t,e,i,r){return function(n){return function(){const o=e.timestamp(),a=new Array(arguments.length),c=Object.getPrototypeOf&&Object.getPrototypeOf(this)===En?En:this;for(var l=0;l<a.length;l++)a[l]=arguments[l];var u=!1;if(e.serialize&&(Tc(a,this._serialize,this.serializers,this._stdErrSerialize),u=!0),e.asObject||e.formatters?n.call(c,...CE(this,r,a,o,e)):n.apply(c,a),e.transmit){const h=e.transmit.level||t._level,f=Ti(h,i),d=Ti(r,i);if(d<f)return;BE(this,{ts:o,methodLevel:r,methodValue:d,transmitLevel:h,transmitValue:i.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Ti(t._level,i)},a,u)}}}(t[Bc][r])}function CE(t,e,i,r,n){const{level:s,log:o=h=>h}=n.formatters||{},a=i.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),r&&(l.time=r),s){const h=s(e,t.levels.values[e]);Object.assign(l,h)}else l.level=t.levels.values[e];if(n.asObjectBindingsOnly){if(c!==null&&typeof c=="object")for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());return[o(l),...a]}else{if(c!==null&&typeof c=="object"){for(;u--&&typeof a[0]=="object";)Object.assign(l,a.shift());c=a.length?du(a.shift(),a):void 0}else typeof c=="string"&&(c=du(a.shift(),a));return c!==void 0&&(l[n.messageKey]=c),[o(l)]}}function Tc(t,e,i,r){for(const n in t)if(r&&t[n]instanceof Error)t[n]=hi.stdSerializers.err(t[n]);else if(typeof t[n]=="object"&&!Array.isArray(t[n])&&e)for(const s in t[n])e.indexOf(s)>-1&&s in i&&(t[n][s]=i[s](t[n][s]))}function BE(t,e,i,r=!1){const n=e.send,s=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;r||Tc(i,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=i.filter(function(u){return l.indexOf(u)===-1}),t._logEvent.level.label=o,t._logEvent.level.value=a,n(o,t._logEvent,c),t._logEvent=Ca(l)}function Ca(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function gu(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const i in t)e[i]===void 0&&(e[i]=t[i]);return e}function TE(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?wp:mp}function Yn(){return{}}function jo(t){return t}function Pr(){}function wp(){return!1}function mp(){return Date.now()}function RE(){return Math.round(Date.now()/1e3)}function FE(){return new Date(Date.now()).toISOString()}function NE(){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)||{}}}Gs.exports.default=hi;Gs.exports.pino=hi;var _r=Gs.exports;const bp=D0(_r),UE={level:"info"},Ys="custom_context",Rc=1e3*1024;var kE=Object.defineProperty,jE=(t,e,i)=>e in t?kE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Pi=(t,e,i)=>jE(t,typeof e!="symbol"?e+"":e,i);let LE=class{constructor(e){Pi(this,"nodeValue"),Pi(this,"sizeInBytes"),Pi(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}},yu=class{constructor(e){Pi(this,"lengthInNodes"),Pi(this,"sizeInBytes"),Pi(this,"head"),Pi(this,"tail"),Pi(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const i=new LE(e);if(i.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${i.size}`);for(;this.size+i.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=i),this.tail=i):(this.head=i,this.tail=i),this.lengthInNodes++,this.sizeInBytes+=i.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 i=this.head;for(;i!==null;)e.push(i.value),i=i.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 i=e.value;return e=e.next,{done:!1,value:i}}}}};var ME=Object.defineProperty,qE=(t,e,i)=>e in t?ME(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Zn=(t,e,i)=>qE(t,typeof e!="symbol"?e+"":e,i);let vp=class{constructor(e,i=Rc){Zn(this,"logs"),Zn(this,"level"),Zn(this,"levelValue"),Zn(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=_r.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=i,this.logs=new yu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,i){i===_r.levels.values.error?console.error(e):i===_r.levels.values.warn?console.warn(e):i===_r.levels.values.debug?console.debug(e):i===_r.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(ui({timestamp:new Date().toISOString(),log:e}));const i=typeof e=="string"?JSON.parse(e).level:e.level;i>=this.levelValue&&this.forwardToConsole(e,i)}getLogs(){return this.logs}clearLogs(){this.logs=new yu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const i=this.getLogArray();return i.push(ui({extraMetadata:e})),new Blob(i,{type:"application/json"})}};var zE=Object.defineProperty,VE=(t,e,i)=>e in t?zE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,HE=(t,e,i)=>VE(t,typeof e!="symbol"?e+"":e,i);let KE=class{constructor(e,i=Rc){HE(this,"baseChunkLogger"),this.baseChunkLogger=new vp(e,i)}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 i=URL.createObjectURL(this.logsToBlob(e)),r=document.createElement("a");r.href=i,r.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(r),r.click(),document.body.removeChild(r),URL.revokeObjectURL(i)}};var WE=Object.defineProperty,GE=(t,e,i)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,YE=(t,e,i)=>GE(t,typeof e!="symbol"?e+"":e,i);let ZE=class{constructor(e,i=Rc){YE(this,"baseChunkLogger"),this.baseChunkLogger=new vp(e,i)}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 JE=Object.defineProperty,XE=Object.defineProperties,QE=Object.getOwnPropertyDescriptors,wu=Object.getOwnPropertySymbols,e3=Object.prototype.hasOwnProperty,t3=Object.prototype.propertyIsEnumerable,mu=(t,e,i)=>e in t?JE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ds=(t,e)=>{for(var i in e||(e={}))e3.call(e,i)&&mu(t,i,e[i]);if(wu)for(var i of wu(e))t3.call(e,i)&&mu(t,i,e[i]);return t},Os=(t,e)=>XE(t,QE(e));function i3(t){return Os(Ds({},t),{level:(t==null?void 0:t.level)||UE.level})}function r3(t,e,i=Ys){return t[i]=e,t}function st(t,e=Ys){return t[e]||""}function n3(t,e,i=Ys){const r=st(t,i);return r.trim()?`${r}/${e}`:e}function dt(t,e,i=Ys){const r=n3(t,e,i),n=t.child({context:r});return r3(n,r,i)}function s3(t){var e,i;const r=new KE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:bp(Os(Ds({},t.opts),{level:"trace",browser:Os(Ds({},(i=t.opts)==null?void 0:i.browser),{write:n=>r.write(n)})})),chunkLoggerController:r}}function o3(t){var e;const i=new ZE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:bp(Os(Ds({},t.opts),{level:"trace"}),i),chunkLoggerController:i}}function Ep(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?s3(t):o3(t)}const a3=":";function ci(t){const[e,i]=t.split(a3);return{namespace:e,reference:i}}function bu(t,e=[]){const i=[];return Object.keys(t).forEach(r=>{if(e.length&&!e.includes(r))return;const n=t[r];i.push(...n.accounts)}),i}function xp(t,e){return t.includes(":")?[t]:e.chains||[]}var c3=Object.defineProperty,l3=Object.defineProperties,u3=Object.getOwnPropertyDescriptors,vu=Object.getOwnPropertySymbols,h3=Object.prototype.hasOwnProperty,f3=Object.prototype.propertyIsEnumerable,Ba=(t,e,i)=>e in t?c3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Eu=(t,e)=>{for(var i in e||(e={}))h3.call(e,i)&&Ba(t,i,e[i]);if(vu)for(var i of vu(e))f3.call(e,i)&&Ba(t,i,e[i]);return t},d3=(t,e)=>l3(t,u3(e)),xu=(t,e,i)=>Ba(t,typeof e!="symbol"?e+"":e,i);const p3="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},g3="js";function As(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}function ki(){return!rr()&&!!uc()&&navigator.product===p3}function y3(){return ki()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="android"}function w3(){return ki()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="ios"}function Mr(){return!As()&&!!uc()&&!!rr()}function Bn(){return ki()?ft.reactNative:As()?ft.node:Mr()?ft.browser:ft.unknown}function Iu(){var t;try{return ki()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Application)<"u"?(t=Y.Application)==null?void 0:t.applicationId:void 0}catch{return}}function m3(t,e){const i=new URLSearchParams(t);return Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).forEach(([r,n])=>{n!=null&&i.set(r,String(n))}),i.toString()}function b3(t){var e,i;const r=Ip();try{return t!=null&&t.url&&r.url&&new URL(t.url).host!==new URL(r.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${r.url}. This is probably unintended and can lead to issues.`),t.url=r.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(n=>n!=="")),d3(Eu(Eu({},r),t),{url:(t==null?void 0:t.url)||r.url,name:(t==null?void 0:t.name)||r.name,description:(t==null?void 0:t.description)||r.description,icons:(i=t==null?void 0:t.icons)!=null&&i.length&&t.icons.length>0?t.icons:r.icons})}catch(n){return console.warn("Error populating app metadata",n),t||r}}function Ip(){return Ff()||{name:"",description:"",url:"",icons:[""]}}function v3(){if(Bn()===ft.reactNative&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"){const{OS:i,Version:r}=Y.Platform;return[i,r].join("-")}const t=U0();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 E3(){var t;const e=Bn();return e===ft.browser?[e,((t=Rf())==null?void 0:t.host)||"unknown"].join(":"):e}function _p(t,e,i){const r=v3(),n=E3();return[[t,e].join("-"),[g3,i].join("-"),r,n].join("/")}function x3({protocol:t,version:e,relayUrl:i,sdkVersion:r,auth:n,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=i.split("?"),u=_p(t,e,r),h={auth:n,ua:u,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=m3(l[1]||"",h);return l[0]+"?"+f}function Xi(t,e){return t.filter(i=>e.includes(i)).length===t.length}function Ta(t){return Object.fromEntries(t.entries())}function Ra(t){return new Map(Object.entries(t))}function Ki(t=L.FIVE_MINUTES,e){const i=L.toMiliseconds(t||L.FIVE_MINUTES);let r,n,s,o;return{resolve:a=>{s&&r&&(clearTimeout(s),r(a),o=Promise.resolve(a))},reject:a=>{s&&n&&(clearTimeout(s),n(a))},done:()=>new Promise((a,c)=>{if(o)return a(o);s=setTimeout(()=>{const l=new Error(e);o=Promise.reject(l),c(l)},i),r=a,n=c})}}function zt(t,e,i){return new Promise(async(r,n)=>{const s=setTimeout(()=>n(new Error(i)),e);try{const o=await t;r(o)}catch(o){n(o)}clearTimeout(s)})}function Sp(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 I3(t){return Sp("topic",t)}function _3(t){return Sp("id",t)}function $p(t){const[e,i]=t.split(":"),r={id:void 0,topic:void 0};if(e==="topic"&&typeof i=="string")r.topic=i;else if(e==="id"&&Number.isInteger(Number(i)))r.id=Number(i);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${i}`);return r}function we(t,e){return L.fromMiliseconds((e||Date.now())+L.toMiliseconds(t))}function qt(t){return Date.now()>=L.toMiliseconds(t)}function ae(t,e){return`${t}${e?`:${e}`:""}`}function Vt(t=[],e=[]){return[...new Set([...t,...e])]}async function S3({id:t,topic:e,wcDeepLink:i}){var r;try{if(!i)return;const n=typeof i=="string"?JSON.parse(i):i,s=n==null?void 0:n.href;if(typeof s!="string")return;const o=$3(s,t,e),a=Bn();if(a===ft.browser){if(!((r=rr())!=null&&r.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}D3(o)}else a===ft.reactNative&&typeof(Y==null?void 0:Y.Linking)<"u"&&await Y.Linking.openURL(o)}catch(n){console.error(n)}}function $3(t,e,i){const r=`requestId=${e}&sessionTopic=${i}`;t.endsWith("/")&&(t=t.slice(0,-1));let n=`${t}`;if(t.startsWith("https://t.me")){const s=t.includes("?")?"&startapp=":"?startapp=";n=`${n}${s}${C3(r,!0)}`}else n=`${n}/wc?${r}`;return n}function D3(t){let e="_self";P3()?e="_top":(A3()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function O3(t,e){let i="";try{if(Mr()&&(i=localStorage.getItem(e),i))return i;i=await t.getItem(e)}catch(r){console.error(r)}return i}function _u(t,e){if(!t.includes(e))return null;const i=t.split(/([&,?,=])/),r=i.indexOf(e);return i[r+2]}function Su(){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 Fc(){return typeof xt<"u"&&{}.IS_VITEST==="true"}function A3(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function P3(){try{return window.self!==window.top}catch{return!1}}function C3(t,e=!1){const i=ie.from(t).toString("base64");return e?i.replace(/[=]/g,""):i}function Dp(t){return ie.from(t,"base64").toString("utf-8")}function B3(t){return new Promise(e=>setTimeout(e,t))}let T3=class{constructor({limit:e}){xu(this,"limit"),xu(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const i=this.set.values().next().value;i&&this.set.delete(i)}this.set.add(e)}}has(e){return this.set.has(e)}};const Jn=BigInt(2**32-1),$u=BigInt(32);function Op(t,e=!1){return e?{h:Number(t&Jn),l:Number(t>>$u&Jn)}:{h:Number(t>>$u&Jn)|0,l:Number(t&Jn)|0}}function Ap(t,e=!1){const i=t.length;let r=new Uint32Array(i),n=new Uint32Array(i);for(let s=0;s<i;s++){const{h:o,l:a}=Op(t[s],e);[r[s],n[s]]=[o,a]}return[r,n]}const Du=(t,e,i)=>t>>>i,Ou=(t,e,i)=>t<<32-i|e>>>i,Di=(t,e,i)=>t>>>i|e<<32-i,Oi=(t,e,i)=>t<<32-i|e>>>i,cn=(t,e,i)=>t<<64-i|e>>>i-32,ln=(t,e,i)=>t>>>i-32|e<<64-i,R3=(t,e)=>e,F3=(t,e)=>t,N3=(t,e,i)=>t<<i|e>>>32-i,U3=(t,e,i)=>e<<i|t>>>32-i,k3=(t,e,i)=>e<<i-32|t>>>64-i,j3=(t,e,i)=>t<<i-32|e>>>64-i;function Pt(t,e,i,r){const n=(e>>>0)+(r>>>0);return{h:t+i+(n/2**32|0)|0,l:n|0}}const Nc=(t,e,i)=>(t>>>0)+(e>>>0)+(i>>>0),Uc=(t,e,i,r)=>e+i+r+(t/2**32|0)|0,L3=(t,e,i,r)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0),M3=(t,e,i,r,n)=>e+i+r+n+(t/2**32|0)|0,q3=(t,e,i,r,n)=>(t>>>0)+(e>>>0)+(i>>>0)+(r>>>0)+(n>>>0),z3=(t,e,i,r,n,s)=>e+i+r+n+s+(t/2**32|0)|0,mr=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;function Zs(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function fi(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function Tt(t,...e){if(!Zs(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 Js(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.createHasher");fi(t.outputLen),fi(t.blockLen)}function Ui(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 kc(t,e){Tt(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function xn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function _t(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Lo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Nt(t,e){return t<<32-e|t>>>e}const Pp=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Cp(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const ti=Pp?t=>t:t=>Cp(t);function V3(t){for(let e=0;e<t.length;e++)t[e]=Cp(t[e]);return t}const Ai=Pp?t=>t:V3,Bp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",H3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Cr(t){if(Tt(t),Bp)return t.toHex();let e="";for(let i=0;i<t.length;i++)e+=H3[t[i]];return e}const Xt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Au(t){if(t>=Xt._0&&t<=Xt._9)return t-Xt._0;if(t>=Xt.A&&t<=Xt.F)return t-(Xt.A-10);if(t>=Xt.a&&t<=Xt.f)return t-(Xt.a-10)}function Ps(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Bp)return Uint8Array.fromHex(t);const e=t.length,i=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const r=new Uint8Array(i);for(let n=0,s=0;n<i;n++,s+=2){const o=Au(t.charCodeAt(s)),a=Au(t.charCodeAt(s+1));if(o===void 0||a===void 0){const c=t[s]+t[s+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+s)}r[n]=o*16+a}return r}function Tp(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Bt(t){return typeof t=="string"&&(t=Tp(t)),Tt(t),t}function Ci(...t){let e=0;for(let r=0;r<t.length;r++){const n=t[r];Tt(n),e+=n.length}const i=new Uint8Array(e);for(let r=0,n=0;r<t.length;r++){const s=t[r];i.set(s,n),n+=s.length}return i}let Xs=class{};function Tn(t){const e=r=>t().update(Bt(r)).digest(),i=t();return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=()=>t(),e}function K3(t){const e=(r,n)=>t(n).update(Bt(r)).digest(),i=t({});return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}function lr(t=32){if(mr&&typeof mr.getRandomValues=="function")return mr.getRandomValues(new Uint8Array(t));if(mr&&typeof mr.randomBytes=="function")return Uint8Array.from(mr.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const W3=BigInt(0),Jr=BigInt(1),G3=BigInt(2),Y3=BigInt(7),Z3=BigInt(256),J3=BigInt(113),Rp=[],Fp=[],Np=[];for(let t=0,e=Jr,i=1,r=0;t<24;t++){[i,r]=[r,(2*i+3*r)%5],Rp.push(2*(5*r+i)),Fp.push((t+1)*(t+2)/2%64);let n=W3;for(let s=0;s<7;s++)e=(e<<Jr^(e>>Y3)*J3)%Z3,e&G3&&(n^=Jr<<(Jr<<BigInt(s))-Jr);Np.push(n)}const Up=Ap(Np,!0),X3=Up[0],Q3=Up[1],Pu=(t,e,i)=>i>32?k3(t,e,i):N3(t,e,i),Cu=(t,e,i)=>i>32?j3(t,e,i):U3(t,e,i);function ex(t,e=24){const i=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let o=0;o<10;o++)i[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=i[c],u=i[c+1],h=Pu(l,u,1)^i[a],f=Cu(l,u,1)^i[a+1];for(let d=0;d<50;d+=10)t[o+d]^=h,t[o+d+1]^=f}let n=t[2],s=t[3];for(let o=0;o<24;o++){const a=Fp[o],c=Pu(n,s,a),l=Cu(n,s,a),u=Rp[o];n=t[u],s=t[u+1],t[u]=c,t[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)i[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~i[(a+2)%10]&i[(a+4)%10]}t[0]^=X3[r],t[1]^=Q3[r]}_t(i)}let tx=class kp extends Xs{constructor(e,i,r,n=!1,s=24){if(super(),this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,this.enableXOF=!1,this.blockLen=e,this.suffix=i,this.outputLen=r,this.enableXOF=n,this.rounds=s,fi(r),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=xn(this.state)}clone(){return this._cloneInto()}keccak(){Ai(this.state32),ex(this.state32,this.rounds),Ai(this.state32),this.posOut=0,this.pos=0}update(e){Ui(this),e=Bt(e),Tt(e);const{blockLen:i,state:r}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(i-this.pos,n-s);for(let a=0;a<o;a++)r[this.pos++]^=e[s++];this.pos===i&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:i,pos:r,blockLen:n}=this;e[r]^=i,i&128&&r===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ui(this,!1),Tt(e),this.finish();const i=this.state,{blockLen:r}=this;for(let n=0,s=e.length;n<s;){this.posOut>=r&&this.keccak();const o=Math.min(r-this.posOut,s-n);e.set(i.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=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 fi(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(kc(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,_t(this.state)}_cloneInto(e){const{blockLen:i,suffix:r,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new kp(i,r,n,o,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}};const ix=(t,e,i)=>Tn(()=>new tx(e,t,i)),rx=ix(1,136,256/8);function nx(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const n=BigInt(32),s=BigInt(4294967295),o=Number(i>>n&s),a=Number(i&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function sx(t,e,i){return t&e^~t&i}function ox(t,e,i){return t&e^t&i^e&i}let jp=class extends Xs{constructor(e,i,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=i,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Lo(this.buffer)}update(e){Ui(this),e=Bt(e),Tt(e);const{view:i,buffer:r,blockLen:n}=this,s=e.length;for(let o=0;o<s;){const a=Math.min(n-this.pos,s-o);if(a===n){const c=Lo(e);for(;n<=s-o;o+=n)this.process(c,o);continue}r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(i,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ui(this),kc(e,this),this.finished=!0;const{buffer:i,view:r,blockLen:n,isLE:s}=this;let{pos:o}=this;i[o++]=128,_t(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let h=o;h<n;h++)i[h]=0;nx(r,n-8,BigInt(this.length*8),s),this.process(r,0);const a=Lo(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen should be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let h=0;h<l;h++)a.setUint32(4*h,u[h],s)}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:i,buffer:r,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%i&&e.buffer.set(r),e}clone(){return this._cloneInto()}};const Ei=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Le=Uint32Array.from([3418070365,3238371032,1654270250,914150663,2438529370,812702999,355462360,4144912697,1731405415,4290775857,2394180231,1750603025,3675008525,1694076839,1203062813,3204075428]),Me=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),ax=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]),xi=new Uint32Array(64);class cx extends jp{constructor(e=32){super(64,e,8,!1),this.A=Ei[0]|0,this.B=Ei[1]|0,this.C=Ei[2]|0,this.D=Ei[3]|0,this.E=Ei[4]|0,this.F=Ei[5]|0,this.G=Ei[6]|0,this.H=Ei[7]|0}get(){const{A:e,B:i,C:r,D:n,E:s,F:o,G:a,H:c}=this;return[e,i,r,n,s,o,a,c]}set(e,i,r,n,s,o,a,c){this.A=e|0,this.B=i|0,this.C=r|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,i){for(let h=0;h<16;h++,i+=4)xi[h]=e.getUint32(i,!1);for(let h=16;h<64;h++){const f=xi[h-15],d=xi[h-2],p=Nt(f,7)^Nt(f,18)^f>>>3,g=Nt(d,17)^Nt(d,19)^d>>>10;xi[h]=g+xi[h-7]+p+xi[h-16]|0}let{A:r,B:n,C:s,D:o,E:a,F:c,G:l,H:u}=this;for(let h=0;h<64;h++){const f=Nt(a,6)^Nt(a,11)^Nt(a,25),d=u+f+sx(a,c,l)+ax[h]+xi[h]|0,p=(Nt(r,2)^Nt(r,13)^Nt(r,22))+ox(r,n,s)|0;u=l,l=c,c=a,a=o+d|0,o=s,s=n,n=r,r=d+p|0}r=r+this.A|0,n=n+this.B|0,s=s+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(r,n,s,o,a,c,l,u)}roundClean(){_t(xi)}destroy(){this.set(0,0,0,0,0,0,0,0),_t(this.buffer)}}const Lp=Ap(["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))),lx=Lp[0],ux=Lp[1],Ii=new Uint32Array(80),_i=new Uint32Array(80);let jc=class extends jp{constructor(e=64){super(128,e,16,!1),this.Ah=Me[0]|0,this.Al=Me[1]|0,this.Bh=Me[2]|0,this.Bl=Me[3]|0,this.Ch=Me[4]|0,this.Cl=Me[5]|0,this.Dh=Me[6]|0,this.Dl=Me[7]|0,this.Eh=Me[8]|0,this.El=Me[9]|0,this.Fh=Me[10]|0,this.Fl=Me[11]|0,this.Gh=Me[12]|0,this.Gl=Me[13]|0,this.Hh=Me[14]|0,this.Hl=Me[15]|0}get(){const{Ah:e,Al:i,Bh:r,Bl:n,Ch:s,Cl:o,Dh:a,Dl:c,Eh:l,El:u,Fh:h,Fl:f,Gh:d,Gl:p,Hh:g,Hl:w}=this;return[e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w){this.Ah=e|0,this.Al=i|0,this.Bh=r|0,this.Bl=n|0,this.Ch=s|0,this.Cl=o|0,this.Dh=a|0,this.Dl=c|0,this.Eh=l|0,this.El=u|0,this.Fh=h|0,this.Fl=f|0,this.Gh=d|0,this.Gl=p|0,this.Hh=g|0,this.Hl=w|0}process(e,i){for(let b=0;b<16;b++,i+=4)Ii[b]=e.getUint32(i),_i[b]=e.getUint32(i+=4);for(let b=16;b<80;b++){const v=Ii[b-15]|0,O=_i[b-15]|0,P=Di(v,O,1)^Di(v,O,8)^Du(v,O,7),T=Oi(v,O,1)^Oi(v,O,8)^Ou(v,O,7),R=Ii[b-2]|0,A=_i[b-2]|0,U=Di(R,A,19)^cn(R,A,61)^Du(R,A,6),j=Oi(R,A,19)^ln(R,A,61)^Ou(R,A,6),B=L3(T,j,_i[b-7],_i[b-16]),I=M3(B,P,U,Ii[b-7],Ii[b-16]);Ii[b]=I|0,_i[b]=B|0}let{Ah:r,Al:n,Bh:s,Bl:o,Ch:a,Cl:c,Dh:l,Dl:u,Eh:h,El:f,Fh:d,Fl:p,Gh:g,Gl:w,Hh:_,Hl:C}=this;for(let b=0;b<80;b++){const v=Di(h,f,14)^Di(h,f,18)^cn(h,f,41),O=Oi(h,f,14)^Oi(h,f,18)^ln(h,f,41),P=h&d^~h&g,T=f&p^~f&w,R=q3(C,O,T,ux[b],_i[b]),A=z3(R,_,v,P,lx[b],Ii[b]),U=R|0,j=Di(r,n,28)^cn(r,n,34)^cn(r,n,39),B=Oi(r,n,28)^ln(r,n,34)^ln(r,n,39),I=r&s^r&a^s&a,D=n&o^n&c^o&c;_=g|0,C=w|0,g=d|0,w=p|0,d=h|0,p=f|0,{h,l:f}=Pt(l|0,u|0,A|0,U|0),l=a|0,u=c|0,a=s|0,c=o|0,s=r|0,o=n|0;const m=Nc(U,B,D);r=Uc(m,A,j,I),n=m|0}({h:r,l:n}=Pt(this.Ah|0,this.Al|0,r|0,n|0)),{h:s,l:o}=Pt(this.Bh|0,this.Bl|0,s|0,o|0),{h:a,l:c}=Pt(this.Ch|0,this.Cl|0,a|0,c|0),{h:l,l:u}=Pt(this.Dh|0,this.Dl|0,l|0,u|0),{h,l:f}=Pt(this.Eh|0,this.El|0,h|0,f|0),{h:d,l:p}=Pt(this.Fh|0,this.Fl|0,d|0,p|0),{h:g,l:w}=Pt(this.Gh|0,this.Gl|0,g|0,w|0),{h:_,l:C}=Pt(this.Hh|0,this.Hl|0,_|0,C|0),this.set(r,n,s,o,a,c,l,u,h,f,d,p,g,w,_,C)}roundClean(){_t(Ii,_i)}destroy(){_t(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class hx extends jc{constructor(){super(48),this.Ah=Le[0]|0,this.Al=Le[1]|0,this.Bh=Le[2]|0,this.Bl=Le[3]|0,this.Ch=Le[4]|0,this.Cl=Le[5]|0,this.Dh=Le[6]|0,this.Dl=Le[7]|0,this.Eh=Le[8]|0,this.El=Le[9]|0,this.Fh=Le[10]|0,this.Fl=Le[11]|0,this.Gh=Le[12]|0,this.Gl=Le[13]|0,this.Hh=Le[14]|0,this.Hl=Le[15]|0}}const qe=Uint32Array.from([573645204,4230739756,2673172387,3360449730,596883563,1867755857,2520282905,1497426621,2519219938,2827943907,3193839141,1401305490,721525244,746961066,246885852,2177182882]);class fx extends jc{constructor(){super(32),this.Ah=qe[0]|0,this.Al=qe[1]|0,this.Bh=qe[2]|0,this.Bl=qe[3]|0,this.Ch=qe[4]|0,this.Cl=qe[5]|0,this.Dh=qe[6]|0,this.Dl=qe[7]|0,this.Eh=qe[8]|0,this.El=qe[9]|0,this.Fh=qe[10]|0,this.Fl=qe[11]|0,this.Gh=qe[12]|0,this.Gl=qe[13]|0,this.Hh=qe[14]|0,this.Hl=qe[15]|0}}const Qs=Tn(()=>new cx),dx=Tn(()=>new jc),px=Tn(()=>new hx),gx=Tn(()=>new fx),yx=Uint8Array.from([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9,12,5,1,15,14,13,4,10,0,7,6,3,9,2,8,11,13,11,7,14,12,1,3,9,5,0,15,4,8,6,2,10,6,15,14,9,11,3,0,8,12,2,13,7,1,4,10,5,10,2,8,4,7,6,1,5,15,11,9,14,3,12,13,0,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,10,4,8,9,15,13,6,1,12,0,2,11,7,5,3,11,8,12,0,5,2,15,13,10,14,3,6,7,1,9,4,7,9,3,1,13,12,11,14,2,6,5,10,4,0,15,8,9,0,5,7,2,4,10,15,14,1,11,12,6,8,3,13,2,12,6,10,0,11,8,3,4,13,7,5,15,14,1,9]),Ee=Uint32Array.from([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),V=new Uint32Array(32);function Si(t,e,i,r,n,s){const o=n[s],a=n[s+1];let c=V[2*t],l=V[2*t+1],u=V[2*e],h=V[2*e+1],f=V[2*i],d=V[2*i+1],p=V[2*r],g=V[2*r+1],w=Nc(c,u,o);l=Uc(w,l,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:R3(g,p),Dl:F3(g)},{h:d,l:f}=Pt(d,f,g,p),{Bh:h,Bl:u}={Bh:h^d,Bl:u^f},{Bh:h,Bl:u}={Bh:Di(h,u,24),Bl:Oi(h,u,24)},V[2*t]=c,V[2*t+1]=l,V[2*e]=u,V[2*e+1]=h,V[2*i]=f,V[2*i+1]=d,V[2*r]=p,V[2*r+1]=g}function $i(t,e,i,r,n,s){const o=n[s],a=n[s+1];let c=V[2*t],l=V[2*t+1],u=V[2*e],h=V[2*e+1],f=V[2*i],d=V[2*i+1],p=V[2*r],g=V[2*r+1],w=Nc(c,u,o);l=Uc(w,l,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:Di(g,p,16),Dl:Oi(g,p,16)},{h:d,l:f}=Pt(d,f,g,p),{Bh:h,Bl:u}={Bh:h^d,Bl:u^f},{Bh:h,Bl:u}={Bh:cn(h,u,63),Bl:ln(h,u,63)},V[2*t]=c,V[2*t+1]=l,V[2*e]=u,V[2*e+1]=h,V[2*i]=f,V[2*i+1]=d,V[2*r]=p,V[2*r+1]=g}function wx(t,e={},i,r,n){if(fi(i),t<0||t>i)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>i))throw new Error("key length must be undefined or 1.."+i);if(o!==void 0&&o.length!==r)throw new Error("salt must be undefined or "+r);if(a!==void 0&&a.length!==n)throw new Error("personalization must be undefined or "+n)}class mx extends Xs{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,fi(e),fi(i),this.blockLen=e,this.outputLen=i,this.buffer=new Uint8Array(e),this.buffer32=xn(this.buffer)}update(e){Ui(this),e=Bt(e),Tt(e);const{blockLen:i,buffer:r,buffer32:n}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===i&&(Ai(n),this.compress(n,0,!1),Ai(n),this.pos=0);const l=Math.min(i-this.pos,s-c),u=o+c;if(l===i&&!(u%4)&&c+l<s){const h=new Uint32Array(a,u,Math.floor((s-c)/4));Ai(h);for(let f=0;c+i<s;f+=n.length,c+=i)this.length+=i,this.compress(h,f,!1);Ai(h);continue}r.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Ui(this),kc(e,this);const{pos:i,buffer32:r}=this;this.finished=!0,_t(this.buffer.subarray(i)),Ai(r),this.compress(r,0,!0),Ai(r);const n=xn(e);this.get().forEach((s,o)=>n[o]=ti(s))}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}_cloneInto(e){const{buffer:i,length:r,finished:n,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(i),e.destroyed=s,e.finished=n,e.length=r,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class bx extends mx{constructor(e={}){const i=e.dkLen===void 0?64:e.dkLen;super(128,i),this.v0l=Ee[0]|0,this.v0h=Ee[1]|0,this.v1l=Ee[2]|0,this.v1h=Ee[3]|0,this.v2l=Ee[4]|0,this.v2h=Ee[5]|0,this.v3l=Ee[6]|0,this.v3h=Ee[7]|0,this.v4l=Ee[8]|0,this.v4h=Ee[9]|0,this.v5l=Ee[10]|0,this.v5h=Ee[11]|0,this.v6l=Ee[12]|0,this.v6h=Ee[13]|0,this.v7l=Ee[14]|0,this.v7h=Ee[15]|0,wx(i,e,64,16,16);let{key:r,personalization:n,salt:s}=e,o=0;if(r!==void 0&&(r=Bt(r),o=r.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Bt(s);const a=xn(s);this.v4l^=ti(a[0]),this.v4h^=ti(a[1]),this.v5l^=ti(a[2]),this.v5h^=ti(a[3])}if(n!==void 0){n=Bt(n);const a=xn(n);this.v6l^=ti(a[0]),this.v6h^=ti(a[1]),this.v7l^=ti(a[2]),this.v7h^=ti(a[3])}if(r!==void 0){const a=new Uint8Array(this.blockLen);a.set(r),this.update(a)}}get(){let{v0l:e,v0h:i,v1l:r,v1h:n,v2l:s,v2h:o,v3l:a,v3h:c,v4l:l,v4h:u,v5l:h,v5h:f,v6l:d,v6h:p,v7l:g,v7h:w}=this;return[e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,i,r,n,s,o,a,c,l,u,h,f,d,p,g,w){this.v0l=e|0,this.v0h=i|0,this.v1l=r|0,this.v1h=n|0,this.v2l=s|0,this.v2h=o|0,this.v3l=a|0,this.v3h=c|0,this.v4l=l|0,this.v4h=u|0,this.v5l=h|0,this.v5h=f|0,this.v6l=d|0,this.v6h=p|0,this.v7l=g|0,this.v7h=w|0}compress(e,i,r){this.get().forEach((c,l)=>V[l]=c),V.set(Ee,16);let{h:n,l:s}=Op(BigInt(this.length));V[24]=Ee[8]^s,V[25]=Ee[9]^n,r&&(V[28]=~V[28],V[29]=~V[29]);let o=0;const a=yx;for(let c=0;c<12;c++)Si(0,4,8,12,e,i+2*a[o++]),$i(0,4,8,12,e,i+2*a[o++]),Si(1,5,9,13,e,i+2*a[o++]),$i(1,5,9,13,e,i+2*a[o++]),Si(2,6,10,14,e,i+2*a[o++]),$i(2,6,10,14,e,i+2*a[o++]),Si(3,7,11,15,e,i+2*a[o++]),$i(3,7,11,15,e,i+2*a[o++]),Si(0,5,10,15,e,i+2*a[o++]),$i(0,5,10,15,e,i+2*a[o++]),Si(1,6,11,12,e,i+2*a[o++]),$i(1,6,11,12,e,i+2*a[o++]),Si(2,7,8,13,e,i+2*a[o++]),$i(2,7,8,13,e,i+2*a[o++]),Si(3,4,9,14,e,i+2*a[o++]),$i(3,4,9,14,e,i+2*a[o++]);this.v0l^=V[0]^V[16],this.v0h^=V[1]^V[17],this.v1l^=V[2]^V[18],this.v1h^=V[3]^V[19],this.v2l^=V[4]^V[20],this.v2h^=V[5]^V[21],this.v3l^=V[6]^V[22],this.v3h^=V[7]^V[23],this.v4l^=V[8]^V[24],this.v4h^=V[9]^V[25],this.v5l^=V[10]^V[26],this.v5h^=V[11]^V[27],this.v6l^=V[12]^V[28],this.v6h^=V[13]^V[29],this.v7l^=V[14]^V[30],this.v7h^=V[15]^V[31],_t(V)}destroy(){this.destroyed=!0,_t(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const vx=K3(t=>new bx(t)),Ex="https://rpc.walletconnect.org/v1";function Mp(t){const e=`Ethereum Signed Message:
|
|
18
|
+
${t.length}`,i=new TextEncoder().encode(e+t);return"0x"+ie.from(rx(i)).toString("hex")}async function xx(t,e,i,r,n,s){switch(i.t){case"eip191":return await Ix(t,e,i.s);case"eip1271":return await _x(t,e,i.s,r,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${i.t}`)}}function Ix(t,e,i){const r=mm(i);return Im({payload:Mp(e),signature:r}).toLowerCase()===t.toLowerCase()}async function _x(t,e,i,r,n,s){const o=ci(r);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${r}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=i.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Mp(e)).substring(2),f=a+h+c+u+l,d=await fetch(`${s||Ex}/?chainId=${r}&projectId=${n}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Sx(),jsonrpc:"2.0",method:"eth_call",params:[{to:t,data:f},"latest"]})}),{result:p}=await d.json();return p?p.slice(0,a.length).toLowerCase()===a.toLowerCase():!1}catch(a){return console.error("isValidEip1271Signature: ",a),!1}}function Sx(){return Date.now()+Math.floor(Math.random()*1e3)}function $x(t){const e=atob(t),i=new Uint8Array(e.length);for(let o=0;o<e.length;o++)i[o]=e.charCodeAt(o);const r=i[0];if(r===0)throw new Error("No signatures found");const n=1+r*64;if(i.length<n)throw new Error("Transaction data too short for claimed signature count");if(i.length<100)throw new Error("Transaction too short");const s=ie.from(t,"base64").slice(1,65);return An.encode(s)}function Dx(t){const e=new Uint8Array(ie.from(t,"base64")),i=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),r=new Uint8Array(i.length+e.length);r.set(i),r.set(e,i.length);const n=vx(r,{dkLen:32});return An.encode(n)}function Bu(t){const e=new Uint8Array(Qs(Ox(t)));return An.encode(e)}function Ox(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 Tu(t){const e=ie.from(t,"base64"),i=c1(e).txn;if(!i)throw new Error("Invalid signed transaction: missing 'txn' field");const r=Qm(i),n=ie.from("TX"),s=ie.concat([n,ie.from(r)]),o=gx(s);return y1.encode(o).replace(/=+$/,"")}function Mo(t){const e=[];let i=BigInt(t);for(;i>=BigInt(128);)e.push(Number(i&BigInt(127)|BigInt(128))),i>>=BigInt(7);return e.push(Number(i)),ie.from(e)}function Ax(t){const e=ie.from(t.signed.bodyBytes,"base64"),i=ie.from(t.signed.authInfoBytes,"base64"),r=ie.from(t.signature.signature,"base64"),n=[];n.push(ie.from([10])),n.push(Mo(e.length)),n.push(e),n.push(ie.from([18])),n.push(Mo(i.length)),n.push(i),n.push(ie.from([26])),n.push(Mo(r.length)),n.push(r);const s=ie.concat(n),o=Qs(s);return ie.from(o).toString("hex").toUpperCase()}function Px(t){var e,i;const r=[];try{if(typeof t=="string")return r.push(t),r;if(typeof t!="object")return r;t!=null&&t.id&&r.push(t.id);const n=(i=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:i.transactionHashes;n&&r.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return r}var Cx=Object.defineProperty,Bx=Object.defineProperties,Tx=Object.getOwnPropertyDescriptors,Ru=Object.getOwnPropertySymbols,Rx=Object.prototype.hasOwnProperty,Fx=Object.prototype.propertyIsEnumerable,Fu=(t,e,i)=>e in t?Cx(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Nx=(t,e)=>{for(var i in e||(e={}))Rx.call(e,i)&&Fu(t,i,e[i]);if(Ru)for(var i of Ru(e))Fx.call(e,i)&&Fu(t,i,e[i]);return t},Ux=(t,e)=>Bx(t,Tx(e));const qp="did:pkh:",kx={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},jx=t=>t?kx[t]||t:"",eo=t=>t==null?void 0:t.split(":"),Lx=t=>{const e=t&&eo(t);if(e)return t.includes(qp)?e[3]:e[1]},Mx=t=>{const e=t&&eo(t);if(e)return t.includes(qp)?e[2]:e[0]},Fa=t=>{const e=t&&eo(t);if(e)return e[2]+":"+e[3]},Cs=t=>{const e=t&&eo(t);if(e)return e.pop()};async function Nu(t){const{cacao:e,projectId:i}=t,{s:r,p:n}=e,s=zp(n,n.iss),o=Cs(n.iss);return await xx(o,s,r,Fa(n.iss),i)}const zp=(t,e)=>{const i=Mx(e);if(!i)throw new Error("Invalid issuer: "+e);const r=`${t.domain} wants you to sign in with your ${jx(i)} account:`,n=Cs(e);if(!t.aud&&!t.uri)throw new Error("Either `aud` or `uri` is required to construct the message");let s=t.statement||void 0;const o=`URI: ${t.aud||t.uri}`,a=`Version: ${t.version}`,c=`Chain ID: ${Lx(e)}`,l=`Nonce: ${t.nonce}`,u=`Issued At: ${t.iat}`,h=t.exp?`Expiration Time: ${t.exp}`:void 0,f=t.nbf?`Not Before: ${t.nbf}`:void 0,d=t.requestId?`Request ID: ${t.requestId}`:void 0,p=t.resources?`Resources:${t.resources.map(w=>`
|
|
19
|
+
- ${w}`).join("")}`:void 0,g=fs(t.resources);if(g){const w=In(g);s=Zx(s,w)}return[r,n,"",s,"",o,a,c,l,u,h,f,d,p].filter(w=>w!=null).join(`
|
|
20
|
+
`)};function qx(t){return ie.from(JSON.stringify(t)).toString("base64")}function zx(t){return JSON.parse(ie.from(t,"base64").toString("utf-8"))}function or(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(i=>{const r=t.att[i];if(Array.isArray(r))throw new Error(`Resource must be an object: ${i}`);if(typeof r!="object")throw new Error(`Resource must be an object: ${i}`);if(!Object.keys(r).length)throw new Error(`Resource object is empty: ${i}`);Object.keys(r).forEach(n=>{const s=r[n];if(!Array.isArray(s))throw new Error(`Ability limits ${n} must be an array of objects, found: ${s}`);if(!s.length)throw new Error(`Value of ${n} is empty array, must be an array with objects`);s.forEach(o=>{if(typeof o!="object")throw new Error(`Ability limits (${n}) must be an array of objects, found: ${o}`)})})})}function Vx(t,e,i,r={}){return i==null||i.sort((n,s)=>n.localeCompare(s)),{att:{[t]:Hx(e,i,r)}}}function Hx(t,e,i={}){e=e==null?void 0:e.sort((n,s)=>n.localeCompare(s));const r=e.map(n=>({[`${t}/${n}`]:[i]}));return Object.assign({},...r)}function Vp(t){return or(t),`urn:recap:${qx(t).replace(/=/g,"")}`}function In(t){const e=zx(t.replace("urn:recap:",""));return or(e),e}function Kx(t,e,i){const r=Vx(t,e,i);return Vp(r)}function Wx(t){return t&&t.includes("urn:recap:")}function Gx(t,e){const i=In(t),r=In(e),n=Yx(i,r);return Vp(n)}function Yx(t,e){or(t),or(e);const i=Object.keys(t.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),r={att:{}};return i.forEach(n=>{var s,o;Object.keys(((s=t.att)==null?void 0:s[n])||{}).concat(Object.keys(((o=e.att)==null?void 0:o[n])||{})).sort((a,c)=>a.localeCompare(c)).forEach(a=>{var c,l;r.att[n]=Ux(Nx({},r.att[n]),{[a]:((c=t.att[n])==null?void 0:c[a])||((l=e.att[n])==null?void 0:l[a])})})}),r}function Zx(t="",e){or(e);const i="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(i))return t;const r=[];let n=0;Object.keys(e.att).forEach(a=>{const c=Object.keys(e.att[a]).map(h=>({ability:h.split("/")[0],action:h.split("/")[1]}));c.sort((h,f)=>h.action.localeCompare(f.action));const l={};c.forEach(h=>{l[h.ability]||(l[h.ability]=[]),l[h.ability].push(h.action)});const u=Object.keys(l).map(h=>(n++,`(${n}) '${h}': '${l[h].join("', '")}' for '${a}'.`));r.push(u.join(", ").replace(".,","."))});const s=r.join(" "),o=`${i}${s}`;return`${t?t+" ":""}${o}`}function Uu(t){var e;const i=In(t);or(i);const r=(e=i.att)==null?void 0:e.eip155;return r?Object.keys(r).map(n=>n.split("/")[1]):[]}function ku(t){const e=In(t);or(e);const i=[];return Object.values(e.att).forEach(r=>{Object.values(r).forEach(n=>{var s;(s=n==null?void 0:n[0])!=null&&s.chains&&i.push(n[0].chains)})}),[...new Set(i.flat())]}function fs(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return Wx(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Hp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Na(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function qo(t){if(!Number.isSafeInteger(t)||t<0)throw new Error("positive integer expected, got "+t)}function et(t,...e){if(!Hp(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 ju(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 Jx(t,e){et(t);const i=e.outputLen;if(t.length<i)throw new Error("digestInto() expects output buffer of length at least "+i)}function Fi(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ur(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Xx(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const Qx=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function eI(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function Ua(t){if(typeof t=="string")t=eI(t);else if(Hp(t))t=ka(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function tI(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function iI(t,e){if(t.length!==e.length)return!1;let i=0;for(let r=0;r<t.length;r++)i|=t[r]^e[r];return i===0}const rI=(t,e)=>{function i(r,...n){if(et(r),!Qx)throw new Error("Non little-endian hardware is not yet supported");if(t.nonceLength!==void 0){const l=n[0];if(!l)throw new Error("nonce / iv required");t.varSizeNonce?et(l):et(l,t.nonceLength)}const s=t.tagLength;s&&n[1]!==void 0&&et(n[1]);const o=e(r,...n),a=(l,u)=>{if(u!==void 0){if(l!==2)throw new Error("cipher output not supported");et(u)}};let c=!1;return{encrypt(l,u){if(c)throw new Error("cannot encrypt() twice with same key + nonce");return c=!0,et(l),a(o.encrypt.length,u),o.encrypt(l,u)},decrypt(l,u){if(et(l),s&&l.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return a(o.decrypt.length,u),o.decrypt(l,u)}}}return Object.assign(i,t),i};function Lu(t,e,i=!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(i&&!sI(e))throw new Error("invalid output, must be aligned");return e}function Mu(t,e,i,r){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,i,r);const n=BigInt(32),s=BigInt(4294967295),o=Number(i>>n&s),a=Number(i&s),c=r?4:0,l=r?0:4;t.setUint32(e+c,o,r),t.setUint32(e+l,a,r)}function nI(t,e,i){Na(i);const r=new Uint8Array(16),n=Xx(r);return Mu(n,0,BigInt(e),i),Mu(n,8,BigInt(t),i),r}function sI(t){return t.byteOffset%4===0}function ka(t){return Uint8Array.from(t)}const Kp=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),oI=Kp("expand 16-byte k"),aI=Kp("expand 32-byte k"),cI=Fi(oI),lI=Fi(aI);function re(t,e){return t<<e|t>>>32-e}function ja(t){return t.byteOffset%4===0}const Xn=64,uI=16,Wp=2**32-1,qu=new Uint32Array;function hI(t,e,i,r,n,s,o,a){const c=n.length,l=new Uint8Array(Xn),u=Fi(l),h=ja(n)&&ja(s),f=h?Fi(n):qu,d=h?Fi(s):qu;for(let p=0;p<c;o++){if(t(e,i,r,u,o,a),o>=Wp)throw new Error("arx: counter overflow");const g=Math.min(Xn,c-p);if(h&&g===Xn){const w=p/4;if(p%4!==0)throw new Error("arx: invalid block position");for(let _=0,C;_<uI;_++)C=w+_,d[C]=f[C]^u[_];p+=Xn;continue}for(let w=0,_;w<g;w++)_=p+w,s[_]=n[_]^l[w];p+=g}}function fI(t,e){const{allowShortKeys:i,extendNonceFn:r,counterLength:n,counterRight:s,rounds:o}=tI({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},e);if(typeof t!="function")throw new Error("core must be a function");return qo(n),qo(o),Na(s),Na(i),(a,c,l,u,h=0)=>{et(a),et(c),et(l);const f=l.length;if(u===void 0&&(u=new Uint8Array(f)),et(u),qo(h),h<0||h>=Wp)throw new Error("arx: counter overflow");if(u.length<f)throw new Error(`arx: output (${u.length}) is shorter than data (${f})`);const d=[];let p=a.length,g,w;if(p===32)d.push(g=ka(a)),w=lI;else if(p===16&&i)g=new Uint8Array(32),g.set(a),g.set(a,16),w=cI,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);ja(c)||d.push(c=ka(c));const _=Fi(g);if(r){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");r(w,_,Fi(c.subarray(0,16)),_),c=c.subarray(16)}const C=16-n;if(C!==c.length)throw new Error(`arx: nonce must be ${C} or 16 bytes`);if(C!==12){const v=new Uint8Array(12);v.set(c,s?0:12-c.length),c=v,d.push(c)}const b=Fi(c);return hI(t,w,_,b,l,u,h,o),Ur(...d),u}}const Ce=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class dI{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=Ua(e),et(e,32);const i=Ce(e,0),r=Ce(e,2),n=Ce(e,4),s=Ce(e,6),o=Ce(e,8),a=Ce(e,10),c=Ce(e,12),l=Ce(e,14);this.r[0]=i&8191,this.r[1]=(i>>>13|r<<3)&8191,this.r[2]=(r>>>10|n<<6)&7939,this.r[3]=(n>>>7|s<<9)&8191,this.r[4]=(s>>>4|o<<12)&255,this.r[5]=o>>>1&8190,this.r[6]=(o>>>14|a<<2)&8191,this.r[7]=(a>>>11|c<<5)&8065,this.r[8]=(c>>>8|l<<8)&8191,this.r[9]=l>>>5&127;for(let u=0;u<8;u++)this.pad[u]=Ce(e,16+2*u)}process(e,i,r=!1){const n=r?0:2048,{h:s,r:o}=this,a=o[0],c=o[1],l=o[2],u=o[3],h=o[4],f=o[5],d=o[6],p=o[7],g=o[8],w=o[9],_=Ce(e,i+0),C=Ce(e,i+2),b=Ce(e,i+4),v=Ce(e,i+6),O=Ce(e,i+8),P=Ce(e,i+10),T=Ce(e,i+12),R=Ce(e,i+14);let A=s[0]+(_&8191),U=s[1]+((_>>>13|C<<3)&8191),j=s[2]+((C>>>10|b<<6)&8191),B=s[3]+((b>>>7|v<<9)&8191),I=s[4]+((v>>>4|O<<12)&8191),D=s[5]+(O>>>1&8191),m=s[6]+((O>>>14|P<<2)&8191),y=s[7]+((P>>>11|T<<5)&8191),x=s[8]+((T>>>8|R<<8)&8191),$=s[9]+(R>>>5|n),E=0,S=E+A*a+U*(5*w)+j*(5*g)+B*(5*p)+I*(5*d);E=S>>>13,S&=8191,S+=D*(5*f)+m*(5*h)+y*(5*u)+x*(5*l)+$*(5*c),E+=S>>>13,S&=8191;let F=E+A*c+U*a+j*(5*w)+B*(5*g)+I*(5*p);E=F>>>13,F&=8191,F+=D*(5*d)+m*(5*f)+y*(5*h)+x*(5*u)+$*(5*l),E+=F>>>13,F&=8191;let N=E+A*l+U*c+j*a+B*(5*w)+I*(5*g);E=N>>>13,N&=8191,N+=D*(5*p)+m*(5*d)+y*(5*f)+x*(5*h)+$*(5*u),E+=N>>>13,N&=8191;let H=E+A*u+U*l+j*c+B*a+I*(5*w);E=H>>>13,H&=8191,H+=D*(5*g)+m*(5*p)+y*(5*d)+x*(5*f)+$*(5*h),E+=H>>>13,H&=8191;let z=E+A*h+U*u+j*l+B*c+I*a;E=z>>>13,z&=8191,z+=D*(5*w)+m*(5*g)+y*(5*p)+x*(5*d)+$*(5*f),E+=z>>>13,z&=8191;let q=E+A*f+U*h+j*u+B*l+I*c;E=q>>>13,q&=8191,q+=D*a+m*(5*w)+y*(5*g)+x*(5*p)+$*(5*d),E+=q>>>13,q&=8191;let K=E+A*d+U*f+j*h+B*u+I*l;E=K>>>13,K&=8191,K+=D*c+m*a+y*(5*w)+x*(5*g)+$*(5*p),E+=K>>>13,K&=8191;let G=E+A*p+U*d+j*f+B*h+I*u;E=G>>>13,G&=8191,G+=D*l+m*c+y*a+x*(5*w)+$*(5*g),E+=G>>>13,G&=8191;let X=E+A*g+U*p+j*d+B*f+I*h;E=X>>>13,X&=8191,X+=D*u+m*l+y*c+x*a+$*(5*w),E+=X>>>13,X&=8191;let W=E+A*w+U*g+j*p+B*d+I*f;E=W>>>13,W&=8191,W+=D*h+m*u+y*l+x*c+$*a,E+=W>>>13,W&=8191,E=(E<<2)+E|0,E=E+S|0,S=E&8191,E=E>>>13,F+=E,s[0]=S,s[1]=F,s[2]=N,s[3]=H,s[4]=z,s[5]=q,s[6]=K,s[7]=G,s[8]=X,s[9]=W}finalize(){const{h:e,pad:i}=this,r=new Uint16Array(10);let n=e[1]>>>13;e[1]&=8191;for(let a=2;a<10;a++)e[a]+=n,n=e[a]>>>13,e[a]&=8191;e[0]+=n*5,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(let a=1;a<10;a++)r[a]=e[a]+n,n=r[a]>>>13,r[a]&=8191;r[9]-=8192;let s=(n^1)-1;for(let a=0;a<10;a++)r[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|r[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+i[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+i[a]|0)+(o>>>16)|0,e[a]=o&65535;Ur(r)}update(e){ju(this),e=Ua(e),et(e);const{buffer:i,blockLen:r}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);if(o===r){for(;r<=n-s;s+=r)this.process(e,s);continue}i.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===r&&(this.process(i,0,!1),this.pos=0)}return this}destroy(){Ur(this.h,this.r,this.buffer,this.pad)}digestInto(e){ju(this),Jx(e,this),this.finished=!0;const{buffer:i,h:r}=this;let{pos:n}=this;if(n){for(i[n++]=1;n<16;n++)i[n]=0;this.process(i,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=r[o]>>>0,e[s++]=r[o]>>>8;return e}digest(){const{buffer:e,outputLen:i}=this;this.digestInto(e);const r=e.slice(0,i);return this.destroy(),r}}function pI(t){const e=(r,n)=>t(n).update(Ua(r)).digest(),i=t(new Uint8Array(32));return e.outputLen=i.outputLen,e.blockLen=i.blockLen,e.create=r=>t(r),e}const gI=pI(t=>new dI(t));function yI(t,e,i,r,n,s=20){let o=t[0],a=t[1],c=t[2],l=t[3],u=e[0],h=e[1],f=e[2],d=e[3],p=e[4],g=e[5],w=e[6],_=e[7],C=n,b=i[0],v=i[1],O=i[2],P=o,T=a,R=c,A=l,U=u,j=h,B=f,I=d,D=p,m=g,y=w,x=_,$=C,E=b,S=v,F=O;for(let H=0;H<s;H+=2)P=P+U|0,$=re($^P,16),D=D+$|0,U=re(U^D,12),P=P+U|0,$=re($^P,8),D=D+$|0,U=re(U^D,7),T=T+j|0,E=re(E^T,16),m=m+E|0,j=re(j^m,12),T=T+j|0,E=re(E^T,8),m=m+E|0,j=re(j^m,7),R=R+B|0,S=re(S^R,16),y=y+S|0,B=re(B^y,12),R=R+B|0,S=re(S^R,8),y=y+S|0,B=re(B^y,7),A=A+I|0,F=re(F^A,16),x=x+F|0,I=re(I^x,12),A=A+I|0,F=re(F^A,8),x=x+F|0,I=re(I^x,7),P=P+j|0,F=re(F^P,16),y=y+F|0,j=re(j^y,12),P=P+j|0,F=re(F^P,8),y=y+F|0,j=re(j^y,7),T=T+B|0,$=re($^T,16),x=x+$|0,B=re(B^x,12),T=T+B|0,$=re($^T,8),x=x+$|0,B=re(B^x,7),R=R+I|0,E=re(E^R,16),D=D+E|0,I=re(I^D,12),R=R+I|0,E=re(E^R,8),D=D+E|0,I=re(I^D,7),A=A+U|0,S=re(S^A,16),m=m+S|0,U=re(U^m,12),A=A+U|0,S=re(S^A,8),m=m+S|0,U=re(U^m,7);let N=0;r[N++]=o+P|0,r[N++]=a+T|0,r[N++]=c+R|0,r[N++]=l+A|0,r[N++]=u+U|0,r[N++]=h+j|0,r[N++]=f+B|0,r[N++]=d+I|0,r[N++]=p+D|0,r[N++]=g+m|0,r[N++]=w+y|0,r[N++]=_+x|0,r[N++]=C+$|0,r[N++]=b+E|0,r[N++]=v+S|0,r[N++]=O+F|0}const wI=fI(yI,{counterRight:!1,counterLength:4,allowShortKeys:!1}),mI=new Uint8Array(16),zu=(t,e)=>{t.update(e);const i=e.length%16;i&&t.update(mI.subarray(i))},bI=new Uint8Array(32);function Vu(t,e,i,r,n){const s=t(e,i,bI),o=gI.create(s);n&&zu(o,n),zu(o,r);const a=nI(r.length,n?n.length:0,!0);o.update(a);const c=o.digest();return Ur(s,a),c}const vI=t=>(e,i,r)=>({encrypt(n,s){const o=n.length;s=Lu(o+16,s,!1),s.set(n);const a=s.subarray(0,-16);t(e,i,a,a,1);const c=Vu(t,e,i,a,r);return s.set(c,o),Ur(c),s},decrypt(n,s){s=Lu(n.length-16,s,!1);const o=n.subarray(0,-16),a=n.subarray(-16),c=Vu(t,e,i,o,r);if(!iI(a,c))throw new Error("invalid tag");return s.set(n.subarray(0,-16)),t(e,i,s,s,1),Ur(c),s}}),Gp=rI({blockSize:64,nonceLength:12,tagLength:16},vI(wI));let Yp=class extends Xs{constructor(e,i){super(),this.finished=!1,this.destroyed=!1,Js(e);const r=Bt(i);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 n=this.blockLen,s=new Uint8Array(n);s.set(r.length>n?e.create().update(r).digest():r);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),_t(s)}update(e){return Ui(this),this.iHash.update(e),this}digestInto(e){Ui(this),Tt(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:i,iHash:r,finished:n,destroyed:s,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=s,e.blockLen=o,e.outputLen=a,e.oHash=i._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const to=(t,e,i)=>new Yp(t,e).update(i).digest();to.create=(t,e)=>new Yp(t,e);function EI(t,e,i){return Js(t),i===void 0&&(i=new Uint8Array(t.outputLen)),to(t,Bt(i),Bt(e))}const zo=Uint8Array.from([0]),Hu=Uint8Array.of();function xI(t,e,i,r=32){Js(t),fi(r);const n=t.outputLen;if(r>255*n)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(r/n);i===void 0&&(i=Hu);const o=new Uint8Array(s*n),a=to.create(t,e),c=a._cloneInto(),l=new Uint8Array(a.outputLen);for(let u=0;u<s;u++)zo[0]=u+1,c.update(u===0?Hu:l).update(i).update(zo).digestInto(l),o.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),_t(l,zo),o.slice(0,r)}const II=(t,e,i,r,n)=>xI(t,EI(t,e,i),r,n),io=Qs,Lc=BigInt(0),La=BigInt(1);function Bs(t,e=""){if(typeof t!="boolean"){const i=e&&`"${e}"`;throw new Error(i+"expected boolean, got type="+typeof t)}return t}function Qi(t,e,i=""){const r=Zs(t),n=t==null?void 0:t.length,s=e!==void 0;if(!r||s&&n!==e){const o=i&&`"${i}" `,a=s?` of length ${e}`:"",c=r?`length=${n}`:`type=${typeof t}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return t}function Qn(t){const e=t.toString(16);return e.length&1?"0"+e:e}function Zp(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Lc:BigInt("0x"+t)}function ro(t){return Zp(Cr(t))}function Ts(t){return Tt(t),Zp(Cr(Uint8Array.from(t).reverse()))}function Mc(t,e){return Ps(t.toString(16).padStart(e*2,"0"))}function qc(t,e){return Mc(t,e).reverse()}function Ve(t,e,i){let r;if(typeof e=="string")try{r=Ps(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Zs(e))r=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=r.length;if(typeof i=="number"&&n!==i)throw new Error(t+" of length "+i+" expected, got "+n);return r}const Vo=t=>typeof t=="bigint"&&Lc<=t;function _I(t,e,i){return Vo(t)&&Vo(e)&&Vo(i)&&e<=t&&t<i}function Ma(t,e,i,r){if(!_I(e,i,r))throw new Error("expected valid "+t+": "+i+" <= n < "+r+", got "+e)}function Jp(t){let e;for(e=0;t>Lc;t>>=La,e+=1);return e}const Rn=t=>(La<<BigInt(t))-La;function SI(t,e,i){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 i!="function")throw new Error("hmacFn must be a function");const r=f=>new Uint8Array(f),n=f=>Uint8Array.of(f);let s=r(t),o=r(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...f)=>i(o,s,...f),u=(f=r(0))=>{o=l(n(0),f),s=l(),f.length!==0&&(o=l(n(1),f),s=l())},h=()=>{if(a++>=1e3)throw new Error("drbg: tried 1000 values");let f=0;const d=[];for(;f<e;){s=l();const p=s.slice();d.push(p),f+=s.length}return Ci(...d)};return(f,d)=>{c(),u(f);let p;for(;!(p=d(h()));)u();return c(),p}}function no(t,e,i={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function r(n,s,o){const a=t[n];if(o&&a===void 0)return;const c=typeof a;if(c!==s||a===null)throw new Error(`param "${n}" is invalid: expected ${s}, got ${c}`)}Object.entries(e).forEach(([n,s])=>r(n,s,!1)),Object.entries(i).forEach(([n,s])=>r(n,s,!0))}function Ku(t){const e=new WeakMap;return(i,...r)=>{const n=e.get(i);if(n!==void 0)return n;const s=t(i,...r);return e.set(i,s),s}}const rt=BigInt(0),We=BigInt(1),er=BigInt(2),Xp=BigInt(3),Qp=BigInt(4),eg=BigInt(5),$I=BigInt(7),tg=BigInt(8),DI=BigInt(9),ig=BigInt(16);function ht(t,e){const i=t%e;return i>=rt?i:e+i}function At(t,e,i){let r=t;for(;e-- >rt;)r*=r,r%=i;return r}function Wu(t,e){if(t===rt)throw new Error("invert: expected non-zero number");if(e<=rt)throw new Error("invert: expected positive modulus, got "+e);let i=ht(t,e),r=e,n=rt,s=We;for(;i!==rt;){const o=r/i,a=r%i,c=n-s*o;r=i,i=a,n=s,s=c}if(r!==We)throw new Error("invert: does not exist");return ht(n,e)}function zc(t,e,i){if(!t.eql(t.sqr(e),i))throw new Error("Cannot find square root")}function rg(t,e){const i=(t.ORDER+We)/Qp,r=t.pow(e,i);return zc(t,r,e),r}function OI(t,e){const i=(t.ORDER-eg)/tg,r=t.mul(e,er),n=t.pow(r,i),s=t.mul(e,n),o=t.mul(t.mul(s,er),n),a=t.mul(s,t.sub(o,t.ONE));return zc(t,a,e),a}function AI(t){const e=ji(t),i=ng(t),r=i(e,e.neg(e.ONE)),n=i(e,r),s=i(e,e.neg(r)),o=(t+$I)/ig;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,r);const h=a.mul(l,n),f=a.mul(l,s),d=a.eql(a.sqr(u),c),p=a.eql(a.sqr(h),c);l=a.cmov(l,u,d),u=a.cmov(f,h,p);const g=a.eql(a.sqr(u),c),w=a.cmov(l,u,g);return zc(a,w,c),w}}function ng(t){if(t<Xp)throw new Error("sqrt is not defined for small field");let e=t-We,i=0;for(;e%er===rt;)e/=er,i++;let r=er;const n=ji(t);for(;Gu(n,r)===1;)if(r++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(i===1)return rg;let s=n.pow(r,e);const o=(e+We)/er;return function(a,c){if(a.is0(c))return c;if(Gu(a,c)!==1)throw new Error("Cannot find square root");let l=i,u=a.mul(a.ONE,s),h=a.pow(c,e),f=a.pow(c,o);for(;!a.eql(h,a.ONE);){if(a.is0(h))return a.ZERO;let d=1,p=a.sqr(h);for(;!a.eql(p,a.ONE);)if(d++,p=a.sqr(p),d===l)throw new Error("Cannot find square root");const g=We<<BigInt(l-d-1),w=a.pow(u,g);l=d,u=a.sqr(w),h=a.mul(h,u),f=a.mul(f,w)}return f}}function PI(t){return t%Qp===Xp?rg:t%tg===eg?OI:t%ig===DI?AI(t):ng(t)}const CI=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function BI(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},i=CI.reduce((r,n)=>(r[n]="function",r),e);return no(t,i),t}function TI(t,e,i){if(i<rt)throw new Error("invalid exponent, negatives unsupported");if(i===rt)return t.ONE;if(i===We)return e;let r=t.ONE,n=e;for(;i>rt;)i&We&&(r=t.mul(r,n)),n=t.sqr(n),i>>=We;return r}function sg(t,e,i=!1){const r=new Array(e.length).fill(i?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(r[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(r[c]=t.mul(o,r[c]),t.mul(o,a)),s),r}function Gu(t,e){const i=(t.ORDER-We)/er,r=t.pow(e,i),n=t.eql(r,t.ONE),s=t.eql(r,t.ZERO),o=t.eql(r,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function og(t,e){e!==void 0&&fi(e);const i=e!==void 0?e:t.toString(2).length,r=Math.ceil(i/8);return{nBitLength:i,nByteLength:r}}function ji(t,e,i=!1,r={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,s,o=!1,a;if(typeof e=="object"&&e!=null){if(r.sqrt||i)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(n=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(i=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(n=e),r.sqrt&&(s=r.sqrt);const{nBitLength:c,nByteLength:l}=og(t,n);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:i,BITS:c,BYTES:l,MASK:Rn(c),ZERO:rt,ONE:We,allowedLengths:a,create:f=>ht(f,t),isValid:f=>{if(typeof f!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof f);return rt<=f&&f<t},is0:f=>f===rt,isValidNot0:f=>!h.is0(f)&&h.isValid(f),isOdd:f=>(f&We)===We,neg:f=>ht(-f,t),eql:(f,d)=>f===d,sqr:f=>ht(f*f,t),add:(f,d)=>ht(f+d,t),sub:(f,d)=>ht(f-d,t),mul:(f,d)=>ht(f*d,t),pow:(f,d)=>TI(h,f,d),div:(f,d)=>ht(f*Wu(d,t),t),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Wu(f,t),sqrt:s||(f=>(u||(u=PI(t)),u(h,f))),toBytes:f=>i?qc(f,l):Mc(f,l),fromBytes:(f,d=!0)=>{if(a){if(!a.includes(f.length)||f.length>l)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+f.length);const g=new Uint8Array(l);g.set(f,i?0:g.length-f.length),f=g}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let p=i?Ts(f):ro(f);if(o&&(p=ht(p,t)),!d&&!h.isValid(p))throw new Error("invalid field element: outside of range 0..ORDER");return p},invertBatch:f=>sg(h,f),cmov:(f,d,p)=>p?d:f});return Object.freeze(h)}function ag(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 cg(t){const e=ag(t);return e+Math.ceil(e/2)}function RI(t,e,i=!1){const r=t.length,n=ag(e),s=cg(e);if(r<16||r<s||r>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+r);const o=i?Ts(t):ro(t),a=ht(o,e-We)+We;return i?qc(a,n):Mc(a,n)}const kr=BigInt(0),tr=BigInt(1);function Rs(t,e){const i=e.negate();return t?i:e}function Ho(t,e){const i=sg(t.Fp,e.map(r=>r.Z));return e.map((r,n)=>t.fromAffine(r.toAffine(i[n])))}function lg(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function Ko(t,e){lg(t,e);const i=Math.ceil(e/t)+1,r=2**(t-1),n=2**t,s=Rn(t),o=BigInt(t);return{windows:i,windowSize:r,mask:s,maxNumber:n,shiftBy:o}}function Yu(t,e,i){const{windowSize:r,mask:n,maxNumber:s,shiftBy:o}=i;let a=Number(t&n),c=t>>o;a>r&&(a-=s,c+=tr);const l=e*r,u=l+Math.abs(a)-1,h=a===0,f=a<0,d=e%2!==0;return{nextN:c,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:l}}function FI(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((i,r)=>{if(!(i instanceof e))throw new Error("invalid point at index "+r)})}function NI(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((i,r)=>{if(!e.isValid(i))throw new Error("invalid scalar at index "+r)})}const Wo=new WeakMap,ug=new WeakMap;function Go(t){return ug.get(t)||1}function Zu(t){if(t!==kr)throw new Error("invalid wNAF")}class UI{constructor(e,i){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=i}_unsafeLadder(e,i,r=this.ZERO){let n=e;for(;i>kr;)i&tr&&(r=r.add(n)),n=n.double(),i>>=tr;return r}precomputeWindow(e,i){const{windows:r,windowSize:n}=Ko(i,this.bits),s=[];let o=e,a=o;for(let c=0;c<r;c++){a=o,s.push(a);for(let l=1;l<n;l++)a=a.add(o),s.push(a);o=a.double()}return s}wNAF(e,i,r){if(!this.Fn.isValid(r))throw new Error("invalid scalar");let n=this.ZERO,s=this.BASE;const o=Ko(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:h,isNegF:f,offsetF:d}=Yu(r,a,o);r=c,u?s=s.add(Rs(f,i[d])):n=n.add(Rs(h,i[l]))}return Zu(r),{p:n,f:s}}wNAFUnsafe(e,i,r,n=this.ZERO){const s=Ko(e,this.bits);for(let o=0;o<s.windows&&r!==kr;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=Yu(r,o,s);if(r=a,!l){const h=i[c];n=n.add(u?h.negate():h)}}return Zu(r),n}getPrecomputes(e,i,r){let n=Wo.get(i);return n||(n=this.precomputeWindow(i,e),e!==1&&(typeof r=="function"&&(n=r(n)),Wo.set(i,n))),n}cached(e,i,r){const n=Go(e);return this.wNAF(n,this.getPrecomputes(n,e,r),i)}unsafe(e,i,r,n){const s=Go(e);return s===1?this._unsafeLadder(e,i,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,r),i,n)}createCache(e,i){lg(i,this.bits),ug.set(e,i),Wo.delete(e)}hasCache(e){return Go(e)!==1}}function kI(t,e,i,r){let n=e,s=t.ZERO,o=t.ZERO;for(;i>kr||r>kr;)i&tr&&(s=s.add(n)),r&tr&&(o=o.add(n)),n=n.double(),i>>=tr,r>>=tr;return{p1:s,p2:o}}function jI(t,e,i,r){FI(i,t),NI(r,e);const n=i.length,s=r.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=Jp(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=Rn(c),u=new Array(Number(l)+1).fill(o),h=Math.floor((e.BITS-1)/c)*c;let f=o;for(let d=h;d>=0;d-=c){u.fill(o);for(let g=0;g<s;g++){const w=r[g],_=Number(w>>BigInt(d)&l);u[_]=u[_].add(i[g])}let p=o;for(let g=u.length-1,w=o;g>0;g--)w=w.add(u[g]),p=p.add(w);if(f=f.add(p),d!==0)for(let g=0;g<c;g++)f=f.double()}return f}function Ju(t,e,i){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return BI(e),e}else return ji(t,{isLE:i})}function LI(t,e,i={},r){if(r===void 0&&(r=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>kr))throw new Error(`CURVE.${a} must be positive bigint`)}const n=Ju(e.p,i.Fp,r),s=Ju(e.n,i.Fn,r),o=["Gx","Gy","a",t==="weierstrass"?"b":"d"];for(const a of o)if(!n.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:n,Fn:s}}BigInt(0),BigInt(1),BigInt(2),BigInt(8),Tp("HashToScalar-");const Xr=BigInt(0),br=BigInt(1),es=BigInt(2);function MI(t){return no(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function qI(t){const e=MI(t),{P:i,type:r,adjustScalarBytes:n,powPminus2:s,randomBytes:o}=e,a=r==="x25519";if(!a&&r!=="x448")throw new Error("invalid type");const c=o||lr,l=a?255:448,u=a?32:56,h=BigInt(a?9:5),f=BigInt(a?121665:39081),d=a?es**BigInt(254):es**BigInt(447),p=a?BigInt(8)*es**BigInt(251)-br:BigInt(4)*es**BigInt(445)-br,g=d+p+br,w=B=>ht(B,i),_=C(h);function C(B){return qc(w(B),u)}function b(B){const I=Ve("u coordinate",B,u);return a&&(I[31]&=127),w(Ts(I))}function v(B){return Ts(n(Ve("scalar",B,u)))}function O(B,I){const D=R(b(I),v(B));if(D===Xr)throw new Error("invalid private or public key received");return C(D)}function P(B){return O(B,_)}function T(B,I,D){const m=w(B*(I-D));return I=w(I-m),D=w(D+m),{x_2:I,x_3:D}}function R(B,I){Ma("u",B,Xr,i),Ma("scalar",I,d,g);const D=I,m=B;let y=br,x=Xr,$=B,E=br,S=Xr;for(let N=BigInt(l-1);N>=Xr;N--){const H=D>>N&br;S^=H,{x_2:y,x_3:$}=T(S,y,$),{x_2:x,x_3:E}=T(S,x,E),S=H;const z=y+x,q=w(z*z),K=y-x,G=w(K*K),X=q-G,W=$+E,Q=$-E,pe=w(Q*z),ve=w(W*K),_e=pe+ve,He=pe-ve;$=w(_e*_e),E=w(m*w(He*He)),y=w(q*G),x=w(X*(q+w(f*X)))}({x_2:y,x_3:$}=T(S,y,$)),{x_2:x,x_3:E}=T(S,x,E);const F=s(x);return w(y*F)}const A={secretKey:u,publicKey:u,seed:u},U=(B=c(u))=>(Tt(B,A.seed),B);function j(B){const I=U(B);return{secretKey:I,publicKey:P(I)}}return{keygen:j,getSharedSecret:(B,I)=>O(B,I),getPublicKey:B=>P(B),scalarMult:O,scalarMultBase:P,utils:{randomSecretKey:U,randomPrivateKey:U},GuBytes:_.slice(),lengths:A}}const zI=BigInt(1),Xu=BigInt(2),VI=BigInt(3),HI=BigInt(5),KI=BigInt(8),hg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),WI={p:hg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:KI,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function GI(t){const e=BigInt(10),i=BigInt(20),r=BigInt(40),n=BigInt(80),s=hg,o=t*t%s*t%s,a=At(o,Xu,s)*o%s,c=At(a,zI,s)*t%s,l=At(c,HI,s)*c%s,u=At(l,e,s)*l%s,h=At(u,i,s)*u%s,f=At(h,r,s)*h%s,d=At(f,n,s)*f%s,p=At(d,n,s)*f%s,g=At(p,e,s)*l%s;return{pow_p_5_8:At(g,Xu,s)*t%s,b2:o}}function YI(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const ZI=ji(WI.p,{isLE:!0}),qa=(()=>{const t=ZI.ORDER;return qI({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:i,b2:r}=GI(e);return ht(At(i,VI,t)*r,t)},adjustScalarBytes:YI})})(),Qu=(t,e)=>(t+(t>=0?e:-e)/fg)/e;function JI(t,e,i){const[[r,n],[s,o]]=e,a=Qu(o*t,i),c=Qu(-n*t,i);let l=t-a*r-c*s,u=-a*n-c*o;const h=l<ai,f=u<ai;h&&(l=-l),f&&(u=-u);const d=Rn(Math.ceil(Jp(i)/2))+Br;if(l<ai||l>=d||u<ai||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}function za(t){if(!["compact","recovered","der"].includes(t))throw new Error('Signature format must be "compact", "recovered", or "der"');return t}function Yo(t,e){const i={};for(let r of Object.keys(e))i[r]=t[r]===void 0?e[r]:t[r];return Bs(i.lowS,"lowS"),Bs(i.prehash,"prehash"),i.format!==void 0&&za(i.format),i}class XI extends Error{constructor(e=""){super(e)}}const si={Err:XI,_tlv:{encode:(t,e)=>{const{Err:i}=si;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length&1)throw new i("tlv.encode: unpadded data");const r=e.length/2,n=Qn(r);if(n.length/2&128)throw new i("tlv.encode: long form length too big");const s=r>127?Qn(n.length/2|128):"";return Qn(t)+s+n+e},decode(t,e){const{Err:i}=si;let r=0;if(t<0||t>256)throw new i("tlv.encode: wrong tag");if(e.length<2||e[r++]!==t)throw new i("tlv.decode: wrong tlv");const n=e[r++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new i("tlv.decode(long): indefinite length not supported");if(c>4)throw new i("tlv.decode(long): byte length is too big");const l=e.subarray(r,r+c);if(l.length!==c)throw new i("tlv.decode: length bytes not complete");if(l[0]===0)throw new i("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(r+=c,o<128)throw new i("tlv.decode(long): not minimal encoding")}const a=e.subarray(r,r+o);if(a.length!==o)throw new i("tlv.decode: wrong value length");return{v:a,l:e.subarray(r+o)}}},_int:{encode(t){const{Err:e}=si;if(t<ai)throw new e("integer: negative integers are not allowed");let i=Qn(t);if(Number.parseInt(i[0],16)&8&&(i="00"+i),i.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return i},decode(t){const{Err:e}=si;if(t[0]&128)throw new e("invalid signature integer: negative");if(t[0]===0&&!(t[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ro(t)}},toSig(t){const{Err:e,_int:i,_tlv:r}=si,n=Ve("signature",t),{v:s,l:o}=r.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=r.decode(2,s),{v:l,l:u}=r.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:i.decode(a),s:i.decode(l)}},hexFromSig(t){const{_tlv:e,_int:i}=si,r=e.encode(2,i.encode(t.r)),n=e.encode(2,i.encode(t.s)),s=r+n;return e.encode(48,s)}},ai=BigInt(0),Br=BigInt(1),fg=BigInt(2),ts=BigInt(3),QI=BigInt(4);function Sr(t,e){const{BYTES:i}=t;let r;if(typeof e=="bigint")r=e;else{let n=Ve("private key",e);try{r=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${i}, got ${typeof e}`)}}if(!t.isValidNot0(r))throw new Error("invalid private key: out of range [1..N-1]");return r}function e_(t,e={}){const i=LI("weierstrass",t,e),{Fp:r,Fn:n}=i;let s=i.CURVE;const{h:o,n:a}=s;no(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object",wrapPrivateKey:"boolean"});const{endo:c}=e;if(c&&(!r.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=pg(r,n);function u(){if(!r.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,I,D){const{x:m,y}=I.toAffine(),x=r.toBytes(m);if(Bs(D,"isCompressed"),D){u();const $=!r.isOdd(y);return Ci(dg($),x)}else return Ci(Uint8Array.of(4),x,r.toBytes(y))}function f(B){Qi(B,void 0,"Point");const{publicKey:I,publicKeyUncompressed:D}=l,m=B.length,y=B[0],x=B.subarray(1);if(m===I&&(y===2||y===3)){const $=r.fromBytes(x);if(!r.isValid($))throw new Error("bad point: is not on curve, wrong x");const E=g($);let S;try{S=r.sqrt(E)}catch(N){const H=N instanceof Error?": "+N.message:"";throw new Error("bad point: is not on curve, sqrt error"+H)}u();const F=r.isOdd(S);return(y&1)===1!==F&&(S=r.neg(S)),{x:$,y:S}}else if(m===D&&y===4){const $=r.BYTES,E=r.fromBytes(x.subarray(0,$)),S=r.fromBytes(x.subarray($,$*2));if(!w(E,S))throw new Error("bad point: is not on curve");return{x:E,y:S}}else throw new Error(`bad point: got length ${m}, expected compressed=${I} or uncompressed=${D}`)}const d=e.toBytes||h,p=e.fromBytes||f;function g(B){const I=r.sqr(B),D=r.mul(I,B);return r.add(r.add(D,r.mul(B,s.a)),s.b)}function w(B,I){const D=r.sqr(I),m=g(B);return r.eql(D,m)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const _=r.mul(r.pow(s.a,ts),QI),C=r.mul(r.sqr(s.b),BigInt(27));if(r.is0(r.add(_,C)))throw new Error("bad curve params: a or b");function b(B,I,D=!1){if(!r.isValid(I)||D&&r.is0(I))throw new Error(`bad point coordinate ${B}`);return I}function v(B){if(!(B instanceof A))throw new Error("ProjectivePoint expected")}function O(B){if(!c||!c.basises)throw new Error("no endo");return JI(B,c.basises,n.ORDER)}const P=Ku((B,I)=>{const{X:D,Y:m,Z:y}=B;if(r.eql(y,r.ONE))return{x:D,y:m};const x=B.is0();I==null&&(I=x?r.ONE:r.inv(y));const $=r.mul(D,I),E=r.mul(m,I),S=r.mul(y,I);if(x)return{x:r.ZERO,y:r.ZERO};if(!r.eql(S,r.ONE))throw new Error("invZ was invalid");return{x:$,y:E}}),T=Ku(B=>{if(B.is0()){if(e.allowInfinityPoint&&!r.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:I,y:D}=B.toAffine();if(!r.isValid(I)||!r.isValid(D))throw new Error("bad point: x or y not field elements");if(!w(I,D))throw new Error("bad point: equation left != right");if(!B.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function R(B,I,D,m,y){return D=new A(r.mul(D.X,B),D.Y,D.Z),I=Rs(m,I),D=Rs(y,D),I.add(D)}class A{constructor(I,D,m){this.X=b("x",I),this.Y=b("y",D,!0),this.Z=b("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(I){const{x:D,y:m}=I||{};if(!I||!r.isValid(D)||!r.isValid(m))throw new Error("invalid affine point");if(I instanceof A)throw new Error("projective point not allowed");return r.is0(D)&&r.is0(m)?A.ZERO:new A(D,m,r.ONE)}static fromBytes(I){const D=A.fromAffine(p(Qi(I,void 0,"point")));return D.assertValidity(),D}static fromHex(I){return A.fromBytes(Ve("pointHex",I))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(I=8,D=!0){return j.createCache(this,I),D||this.multiply(ts),this}assertValidity(){T(this)}hasEvenY(){const{y:I}=this.toAffine();if(!r.isOdd)throw new Error("Field doesn't support isOdd");return!r.isOdd(I)}equals(I){v(I);const{X:D,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=I,S=r.eql(r.mul(D,E),r.mul(x,y)),F=r.eql(r.mul(m,E),r.mul($,y));return S&&F}negate(){return new A(this.X,r.neg(this.Y),this.Z)}double(){const{a:I,b:D}=s,m=r.mul(D,ts),{X:y,Y:x,Z:$}=this;let E=r.ZERO,S=r.ZERO,F=r.ZERO,N=r.mul(y,y),H=r.mul(x,x),z=r.mul($,$),q=r.mul(y,x);return q=r.add(q,q),F=r.mul(y,$),F=r.add(F,F),E=r.mul(I,F),S=r.mul(m,z),S=r.add(E,S),E=r.sub(H,S),S=r.add(H,S),S=r.mul(E,S),E=r.mul(q,E),F=r.mul(m,F),z=r.mul(I,z),q=r.sub(N,z),q=r.mul(I,q),q=r.add(q,F),F=r.add(N,N),N=r.add(F,N),N=r.add(N,z),N=r.mul(N,q),S=r.add(S,N),z=r.mul(x,$),z=r.add(z,z),N=r.mul(z,q),E=r.sub(E,N),F=r.mul(z,H),F=r.add(F,F),F=r.add(F,F),new A(E,S,F)}add(I){v(I);const{X:D,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=I;let S=r.ZERO,F=r.ZERO,N=r.ZERO;const H=s.a,z=r.mul(s.b,ts);let q=r.mul(D,x),K=r.mul(m,$),G=r.mul(y,E),X=r.add(D,m),W=r.add(x,$);X=r.mul(X,W),W=r.add(q,K),X=r.sub(X,W),W=r.add(D,y);let Q=r.add(x,E);return W=r.mul(W,Q),Q=r.add(q,G),W=r.sub(W,Q),Q=r.add(m,y),S=r.add($,E),Q=r.mul(Q,S),S=r.add(K,G),Q=r.sub(Q,S),N=r.mul(H,W),S=r.mul(z,G),N=r.add(S,N),S=r.sub(K,N),N=r.add(K,N),F=r.mul(S,N),K=r.add(q,q),K=r.add(K,q),G=r.mul(H,G),W=r.mul(z,W),K=r.add(K,G),G=r.sub(q,G),G=r.mul(H,G),W=r.add(W,G),q=r.mul(K,W),F=r.add(F,q),q=r.mul(Q,W),S=r.mul(X,S),S=r.sub(S,q),q=r.mul(X,K),N=r.mul(Q,N),N=r.add(N,q),new A(S,F,N)}subtract(I){return this.add(I.negate())}is0(){return this.equals(A.ZERO)}multiply(I){const{endo:D}=e;if(!n.isValidNot0(I))throw new Error("invalid scalar: out of range");let m,y;const x=$=>j.cached(this,$,E=>Ho(A,E));if(D){const{k1neg:$,k1:E,k2neg:S,k2:F}=O(I),{p:N,f:H}=x(E),{p:z,f:q}=x(F);y=H.add(q),m=R(D.beta,N,z,$,S)}else{const{p:$,f:E}=x(I);m=$,y=E}return Ho(A,[m,y])[0]}multiplyUnsafe(I){const{endo:D}=e,m=this;if(!n.isValid(I))throw new Error("invalid scalar: out of range");if(I===ai||m.is0())return A.ZERO;if(I===Br)return m;if(j.hasCache(this))return this.multiply(I);if(D){const{k1neg:y,k1:x,k2neg:$,k2:E}=O(I),{p1:S,p2:F}=kI(A,m,x,E);return R(D.beta,S,F,y,$)}else return j.unsafe(m,I)}multiplyAndAddUnsafe(I,D,m){const y=this.multiplyUnsafe(D).add(I.multiplyUnsafe(m));return y.is0()?void 0:y}toAffine(I){return P(this,I)}isTorsionFree(){const{isTorsionFree:I}=e;return o===Br?!0:I?I(A,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:I}=e;return o===Br?this:I?I(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(I=!0){return Bs(I,"isCompressed"),this.assertValidity(),d(A,this,I)}toHex(I=!0){return Cr(this.toBytes(I))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(I=!0){return this.toBytes(I)}_setWindowSize(I){this.precompute(I)}static normalizeZ(I){return Ho(A,I)}static msm(I,D){return jI(A,n,I,D)}static fromPrivateKey(I){return A.BASE.multiply(Sr(n,I))}}A.BASE=new A(s.Gx,s.Gy,r.ONE),A.ZERO=new A(r.ZERO,r.ONE,r.ZERO),A.Fp=r,A.Fn=n;const U=n.BITS,j=new UI(A,e.endo?Math.ceil(U/2):U);return A.BASE.precompute(8),A}function dg(t){return Uint8Array.of(t?2:3)}function pg(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function t_(t,e={}){const{Fn:i}=t,r=e.randomBytes||lr,n=Object.assign(pg(t.Fp,i),{seed:cg(i.ORDER)});function s(f){try{return!!Sr(i,f)}catch{return!1}}function o(f,d){const{publicKey:p,publicKeyUncompressed:g}=n;try{const w=f.length;return d===!0&&w!==p||d===!1&&w!==g?!1:!!t.fromBytes(f)}catch{return!1}}function a(f=r(n.seed)){return RI(Qi(f,n.seed,"seed"),i.ORDER)}function c(f,d=!0){return t.BASE.multiply(Sr(i,f)).toBytes(d)}function l(f){const d=a(f);return{secretKey:d,publicKey:c(d)}}function u(f){if(typeof f=="bigint")return!1;if(f instanceof t)return!0;const{secretKey:d,publicKey:p,publicKeyUncompressed:g}=n;if(i.allowedLengths||d===p)return;const w=Ve("key",f).length;return w===p||w===g}function h(f,d,p=!0){if(u(f)===!0)throw new Error("first arg must be private key");if(u(d)===!1)throw new Error("second arg must be public key");const g=Sr(i,f);return t.fromHex(d).multiply(g).toBytes(p)}return Object.freeze({getPublicKey:c,getSharedSecret:h,keygen:l,Point:t,utils:{isValidSecretKey:s,isValidPublicKey:o,randomSecretKey:a,isValidPrivateKey:s,randomPrivateKey:a,normPrivateKeyToScalar:f=>Sr(i,f),precompute(f=8,d=t.BASE){return d.precompute(f,!1)}},lengths:n})}function i_(t,e,i={}){Js(e),no(i,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const r=i.randomBytes||lr,n=i.hmac||((D,...m)=>to(e,D,Ci(...m))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d}=t_(t,i),p={prehash:!1,lowS:typeof i.lowS=="boolean"?i.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(D){const m=a>>Br;return D>m}function _(D,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${D}: out of range 1..Point.Fn.ORDER`);return m}function C(D,m){za(m);const y=d.signature,x=m==="compact"?y:m==="recovered"?y+1:void 0;return Qi(D,x,`${m} signature`)}class b{constructor(m,y,x){this.r=_("r",m),this.s=_("s",y),x!=null&&(this.recovery=x),Object.freeze(this)}static fromBytes(m,y=g){C(m,y);let x;if(y==="der"){const{r:F,s:N}=si.toSig(Qi(m));return new b(F,N)}y==="recovered"&&(x=m[0],y="compact",m=m.subarray(1));const $=o.BYTES,E=m.subarray(0,$),S=m.subarray($,$*2);return new b(o.fromBytes(E),o.fromBytes(S),x)}static fromHex(m,y){return this.fromBytes(Ps(m),y)}addRecoveryBit(m){return new b(this.r,this.s,m)}recoverPublicKey(m){const y=s.ORDER,{r:x,s:$,recovery:E}=this;if(E==null||![0,1,2,3].includes(E))throw new Error("recovery id invalid");if(a*fg<y&&E>1)throw new Error("recovery id is ambiguous for h>1 curve");const S=E===2||E===3?x+a:x;if(!s.isValid(S))throw new Error("recovery id 2 or 3 invalid");const F=s.toBytes(S),N=t.fromBytes(Ci(dg((E&1)===0),F)),H=o.inv(S),z=O(Ve("msgHash",m)),q=o.create(-z*H),K=o.create($*H),G=t.BASE.multiplyUnsafe(q).add(N.multiplyUnsafe(K));if(G.is0())throw new Error("point at infinify");return G.assertValidity(),G}hasHighS(){return w(this.s)}toBytes(m=g){if(za(m),m==="der")return Ps(si.hexFromSig(this));const y=o.toBytes(this.r),x=o.toBytes(this.s);if(m==="recovered"){if(this.recovery==null)throw new Error("recovery bit must be present");return Ci(Uint8Array.of(this.recovery),y,x)}return Ci(y,x)}toHex(m){return Cr(this.toBytes(m))}assertValidity(){}static fromCompact(m){return b.fromBytes(Ve("sig",m),"compact")}static fromDER(m){return b.fromBytes(Ve("sig",m),"der")}normalizeS(){return this.hasHighS()?new b(this.r,o.neg(this.s),this.recovery):this}toDERRawBytes(){return this.toBytes("der")}toDERHex(){return Cr(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Cr(this.toBytes("compact"))}}const v=i.bits2int||function(D){if(D.length>8192)throw new Error("input is too large");const m=ro(D),y=D.length*8-c;return y>0?m>>BigInt(y):m},O=i.bits2int_modN||function(D){return o.create(v(D))},P=Rn(c);function T(D){return Ma("num < 2^"+c,D,ai,P),o.toBytes(D)}function R(D,m){return Qi(D,void 0,"message"),m?Qi(e(D),void 0,"prehashed message"):D}function A(D,m,y){if(["recovered","canonical"].some(K=>K in y))throw new Error("sign() legacy options not supported");const{lowS:x,prehash:$,extraEntropy:E}=Yo(y,p);D=R(D,$);const S=O(D),F=Sr(o,m),N=[T(F),T(S)];if(E!=null&&E!==!1){const K=E===!0?r(d.secretKey):E;N.push(Ve("extraEntropy",K))}const H=Ci(...N),z=S;function q(K){const G=v(K);if(!o.isValidNot0(G))return;const X=o.inv(G),W=t.BASE.multiply(G).toAffine(),Q=o.create(W.x);if(Q===ai)return;const pe=o.create(X*o.create(z+Q*F));if(pe===ai)return;let ve=(W.x===Q?0:2)|Number(W.y&Br),_e=pe;return x&&w(pe)&&(_e=o.neg(pe),ve^=1),new b(Q,_e,ve)}return{seed:H,k2sig:q}}function U(D,m,y={}){D=Ve("message",D);const{seed:x,k2sig:$}=A(D,m,y);return SI(e.outputLen,o.BYTES,n)(x,$)}function j(D){let m;const y=typeof D=="string"||Zs(D),x=!y&&D!==null&&typeof D=="object"&&typeof D.r=="bigint"&&typeof D.s=="bigint";if(!y&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)m=new b(D.r,D.s);else if(y){try{m=b.fromBytes(Ve("sig",D),"der")}catch($){if(!($ instanceof si.Err))throw $}if(!m)try{m=b.fromBytes(Ve("sig",D),"compact")}catch{return!1}}return m||!1}function B(D,m,y,x={}){const{lowS:$,prehash:E,format:S}=Yo(x,p);if(y=Ve("publicKey",y),m=R(Ve("message",m),E),"strict"in x)throw new Error("options.strict was renamed to lowS");const F=S===void 0?j(D):b.fromBytes(Ve("sig",D),S);if(F===!1)return!1;try{const N=t.fromBytes(y);if($&&F.hasHighS())return!1;const{r:H,s:z}=F,q=O(m),K=o.inv(z),G=o.create(q*K),X=o.create(H*K),W=t.BASE.multiplyUnsafe(G).add(N.multiplyUnsafe(X));return W.is0()?!1:o.create(W.x)===H}catch{return!1}}function I(D,m,y={}){const{prehash:x}=Yo(y,p);return m=R(m,x),b.fromBytes(D,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d,Point:t,sign:U,verify:B,recoverPublicKey:I,Signature:b,hash:e})}function r_(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},i=t.Fp;let r=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const n=ji(e.n,{BITS:t.nBitLength,allowedLengths:r,modFromBytes:t.wrapPrivateKey}),s={Fp:i,Fn:n,allowInfinityPoint:t.allowInfinityPoint,endo:t.endo,isTorsionFree:t.isTorsionFree,clearCofactor:t.clearCofactor,fromBytes:t.fromBytes,toBytes:t.toBytes};return{CURVE:e,curveOpts:s}}function n_(t){const{CURVE:e,curveOpts:i}=r_(t),r={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:i,hash:t.hash,ecdsaOpts:r}}function s_(t,e){const i=e.Point;return Object.assign({},e,{ProjectivePoint:i,CURVE:Object.assign({},t,og(i.Fn.ORDER,i.Fn.BITS))})}function o_(t){const{CURVE:e,curveOpts:i,hash:r,ecdsaOpts:n}=n_(t),s=e_(e,i),o=i_(s,r,n);return s_(t,o)}function Va(t,e){const i=r=>o_({...t,hash:r});return{...i(e),create:i}}const gg={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},yg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},wg={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},a_=ji(gg.p),c_=ji(yg.p),l_=ji(wg.p),u_=Va({...gg,Fp:a_,lowS:!1},Qs);Va({...yg,Fp:c_,lowS:!1},px),Va({...wg,Fp:l_,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},dx);const h_=u_,mg="base10",Ge="base16",tt="base64pad",Bi="base64url",Fn="utf8",bg=0,li=1,Nn=2,f_=0,eh=1,dn=12,Vc=32;function d_(){const t=qa.utils.randomPrivateKey(),e=qa.getPublicKey(t);return{privateKey:nt(t,Ge),publicKey:nt(e,Ge)}}function Ha(){const t=lr(Vc);return nt(t,Ge)}function p_(t,e){const i=qa.getSharedSecret(Et(t,Ge),Et(e,Ge)),r=II(io,i,void 0,void 0,Vc);return nt(r,Ge)}function ds(t){const e=io(Et(t,Ge));return nt(e,Ge)}function bt(t){const e=io(Et(t,Fn));return nt(e,Ge)}function vg(t){return Et(`${t}`,mg)}function ar(t){return Number(nt(t,mg))}function Eg(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xg(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),i=(4-e.length%4)%4;return e+"=".repeat(i)}function g_(t){const e=vg(typeof t.type<"u"?t.type:bg);if(ar(e)===li&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const i=typeof t.senderPublicKey<"u"?Et(t.senderPublicKey,Ge):void 0,r=typeof t.iv<"u"?Et(t.iv,Ge):lr(dn),n=Et(t.symKey,Ge),s=Gp(n,r).encrypt(Et(t.message,Fn)),o=Ig({type:e,sealed:s,iv:r,senderPublicKey:i});return t.encoding===Bi?Eg(o):o}function y_(t){const e=Et(t.symKey,Ge),{sealed:i,iv:r}=_n({encoded:t.encoded,encoding:t.encoding}),n=Gp(e,r).decrypt(i);if(n===null)throw new Error("Failed to decrypt");return nt(n,Fn)}function w_(t,e){const i=vg(Nn),r=lr(dn),n=Et(t,Fn),s=Ig({type:i,sealed:n,iv:r});return e===Bi?Eg(s):s}function m_(t,e){const{sealed:i}=_n({encoded:t,encoding:e});return nt(i,Fn)}function Ig(t){if(ar(t.type)===Nn)return nt(fn([t.type,t.sealed]),tt);if(ar(t.type)===li){if(typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");return nt(fn([t.type,t.senderPublicKey,t.iv,t.sealed]),tt)}return nt(fn([t.type,t.iv,t.sealed]),tt)}function _n(t){const e=(t.encoding||tt)===Bi?xg(t.encoded):t.encoded,i=Et(e,tt),r=i.slice(f_,eh),n=eh;if(ar(r)===li){const c=n+Vc,l=c+dn,u=i.slice(n,c),h=i.slice(c,l),f=i.slice(l);return{type:r,sealed:f,iv:h,senderPublicKey:u}}if(ar(r)===Nn){const c=i.slice(n),l=lr(dn);return{type:r,sealed:c,iv:l}}const s=n+dn,o=i.slice(n,s),a=i.slice(s);return{type:r,sealed:a,iv:o}}function b_(t,e){const i=_n({encoded:t,encoding:e==null?void 0:e.encoding});return _g({type:ar(i.type),senderPublicKey:typeof i.senderPublicKey<"u"?nt(i.senderPublicKey,Ge):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function _g(t){const e=(t==null?void 0:t.type)||bg;if(e===li){if(typeof(t==null?void 0:t.senderPublicKey)>"u")throw new Error("missing sender public key");if(typeof(t==null?void 0:t.receiverPublicKey)>"u")throw new Error("missing receiver public key")}return{type:e,senderPublicKey:t==null?void 0:t.senderPublicKey,receiverPublicKey:t==null?void 0:t.receiverPublicKey}}function th(t){return t.type===li&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function ih(t){return t.type===Nn}function v_(t){const e=ie.from(t.x,"base64"),i=ie.from(t.y,"base64");return fn([new Uint8Array([4]),e,i])}function E_(t,e){const[i,r,n]=t.split("."),s=ie.from(xg(n),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${i}.${r}`,l=io(c),u=v_(e);if(!h_.verify(fn([o,a]),l,u))throw new Error("Invalid signature");return Aa(t).payload}const x_="irn";function Fs(t){return(t==null?void 0:t.relay)||{protocol:x_}}function $r(t){const e=oE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var I_=Object.defineProperty,__=Object.defineProperties,S_=Object.getOwnPropertyDescriptors,rh=Object.getOwnPropertySymbols,$_=Object.prototype.hasOwnProperty,D_=Object.prototype.propertyIsEnumerable,nh=(t,e,i)=>e in t?I_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Zo=(t,e)=>{for(var i in e||(e={}))$_.call(e,i)&&nh(t,i,e[i]);if(rh)for(var i of rh(e))D_.call(e,i)&&nh(t,i,e[i]);return t},O_=(t,e)=>__(t,S_(e));function A_(t,e="-"){const i={},r="relay"+e;return Object.keys(t).forEach(n=>{if(n.startsWith(r)){const s=n.replace(r,""),o=t[n];i[s]=o}}),i}function sh(t){if(!t.includes("wc:")){const l=Dp(t);l!=null&&l.includes("wc:")&&(t=l)}t=t.includes("wc://")?t.replace("wc://",""):t,t=t.includes("wc:")?t.replace("wc:",""):t;const e=t.indexOf(":"),i=t.indexOf("?")!==-1?t.indexOf("?"):void 0,r=t.substring(0,e),n=t.substring(e+1,i).split("@"),s=typeof i<"u"?t.substring(i):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:r,topic:P_(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:A_(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function P_(t){return t.startsWith("//")?t.substring(2):t}function C_(t,e="-"){const i="relay",r={};return Object.keys(t).forEach(n=>{const s=n,o=i+e+s;t[s]&&(r[o]=t[s])}),r}function oh(t){const e=new URLSearchParams,i=Zo(Zo(O_(Zo({},C_(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(i).sort(([r],[n])=>r.localeCompare(n)).forEach(([r,n])=>{n!==void 0&&e.append(r,String(n))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function is(t,e,i){return`${t}?wc_ev=${i}&topic=${e}`}var B_=Object.defineProperty,T_=Object.defineProperties,R_=Object.getOwnPropertyDescriptors,ah=Object.getOwnPropertySymbols,F_=Object.prototype.hasOwnProperty,N_=Object.prototype.propertyIsEnumerable,ch=(t,e,i)=>e in t?B_(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,U_=(t,e)=>{for(var i in e||(e={}))F_.call(e,i)&&ch(t,i,e[i]);if(ah)for(var i of ah(e))N_.call(e,i)&&ch(t,i,e[i]);return t},k_=(t,e)=>T_(t,R_(e));function qr(t){const e=[];return t.forEach(i=>{const[r,n]=i.split(":");e.push(`${r}:${n}`)}),e}function Sg(t){const e=[];return Object.values(t).forEach(i=>{e.push(...qr(i.accounts))}),[...new Set(e)]}function j_(t){const e=[];return Object.values(t).forEach(i=>{e.push(...i.methods)}),[...new Set(e)]}function L_(t){const e=[];return Object.values(t).forEach(i=>{e.push(...i.events)}),[...new Set(e)]}function M_(t,e){const i=[];return Object.values(t).forEach(r=>{qr(r.accounts).includes(e)&&i.push(...r.methods)}),i}function q_(t,e){const i=[];return Object.values(t).forEach(r=>{qr(r.accounts).includes(e)&&i.push(...r.events)}),i}function so(t){return t.includes(":")}function Dr(t){return so(t)?t.split(":")[0]:t}function lh(t){var e,i,r;const n={};if(!Ht(t))return n;for(const[s,o]of Object.entries(t)){const a=so(s)?[s]:o.chains,c=o.methods||[],l=o.events||[],u=Dr(s);n[u]=k_(U_({},n[u]),{chains:Vt(a,(e=n[u])==null?void 0:e.chains),methods:Vt(c,(i=n[u])==null?void 0:i.methods),events:Vt(l,(r=n[u])==null?void 0:r.events)})}return n}function z_(t){const e={};return t==null||t.forEach(i=>{var r;const[n,s]=i.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[],methods:[]}),e[n].accounts.push(i),(r=e[n].chains)==null||r.push(`${n}:${s}`)}),e}function uh(t,e){e=e.map(r=>r.replace("did:pkh:",""));const i=z_(e);for(const[r,n]of Object.entries(i))n.methods?n.methods=Vt(n.methods,t):n.methods=t,n.events=["chainChanged","accountsChanged"];return i}function V_(t,e){var i,r,n,s,o,a;const c=lh(t),l=lh(e),u={},h=Object.keys(c).concat(Object.keys(l));for(const f of h)u[f]={chains:Vt((i=c[f])==null?void 0:i.chains,(r=l[f])==null?void 0:r.chains),methods:Vt((n=c[f])==null?void 0:n.methods,(s=l[f])==null?void 0:s.methods),events:Vt((o=c[f])==null?void 0:o.events,(a=l[f])==null?void 0:a.events)};return u}const H_={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}},K_={NOT_INITIALIZED:{message:"Not initialized.",code:1},NO_MATCHING_KEY:{message:"No matching key.",code:2},RESTORE_WILL_OVERRIDE:{message:"Restore will override.",code:3},RESUBSCRIBED:{message:"Resubscribed.",code:4},MISSING_OR_INVALID:{message:"Missing or invalid.",code:5},EXPIRED:{message:"Expired.",code:6},UNKNOWN_TYPE:{message:"Unknown type.",code:7},MISMATCHED_TOPIC:{message:"Mismatched topic.",code:8},NON_CONFORMING_NAMESPACES:{message:"Non conforming namespaces.",code:9}};function M(t,e){const{message:i,code:r}=K_[t];return{message:e?`${i} ${e}`:i,code:r}}function fe(t,e){const{message:i,code:r}=H_[t];return{message:e?`${i} ${e}`:i,code:r}}function It(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Ht(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function Ie(t){return typeof t>"u"}function be(t,e){return e&&Ie(t)?!0:typeof t=="string"&&!!t.trim().length}function Hc(t,e){return e&&Ie(t)?!0:typeof t=="number"&&!isNaN(t)}function W_(t,e){const{requiredNamespaces:i}=e,r=Object.keys(t.namespaces),n=Object.keys(i);let s=!0;return Xi(n,r)?(r.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=qr(a),h=i[o];(!Xi(xp(o,h),u)||!Xi(h.methods,c)||!Xi(h.events,l))&&(s=!1)}),s):!1}function Ns(t){return be(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function G_(t){if(be(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const i=e[0]+":"+e[1];return!!e[2]&&Ns(i)}}return!1}function Y_(t){function e(i){try{return typeof new URL(i)<"u"}catch{return!1}}try{if(be(t,!1)){if(e(t))return!0;const i=Dp(t);return e(i)}}catch{}return!1}function Z_(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function J_(t){return t==null?void 0:t.topic}function X_(t,e){let i=null;return be(t==null?void 0:t.publicKey,!1)||(i=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),i}function hh(t){let e=!0;return It(t)?t.length&&(e=t.every(i=>be(i,!1))):e=!1,e}function Q_(t,e,i){let r=null;return It(e)&&e.length?e.forEach(n=>{r||Ns(n)||(r=fe("UNSUPPORTED_CHAINS",`${i}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):Ns(t)||(r=fe("UNSUPPORTED_CHAINS",`${i}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),r}function e8(t,e,i){let r=null;return Object.entries(t).forEach(([n,s])=>{if(r)return;const o=Q_(n,xp(n,s),`${e} ${i}`);o&&(r=o)}),r}function t8(t,e){let i=null;return It(t)?t.forEach(r=>{i||G_(r)||(i=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${r} should be a string and conform to "namespace:chainId:address" format`))}):i=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),i}function i8(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const n=t8(r==null?void 0:r.accounts,`${e} namespace`);n&&(i=n)}),i}function r8(t,e){let i=null;return hh(t==null?void 0:t.methods)?hh(t==null?void 0:t.events)||(i=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):i=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),i}function $g(t,e){let i=null;return Object.values(t).forEach(r=>{if(i)return;const n=r8(r,`${e}, namespace`);n&&(i=n)}),i}function n8(t,e,i){let r=null;if(t&&Ht(t)){const n=$g(t,e);n&&(r=n);const s=e8(t,e,i);s&&(r=s)}else r=M("MISSING_OR_INVALID",`${e}, ${i} should be an object with data`);return r}function Jo(t,e){let i=null;if(t&&Ht(t)){const r=$g(t,e);r&&(i=r);const n=i8(t,e);n&&(i=n)}else i=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return i}function Dg(t){return be(t.protocol,!0)}function s8(t,e){let i=!1;return e&&!t?i=!0:t&&It(t)&&t.length&&t.forEach(r=>{i=Dg(r)}),i}function o8(t){return typeof t=="number"}function Xe(t){return typeof t<"u"&&typeof t!==null}function a8(t){return!(!t||typeof t!="object"||!t.code||!Hc(t.code,!1)||!t.message||!be(t.message,!1))}function c8(t){return!(Ie(t)||!be(t.method,!1))}function l8(t){return!(Ie(t)||Ie(t.result)&&Ie(t.error)||!Hc(t.id,!1)||!be(t.jsonrpc,!1))}function u8(t){return!(Ie(t)||!be(t.name,!1))}function fh(t,e){return!(!Ns(e)||!Sg(t).includes(e))}function h8(t,e,i){return be(i,!1)?M_(t,e).includes(i):!1}function f8(t,e,i){return be(i,!1)?q_(t,e).includes(i):!1}function dh(t,e,i){let r=null;const n=d8(t),s=p8(e),o=Object.keys(n),a=Object.keys(s),c=ph(Object.keys(t)),l=ph(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces keys don't satisfy requiredNamespaces.
|
|
21
|
+
Required: ${u.toString()}
|
|
22
|
+
Received: ${Object.keys(e).toString()}`)),Xi(o,a)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces chains don't satisfy required namespaces.
|
|
23
|
+
Required: ${o.toString()}
|
|
24
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||r)return;const f=qr(e[h].accounts);f.includes(h)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
25
|
+
Required: ${h}
|
|
26
|
+
Approved: ${f.toString()}`))}),o.forEach(h=>{r||(Xi(n[h].methods,s[h].methods)?Xi(n[h].events,s[h].events)||(r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces events don't satisfy namespace events for ${h}`)):r=M("NON_CONFORMING_NAMESPACES",`${i} namespaces methods don't satisfy namespace methods for ${h}`))}),r}function d8(t){const e={};return Object.keys(t).forEach(i=>{var r;i.includes(":")?e[i]=t[i]:(r=t[i].chains)==null||r.forEach(n=>{e[n]={methods:t[i].methods,events:t[i].events}})}),e}function ph(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function p8(t){const e={};return Object.keys(t).forEach(i=>{if(i.includes(":"))e[i]=t[i];else{const r=qr(t[i].accounts);r==null||r.forEach(n=>{e[n]={accounts:t[i].accounts.filter(s=>s.includes(`${n}:`)),methods:t[i].methods,events:t[i].events}})}}),e}function g8(t,e){return Hc(t,!1)&&t<=e.max&&t>=e.min}function gh(){const t=Bn();return new Promise(e=>{switch(t){case ft.browser:e(y8());break;case ft.reactNative:e(w8());break;case ft.node:e(m8());break;default:e(!0)}})}function y8(){return Mr()&&(navigator==null?void 0:navigator.onLine)}async function w8(){if(ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo){const t=await(Y==null?void 0:Y.NetInfo.fetch());return t==null?void 0:t.isConnected}return!0}function m8(){return!0}function b8(t){switch(Bn()){case ft.browser:v8(t);break;case ft.reactNative:E8(t);break}}function v8(t){!ki()&&Mr()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function E8(t){var e;ki()&&typeof Y<"u"&&Y!=null&&Y.NetInfo&&((e=Y)==null||e.NetInfo.addEventListener(i=>t(i==null?void 0:i.isConnected)))}function x8(){var t;return Mr()&&rr()?((t=rr())==null?void 0:t.visibilityState)==="visible":!0}const Xo={};class Qr{static get(e){return Xo[e]}static set(e,i){Xo[e]=i}static delete(e){delete Xo[e]}}function I8(t){const e=An.decode(t);if(e.length<33)throw new Error("Too short to contain a public key");return e.slice(1,33)}function _8({publicKey:t,signature:e,payload:i}){var r;const n=Ka(i.method),s=128|parseInt(((r=i.version)==null?void 0:r.toString())||"4"),o=D8(i.address),a=i.era==="00"?new Uint8Array([0]):Ka(i.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(i.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${$8(i.tip)}`),h=A8(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...n]),d=O8(f.length+1);return new Uint8Array([...d,s,...f])}function S8(t){const e=Ka(t),i=mE.blake2b(e,void 0,32);return"0x"+ie.from(i).toString("hex")}function Ka(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function $8(t){return t.startsWith("0x")?t.slice(2):t}function D8(t){const e=An.decode(t)[0];return e===42?0:e===60?2:1}function O8(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 A8(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 P8(t){const e=Uint8Array.from(ie.from(t.signature,"hex")),i=I8(t.transaction.address),r=_8({publicKey:i,signature:e,payload:t.transaction}),n=ie.from(r).toString("hex");return S8(n)}function Kc({logger:t,name:e}){const i=typeof t=="string"?Ep({opts:{level:t,name:e}}).logger:t;return i.level=typeof t=="string"?t:t.level,i}class ur{}let C8=class extends ur{constructor(e){super()}};const yh=L.FIVE_SECONDS,hr={pulse:"heartbeat_pulse"};let B8=class Og extends C8{constructor(e){super(e),this.events=new St.EventEmitter,this.interval=yh,this.interval=(e==null?void 0:e.interval)||yh}static async init(e){const i=new Og(e);return await i.init(),i}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(hr.pulse)}};const T8=/"(?:_|\\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*:/,R8=/"(?: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*:/,F8=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function N8(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){U8(t);return}return e}function U8(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function rs(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const i=t.trim();if(i.length<=9)switch(i.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(!F8.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(T8.test(t)||R8.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,N8)}return JSON.parse(t)}catch(r){if(e.strict)throw r;return t}}function k8(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function De(t,...e){try{return k8(t(...e))}catch(i){return Promise.reject(i)}}function j8(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function L8(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ps(t){if(j8(t))return String(t);if(L8(t)||Array.isArray(t))return JSON.stringify(t);if(typeof t.toJSON=="function")return ps(t.toJSON());throw new Error("[unstorage] Cannot stringify value!")}const Wa="base64:";function M8(t){return typeof t=="string"?t:Wa+V8(t)}function q8(t){return typeof t!="string"||!t.startsWith(Wa)?t:z8(t.slice(Wa.length))}function z8(t){return globalThis.Buffer?ie.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function V8(t){return globalThis.Buffer?ie.from(t).toString("base64"):globalThis.btoa(String.fromCodePoint(...t))}function Je(t){var e;return t&&((e=t.split("?")[0])==null?void 0:e.replace(/[/\\]/g,":").replace(/:+/g,":").replace(/^:|:$/g,""))||""}function H8(...t){return Je(t.join(":"))}function ns(t){return t=Je(t),t?t+":":""}function K8(t,e){if(e===void 0)return!0;let i=0,r=t.indexOf(":");for(;r>-1;)i++,r=t.indexOf(":",r+1);return i<=e}function W8(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const G8="memory",Y8=()=>{const t=new Map;return{name:G8,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,i){t.set(e,i)},setItemRaw(e,i){t.set(e,i)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function Z8(t={}){const e={mounts:{"":t.driver||Y8()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},i=l=>{for(const u of e.mountpoints)if(l.startsWith(u))return{base:u,relativeKey:l.slice(u.length),driver:e.mounts[u]};return{base:"",relativeKey:l,driver:e.mounts[""]}},r=(l,u)=>e.mountpoints.filter(h=>h.startsWith(l)||u&&l.startsWith(h)).map(h=>({relativeBase:l.length>h.length?l.slice(h.length):void 0,mountpoint:h,driver:e.mounts[h]})),n=(l,u)=>{if(e.watching){u=Je(u);for(const h of e.watchListeners)h(l,u)}},s=async()=>{if(!e.watching){e.watching=!0;for(const l in e.mounts)e.unwatch[l]=await wh(e.mounts[l],n,l)}},o=async()=>{if(e.watching){for(const l in e.unwatch)await e.unwatch[l]();e.unwatch={},e.watching=!1}},a=(l,u,h)=>{const f=new Map,d=p=>{let g=f.get(p.base);return g||(g={driver:p.driver,base:p.base,items:[]},f.set(p.base,g)),g};for(const p of l){const g=typeof p=="string",w=Je(g?p:p.key),_=g?void 0:p.value,C=g||!p.options?u:{...u,...p.options},b=i(w);d(b).items.push({key:w,value:_,relativeKey:b.relativeKey,options:C})}return Promise.all([...f.values()].map(p=>h(p))).then(p=>p.flat())},c={hasItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.hasItem,h,u)},getItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return De(f.getItem,h,u).then(d=>rs(d))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?De(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(d=>({key:H8(h.base,d.key),value:rs(d.value)}))):Promise.all(h.items.map(f=>De(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:rs(d)})))))},getItemRaw(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=i(l);return f.getItemRaw?De(f.getItemRaw,h,u):De(f.getItem,h,u).then(d=>q8(d))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Je(l);const{relativeKey:f,driver:d}=i(l);d.setItem&&(await De(d.setItem,f,ps(u),h),d.watch||n("update",l))},async setItems(l,u){await a(l,u,async h=>{if(h.driver.setItems)return De(h.driver.setItems,h.items.map(f=>({key:f.relativeKey,value:ps(f.value),options:f.options})),u);h.driver.setItem&&await Promise.all(h.items.map(f=>De(h.driver.setItem,f.relativeKey,ps(f.value),f.options)))})},async setItemRaw(l,u,h={}){if(u===void 0)return c.removeItem(l,h);l=Je(l);const{relativeKey:f,driver:d}=i(l);if(d.setItemRaw)await De(d.setItemRaw,f,u,h);else if(d.setItem)await De(d.setItem,f,M8(u),h);else return;d.watch||n("update",l)},async removeItem(l,u={}){typeof u=="boolean"&&(u={removeMeta:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l);f.removeItem&&(await De(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await De(f.removeItem,h+"$",u),f.watch||n("remove",l))},async getMeta(l,u={}){typeof u=="boolean"&&(u={nativeOnly:u}),l=Je(l);const{relativeKey:h,driver:f}=i(l),d=Object.create(null);if(f.getMeta&&Object.assign(d,await De(f.getMeta,h,u)),!u.nativeOnly){const p=await De(f.getItem,h+"$",u).then(g=>rs(g));p&&typeof p=="object"&&(typeof p.atime=="string"&&(p.atime=new Date(p.atime)),typeof p.mtime=="string"&&(p.mtime=new Date(p.mtime)),Object.assign(d,p))}return d},setMeta(l,u,h={}){return this.setItem(l+"$",u,h)},removeMeta(l,u={}){return this.removeItem(l+"$",u)},async getKeys(l,u={}){var w;l=ns(l);const h=r(l,!0);let f=[];const d=[];let p=!0;for(const _ of h){(w=_.driver.flags)!=null&&w.maxDepth||(p=!1);const C=await De(_.driver.getKeys,_.relativeBase,u);for(const b of C){const v=_.mountpoint+Je(b);f.some(O=>v.startsWith(O))||d.push(v)}f=[_.mountpoint,...f.filter(b=>!b.startsWith(_.mountpoint))]}const g=u.maxDepth!==void 0&&!p;return d.filter(_=>(!g||K8(_,u.maxDepth))&&W8(_,l))},async clear(l,u={}){l=ns(l),await Promise.all(r(l,!1).map(async h=>{if(h.driver.clear)return De(h.driver.clear,h.relativeBase,u);if(h.driver.removeItem){const f=await h.driver.getKeys(h.relativeBase||"",u);return Promise.all(f.map(d=>h.driver.removeItem(d,u)))}}))},async dispose(){await Promise.all(Object.values(e.mounts).map(l=>mh(l)))},async watch(l){return await s(),e.watchListeners.push(l),async()=>{e.watchListeners=e.watchListeners.filter(u=>u!==l),e.watchListeners.length===0&&await o()}},async unwatch(){e.watchListeners=[],await o()},mount(l,u){if(l=ns(l),l&&e.mounts[l])throw new Error(`already mounted at ${l}`);return l&&(e.mountpoints.push(l),e.mountpoints.sort((h,f)=>f.length-h.length)),e.mounts[l]=u,e.watching&&Promise.resolve(wh(u,n,l)).then(h=>{e.unwatch[l]=h}).catch(console.error),c},async unmount(l,u=!0){var h,f;l=ns(l),!(!l||!e.mounts[l])&&(e.watching&&l in e.unwatch&&((f=(h=e.unwatch)[l])==null||f.call(h),delete e.unwatch[l]),u&&await mh(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Je(l)+":";const u=i(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Je(l),r(l,u.parents).map(f=>({driver:f.driver,base:f.mountpoint}))},keys:(l,u={})=>c.getKeys(l,u),get:(l,u={})=>c.getItem(l,u),set:(l,u,h={})=>c.setItem(l,u,h),has:(l,u={})=>c.hasItem(l,u),del:(l,u={})=>c.removeItem(l,u),remove:(l,u={})=>c.removeItem(l,u)};return c}function wh(t,e,i){return t.watch?t.watch((r,n)=>e(r,i+n)):()=>{}}async function mh(t){typeof t.dispose=="function"&&await De(t.dispose)}function fr(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ag(t,e){let i;const r=()=>{if(i)return i;const n=indexedDB.open(t);return n.onupgradeneeded=()=>n.result.createObjectStore(e),i=fr(n),i.then(s=>{s.onclose=()=>i=void 0},()=>{}),i};return(n,s)=>r().then(o=>s(o.transaction(e,n).objectStore(e)))}let Qo;function Un(){return Qo||(Qo=Ag("keyval-store","keyval")),Qo}function bh(t,e=Un()){return e("readonly",i=>fr(i.get(t)))}function J8(t,e,i=Un()){return i("readwrite",r=>(r.put(e,t),fr(r.transaction)))}function X8(t,e=Un()){return e("readwrite",i=>(i.delete(t),fr(i.transaction)))}function Q8(t=Un()){return t("readwrite",e=>(e.clear(),fr(e.transaction)))}function eS(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},fr(t.transaction)}function tS(t=Un()){return t("readonly",e=>{if(e.getAllKeys)return fr(e.getAllKeys());const i=[];return eS(e,r=>i.push(r.key)).then(()=>i)})}const iS="idb-keyval";var rS=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",i=n=>e+n;let r;return t.dbName&&t.storeName&&(r=Ag(t.dbName,t.storeName)),{name:iS,options:t,async hasItem(n){return!(typeof await bh(i(n),r)>"u")},async getItem(n){return await bh(i(n),r)??null},setItem(n,s){return J8(i(n),s,r)},removeItem(n){return X8(i(n),r)},getKeys(){return tS(r)},clear(){return Q8(r)}}};const nS="WALLET_CONNECT_V2_INDEXED_DB",sS="keyvaluestorage";let oS=class{constructor(){this.indexedDb=Z8({driver:rS({dbName:nS,storeName:sS})})}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 i=await this.indexedDb.getItem(e);if(i!==null)return i}async setItem(e,i){await this.indexedDb.setItem(e,ui(i))}async removeItem(e){await this.indexedDb.removeItem(e)}};var ea=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof Y<"u"?Y:typeof self<"u"?self:{},gs={exports:{}};(function(){let t;function e(){}t=e,t.prototype.getItem=function(i){return this.hasOwnProperty(i)?String(this[i]):null},t.prototype.setItem=function(i,r){this[i]=String(r)},t.prototype.removeItem=function(i){delete this[i]},t.prototype.clear=function(){const i=this;Object.keys(i).forEach(function(r){i[r]=void 0,delete i[r]})},t.prototype.key=function(i){return i=i||0,Object.keys(this)[i]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ea<"u"&&ea.localStorage?gs.exports=ea.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function aS(t){var e;return[t[0],sr((e=t[1])!=null?e:"")]}let cS=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(aS)}async getItem(e){const i=this.localStorage.getItem(e);if(i!==null)return sr(i)}async setItem(e,i){this.localStorage.setItem(e,ui(i))}async removeItem(e){this.localStorage.removeItem(e)}};const lS="wc_storage_version",vh=1,uS=async(t,e,i)=>{const r=lS,n=await e.getItem(r);if(n&&n>=vh){i(e);return}const s=await t.getKeys();if(!s.length){i(e);return}const o=[];for(;s.length;){const a=s.shift();if(!a)continue;const c=a.toLowerCase();if(c.includes("wc@")||c.includes("walletconnect")||c.includes("wc_")||c.includes("wallet_connect")){const l=await t.getItem(a);await e.setItem(a,l),o.push(a)}}await e.setItem(r,vh),i(e),hS(t,o)},hS=async(t,e)=>{e.length&&e.forEach(async i=>{await t.removeItem(i)})};let fS=class{constructor(){this.initialized=!1,this.setInitialized=i=>{this.storage=i,this.initialized=!0};const e=new cS;this.storage=e;try{const i=new oS;uS(e,i,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,i){return await this.initialize(),this.storage.setItem(e,i)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const i=setInterval(()=>{this.initialized&&(clearInterval(i),e())},20)})}};var dS=Object.defineProperty,pS=(t,e,i)=>e in t?dS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Eh=(t,e,i)=>pS(t,typeof e!="symbol"?e+"":e,i);let gS=class extends ur{constructor(e){super(),this.opts=e,Eh(this,"protocol","wc"),Eh(this,"version",2)}};var yS=Object.defineProperty,wS=(t,e,i)=>e in t?yS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,mS=(t,e,i)=>wS(t,typeof e!="symbol"?e+"":e,i);let bS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i,mS(this,"records",new Map)}},vS=class{constructor(e,i){this.logger=e,this.core=i}},ES=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},xS=class extends ur{constructor(e){super()}},IS=class{constructor(e,i,r,n){this.core=e,this.logger=i,this.name=r}},_S=class extends ur{constructor(e,i){super(),this.relayer=e,this.logger=i}},SS=class extends ur{constructor(e,i){super(),this.core=e,this.logger=i}},$S=class{constructor(e,i,r){this.core=e,this.logger=i,this.store=r}},DS=class{constructor(e,i){this.projectId=e,this.logger=i}},OS=class{constructor(e,i,r){this.core=e,this.logger=i,this.telemetryEnabled=r}};var AS=Object.defineProperty,PS=(t,e,i)=>e in t?AS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xh=(t,e,i)=>PS(t,typeof e!="symbol"?e+"":e,i);let CS=class{constructor(e){this.opts=e,xh(this,"protocol","wc"),xh(this,"version",2)}},BS=class{constructor(e){this.client=e}};const TS="PARSE_ERROR",RS="INVALID_REQUEST",FS="METHOD_NOT_FOUND",NS="INVALID_PARAMS",Pg="INTERNAL_ERROR",Wc="SERVER_ERROR",US=[-32700,-32600,-32601,-32602,-32603],pn={[TS]:{code:-32700,message:"Parse error"},[RS]:{code:-32600,message:"Invalid Request"},[FS]:{code:-32601,message:"Method not found"},[NS]:{code:-32602,message:"Invalid params"},[Pg]:{code:-32603,message:"Internal error"},[Wc]:{code:-32e3,message:"Server error"}},Cg=Wc;function kS(t){return US.includes(t)}function Ih(t){return Object.keys(pn).includes(t)?pn[t]:pn[Cg]}function jS(t){const e=Object.values(pn).find(i=>i.code===t);return e||pn[Cg]}function Bg(t,e,i){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${i} RPC url at ${e}`):t}var Tg={},Qt={},_h;function LS(){if(_h)return Qt;_h=1,Object.defineProperty(Qt,"__esModule",{value:!0}),Qt.isBrowserCryptoAvailable=Qt.getSubtleCrypto=Qt.getBrowerCrypto=void 0;function t(){return(pr===null||pr===void 0?void 0:pr.crypto)||(pr===null||pr===void 0?void 0:pr.msCrypto)||{}}Qt.getBrowerCrypto=t;function e(){const r=t();return r.subtle||r.webkitSubtle}Qt.getSubtleCrypto=e;function i(){return!!t()&&!!e()}return Qt.isBrowserCryptoAvailable=i,Qt}var ei={},Sh;function MS(){if(Sh)return ei;Sh=1,Object.defineProperty(ei,"__esModule",{value:!0}),ei.isBrowser=ei.isNode=ei.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}ei.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}ei.isNode=e;function i(){return!t()&&!e()}return ei.isBrowser=i,ei}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=$n;e.__exportStar(LS(),t),e.__exportStar(MS(),t)})(Tg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),i=Math.floor(Math.random()*Math.pow(10,t));return e+i}function Ri(t=6){return BigInt(Lt(t))}function Ct(t,e,i){return{id:i||Lt(),jsonrpc:"2.0",method:t,params:e}}function Sn(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,i){return{id:t,jsonrpc:"2.0",error:qS(e,i)}}function qS(t,e){return typeof t>"u"?Ih(Pg):(typeof t=="string"&&(t=Object.assign(Object.assign({},Ih(Wc)),{message:t})),typeof e<"u"&&(t.data=e),kS(t.code)&&(t=jS(t.code)),t)}class zS{}class VS extends zS{constructor(){super()}}class HS extends VS{constructor(e){super()}}const KS="^https?:",WS="^wss?:";function GS(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Rg(t,e){const i=GS(t);return typeof i>"u"?!1:new RegExp(e).test(i)}function $h(t){return Rg(t,KS)}function Dh(t){return Rg(t,WS)}function YS(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function Fg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Gc(t){return Fg(t)&&"method"in t}function ao(t){return Fg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Yc extends HS{constructor(e){super(e),this.events=new St.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,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async request(e,i){return this.requestStrict(Ct(e.method,e.params||[],e.id||Ri().toString()),i)}async requestStrict(e,i){return new Promise(async(r,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):r(s.result)});try{await this.connection.send(e,i)}catch(s){n(s)}})}setConnection(e=this.connection){return e}onPayload(e){this.events.emit("payload",e),ao(e)?this.events.emit(`${e.id}`,e):this.events.emit("message",{type:e.method,data:e.params})}onClose(e){e&&e.code===3e3&&this.events.emit("error",new Error(`WebSocket connection closed abnormally with code: ${e.code} ${e.reason?`(${e.reason})`:""}`)),this.events.emit("disconnect")}async open(e=this.connection){this.connection===e&&this.connection.connected||(this.connection.connected&&this.close(),typeof e=="string"&&(await this.connection.open(e),e=this.connection),this.connection=this.setConnection(e),await this.connection.open(),this.registerEventListeners(),this.events.emit("connect"))}async close(){await this.connection.close()}registerEventListeners(){this.hasRegisteredEventListeners||(this.connection.on("payload",e=>this.onPayload(e)),this.connection.on("close",e=>this.onClose(e)),this.connection.on("error",e=>this.events.emit("error",e)),this.connection.on("register_error",e=>this.onClose()),this.hasRegisteredEventListeners=!0)}}const ZS=()=>typeof WebSocket<"u"?WebSocket:typeof Y<"u"&&typeof Y.WebSocket<"u"?Y.WebSocket:typeof window<"u"&&typeof window.WebSocket<"u"?window.WebSocket:typeof self<"u"&&typeof self.WebSocket<"u"?self.WebSocket:require("ws"),JS=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Oh=t=>t.split("?")[0],Ah=10,XS=ZS();let QS=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Dh(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,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,i)=>{if(typeof this.socket>"u"){i(new Error("Connection already closed"));return}this.socket.onclose=r=>{this.onClose(r),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(ui(e))}catch(i){this.onError(e.id,i)}}register(e=this.url){if(!Dh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.socket>"u")return n(new Error("WebSocket connection is missing or invalid"));r(this.socket)})})}return this.url=e,this.registering=!0,new Promise((i,r)=>{const n=Tg.isReactNative()?void 0:{rejectUnauthorized:!YS(e)},s=new XS(e,[],n);JS()?s.onerror=o=>{const a=o;r(this.emitError(a.error))}:s.on("error",o=>{r(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),i(s)}})}onOpen(e){e.onmessage=i=>this.onPayload(i),e.onclose=i=>this.onClose(i),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 i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,Oh(i),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Ah&&this.events.setMaxListeners(Ah)}emitError(e){const i=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Oh(this.url)}`));return this.events.emit("register_error",i),i}};const Ng="wc",Ug=2,Us="core",Kt=`${Ng}@2:${Us}:`,e$={name:Us,logger:"error"},t$={database:":memory:"},i$="crypto",Ph="client_ed25519_seed",r$=L.ONE_DAY,n$="keychain",s$="0.3",o$="messages",a$="0.3",c$=L.SIX_HOURS,l$="publisher",kg="irn",u$="error",jg="wss://relay.walletconnect.org",h$="relayer",me={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"},f$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},d$=.1,Ga="2.23.0",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},p$="0.3",g$="WALLETCONNECT_CLIENT_ID",Ch="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},y$="subscription",w$="0.3",m$="pairing",b$="0.3",en={wc_pairingDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1e3},res:{ttl:L.ONE_DAY,prompt:!1,tag:1001}},wc_pairingPing:{req:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1002},res:{ttl:L.THIRTY_SECONDS,prompt:!1,tag:1003}},unregistered_method:{req:{ttl:L.ONE_DAY,prompt:!1,tag:0},res:{ttl:L.ONE_DAY,prompt:!1,tag:0}}},Yi={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Dt={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},v$="history",E$="0.3",x$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},I$="0.3",_$="verify-api",S$="https://verify.walletconnect.com",Lg="https://verify.walletconnect.org",gn=Lg,$$=`${gn}/v3`,D$=[S$,Lg],O$="echo",A$="https://echo.walletconnect.com",jt={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"},ii={no_wss_connection:"no_wss_connection",no_internet_connection:"no_internet_connection",malformed_pairing_uri:"malformed_pairing_uri",active_pairing_already_exists:"active_pairing_already_exists",subscribe_pairing_topic_failure:"subscribe_pairing_topic_failure",pairing_expired:"pairing_expired",proposal_expired:"proposal_expired",proposal_listener_not_found:"proposal_listener_not_found"},Ot={session_approve_started:"session_approve_started",proposal_not_expired:"proposal_not_expired",session_namespaces_validation_success:"session_namespaces_validation_success",create_session_topic:"create_session_topic",subscribing_session_topic:"subscribing_session_topic",subscribe_session_topic_success:"subscribe_session_topic_success",publishing_session_approve:"publishing_session_approve",session_approve_publish_success:"session_approve_publish_success",store_session:"store_session",publishing_session_settle:"publishing_session_settle",session_settle_publish_success:"session_settle_publish_success",session_request_response_started:"session_request_response_started",session_request_response_validation_success:"session_request_response_validation_success",session_request_response_publish_started:"session_request_response_publish_started"},zi={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"},Vi={authenticated_session_approve_started:"authenticated_session_approve_started",authenticated_session_not_expired:"authenticated_session_not_expired",chains_caip2_compliant:"chains_caip2_compliant",chains_evm_compliant:"chains_evm_compliant",create_authenticated_session_topic:"create_authenticated_session_topic",cacaos_verified:"cacaos_verified",store_authenticated_session:"store_authenticated_session",subscribing_authenticated_session_topic:"subscribing_authenticated_session_topic",subscribe_authenticated_session_topic_success:"subscribe_authenticated_session_topic_success",publishing_authenticated_session_approve:"publishing_authenticated_session_approve",authenticated_session_approve_publish_success:"authenticated_session_approve_publish_success"},tn={no_internet_connection:"no_internet_connection",no_wss_connection:"no_wss_connection",missing_session_authenticate_request:"missing_session_authenticate_request",session_authenticate_request_expired:"session_authenticate_request_expired",chains_caip2_compliant_failure:"chains_caip2_compliant_failure",chains_evm_compliant_failure:"chains_evm_compliant_failure",invalid_cacao:"invalid_cacao",subscribe_authenticated_session_topic_failure:"subscribe_authenticated_session_topic_failure",authenticated_session_approve_publish_failure:"authenticated_session_approve_publish_failure",authenticated_session_pending_request_not_found:"authenticated_session_pending_request_not_found"},P$=.1,C$="event-client",B$=86400,T$="https://pulse.walletconnect.org/batch";function R$(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var i=new Uint8Array(256),r=0;r<i.length;r++)i[r]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(i[o]!==255)throw new TypeError(s+" is ambiguous");i[o]=n}var a=t.length,c=t.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function h(p){if(p instanceof Uint8Array||(ArrayBuffer.isView(p)?p=new Uint8Array(p.buffer,p.byteOffset,p.byteLength):Array.isArray(p)&&(p=Uint8Array.from(p))),!(p instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(p.length===0)return"";for(var g=0,w=0,_=0,C=p.length;_!==C&&p[_]===0;)_++,g++;for(var b=(C-_)*u+1>>>0,v=new Uint8Array(b);_!==C;){for(var O=p[_],P=0,T=b-1;(O!==0||P<w)&&T!==-1;T--,P++)O+=256*v[T]>>>0,v[T]=O%a>>>0,O=O/a>>>0;if(O!==0)throw new Error("Non-zero carry");w=P,_++}for(var R=b-w;R!==b&&v[R]===0;)R++;for(var A=c.repeat(g);R<b;++R)A+=t.charAt(v[R]);return A}function f(p){if(typeof p!="string")throw new TypeError("Expected String");if(p.length===0)return new Uint8Array;var g=0;if(p[g]!==" "){for(var w=0,_=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=i[p.charCodeAt(g)];if(v===255)return;for(var O=0,P=C-1;(v!==0||O<_)&&P!==-1;P--,O++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");_=O,g++}if(p[g]!==" "){for(var T=C-_;T!==C&&b[T]===0;)T++;for(var R=new Uint8Array(w+(C-T)),A=w;T!==C;)R[A++]=b[T++];return R}}}function d(p){var g=f(p);if(g)return g;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:f,decode:d}}var F$=R$,N$=F$;const Mg=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")},U$=t=>new TextEncoder().encode(t),k$=t=>new TextDecoder().decode(t);class j${constructor(e,i,r){this.name=e,this.prefix=i,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class L${constructor(e,i,r){if(this.name=e,this.prefix=i,i.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i.codePointAt(0),this.baseDecode=r}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return qg(this,e)}}class M${constructor(e){this.decoders=e}or(e){return qg(this,e)}decode(e){const i=e[0],r=this.decoders[i];if(r)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const qg=(t,e)=>new M$({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class q${constructor(e,i,r,n){this.name=e,this.prefix=i,this.baseEncode=r,this.baseDecode=n,this.encoder=new j$(e,i,r),this.decoder=new L$(e,i,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:i,decode:r})=>new q$(t,e,i,r),kn=({prefix:t,name:e,alphabet:i})=>{const{encode:r,decode:n}=N$(i,e);return co({prefix:t,name:e,encode:r,decode:s=>Mg(n(s))})},z$=(t,e,i,r)=>{const n={};for(let u=0;u<e.length;++u)n[e[u]]=u;let s=t.length;for(;t[s-1]==="=";)--s;const o=new Uint8Array(s*i/8|0);let a=0,c=0,l=0;for(let u=0;u<s;++u){const h=n[t[u]];if(h===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<i|h,a+=i,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=i||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},V$=(t,e,i)=>{const r=e[e.length-1]==="=",n=(1<<i)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>i;)o-=i,s+=e[n&a>>o];if(o&&(s+=e[n&a<<i-o]),r)for(;s.length*i&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:i,alphabet:r})=>co({prefix:e,name:t,encode(n){return V$(n,r,i)},decode(n){return z$(n,r,i,t)}}),H$=co({prefix:"\0",name:"identity",encode:t=>k$(t),decode:t=>U$(t)});var K$=Object.freeze({__proto__:null,identity:H$});const W$=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var G$=Object.freeze({__proto__:null,base2:W$});const Y$=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var Z$=Object.freeze({__proto__:null,base8:Y$});const J$=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var X$=Object.freeze({__proto__:null,base10:J$});const Q$=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),e6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var t6=Object.freeze({__proto__:null,base16:Q$,base16upper:e6});const i6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),r6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),n6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),s6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),o6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),a6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),c6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),l6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),u6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var h6=Object.freeze({__proto__:null,base32:i6,base32upper:r6,base32pad:n6,base32padupper:s6,base32hex:o6,base32hexupper:a6,base32hexpad:c6,base32hexpadupper:l6,base32z:u6});const f6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),d6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var p6=Object.freeze({__proto__:null,base36:f6,base36upper:d6});const g6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),y6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var w6=Object.freeze({__proto__:null,base58btc:g6,base58flickr:y6});const m6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),b6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),v6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),E6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var x6=Object.freeze({__proto__:null,base64:m6,base64pad:b6,base64url:v6,base64urlpad:E6});const zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),I6=zg.reduce((t,e,i)=>(t[i]=e,t),[]),_6=zg.reduce((t,e,i)=>(t[e.codePointAt(0)]=i,t),[]);function S6(t){return t.reduce((e,i)=>(e+=I6[i],e),"")}function $6(t){const e=[];for(const i of t){const r=_6[i.codePointAt(0)];if(r===void 0)throw new Error(`Non-base256emoji character: ${i}`);e.push(r)}return new Uint8Array(e)}const D6=co({prefix:"🚀",name:"base256emoji",encode:S6,decode:$6});var O6=Object.freeze({__proto__:null,base256emoji:D6}),A6=Vg,Bh=128,P6=127,C6=~P6,B6=Math.pow(2,31);function Vg(t,e,i){e=e||[],i=i||0;for(var r=i;t>=B6;)e[i++]=t&255|Bh,t/=128;for(;t&C6;)e[i++]=t&255|Bh,t>>>=7;return e[i]=t|0,Vg.bytes=i-r+1,e}var T6=Ya,R6=128,Th=127;function Ya(t,r){var i=0,r=r||0,n=0,s=r,o,a=t.length;do{if(s>=a)throw Ya.bytes=0,new RangeError("Could not decode varint");o=t[s++],i+=n<28?(o&Th)<<n:(o&Th)*Math.pow(2,n),n+=7}while(o>=R6);return Ya.bytes=s-r,i}var F6=Math.pow(2,7),N6=Math.pow(2,14),U6=Math.pow(2,21),k6=Math.pow(2,28),j6=Math.pow(2,35),L6=Math.pow(2,42),M6=Math.pow(2,49),q6=Math.pow(2,56),z6=Math.pow(2,63),V6=function(t){return t<F6?1:t<N6?2:t<U6?3:t<k6?4:t<j6?5:t<L6?6:t<M6?7:t<q6?8:t<z6?9:10},H6={encode:A6,decode:T6,encodingLength:V6},Hg=H6;const Rh=(t,e,i=0)=>(Hg.encode(t,e,i),e),Fh=t=>Hg.encodingLength(t),Za=(t,e)=>{const i=e.byteLength,r=Fh(t),n=r+Fh(i),s=new Uint8Array(n+i);return Rh(t,s,0),Rh(i,s,r),s.set(e,n),new K6(t,i,e,s)};class K6{constructor(e,i,r,n){this.code=e,this.size=i,this.digest=r,this.bytes=n}}const Kg=({name:t,code:e,encode:i})=>new W6(t,e,i);class W6{constructor(e,i,r){this.name=e,this.code=i,this.encode=r}digest(e){if(e instanceof Uint8Array){const i=this.encode(e);return i instanceof Uint8Array?Za(this.code,i):i.then(r=>Za(this.code,r))}else throw Error("Unknown type, must be binary type")}}const Wg=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),G6=Kg({name:"sha2-256",code:18,encode:Wg("SHA-256")}),Y6=Kg({name:"sha2-512",code:19,encode:Wg("SHA-512")});var Z6=Object.freeze({__proto__:null,sha256:G6,sha512:Y6});const Gg=0,J6="identity",Yg=Mg,X6=t=>Za(Gg,Yg(t)),Q6={code:Gg,name:J6,encode:Yg,digest:X6};var eD=Object.freeze({__proto__:null,identity:Q6});new TextEncoder,new TextDecoder;const Nh={...K$,...G$,...Z$,...X$,...t6,...h6,...p6,...w6,...x6,...O6};({...Z6,...eD});function Zg(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function tD(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Zg(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Jg(t,e,i,r){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:i},decoder:{decode:r}}}const Uh=Jg("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ta=Jg("ascii","a",t=>{let e="a";for(let i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},t=>{t=t.substring(1);const e=tD(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}),iD={utf8:Uh,"utf-8":Uh,hex:Nh.base16,latin1:ta,ascii:ta,binary:ta,...Nh};function rD(t,e="utf8"){const i=iD[e];if(!i)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Zg(globalThis.Buffer.from(t,"utf-8")):i.decoder.decode(`${i.prefix}${t}`)}var nD=Object.defineProperty,sD=(t,e,i)=>e in t?nD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ut=(t,e,i)=>sD(t,typeof e!="symbol"?e+"":e,i);class oD{constructor(e,i){this.core=e,this.logger=i,Ut(this,"keychain",new Map),Ut(this,"name",n$),Ut(this,"version",s$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Kt),Ut(this,"init",async()=>{if(!this.initialized){const r=await this.getKeyChain();typeof r<"u"&&(this.keychain=r),this.initialized=!0}}),Ut(this,"has",r=>(this.isInitialized(),this.keychain.has(r))),Ut(this,"set",async(r,n)=>{this.isInitialized(),this.keychain.set(r,n),await this.persist()}),Ut(this,"get",r=>{this.isInitialized();const n=this.keychain.get(r);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${r}`);throw new Error(s)}return n}),Ut(this,"del",async r=>{this.isInitialized(),this.keychain.delete(r),await this.persist()}),this.core=e,this.logger=dt(i,this.name)}get context(){return st(this.logger)}get storageKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//"+this.name}async setKeyChain(e){await this.core.storage.setItem(this.storageKey,Ta(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setKeyChain(this.keychain)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var aD=Object.defineProperty,cD=(t,e,i)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Se=(t,e,i)=>cD(t,typeof e!="symbol"?e+"":e,i);class lD{constructor(e,i,r){this.core=e,this.logger=i,Se(this,"name",i$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ha()),Se(this,"initialized",!1),Se(this,"clientId"),Se(this,"init",async()=>{this.initialized||(await this.keychain.init(),this.initialized=!0)}),Se(this,"hasKeys",n=>(this.isInitialized(),this.keychain.has(n))),Se(this,"getClientId",async()=>{if(this.isInitialized(),this.clientId)return this.clientId;const n=await this.getClientSeed(),s=lu(n),o=Xd(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=d_();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=lu(s),a=this.randomSessionIdentifier;return await l2(a,n,r$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=p_(a,s);return this.setSymKey(c,o)}),Se(this,"setSymKey",async(n,s)=>{this.isInitialized();const o=s||ds(n);return await this.keychain.set(o,n),o}),Se(this,"deleteKeyPair",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"deleteSymKey",async n=>{this.isInitialized(),await this.keychain.del(n)}),Se(this,"encode",async(n,s,o)=>{this.isInitialized();const a=_g(o),c=ui(s);if(ih(a))return w_(c,o==null?void 0:o.encoding);if(th(a)){const f=a.senderPublicKey,d=a.receiverPublicKey;n=await this.generateSharedKey(f,d)}const l=this.getSymKey(n),{type:u,senderPublicKey:h}=a;return g_({type:u,symKey:l,message:c,senderPublicKey:h,encoding:o==null?void 0:o.encoding})}),Se(this,"decode",async(n,s,o)=>{this.isInitialized();const a=b_(s,o);if(ih(a)){const c=m_(s,o==null?void 0:o.encoding);return sr(c)}if(th(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=y_({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return sr(l)}catch(c){this.logger.error(`Failed to decode message from topic: '${n}', clientId: '${await this.getClientId()}'`),this.logger.error(c)}}),Se(this,"getPayloadType",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return ar(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=_n({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(i,this.name),this.keychain=r||new oD(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,i){return await this.keychain.set(e,i),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Ph)}catch{e=Ha(),await this.keychain.set(Ph,e)}return rD(e,"base16")}getSymKey(e){return this.keychain.get(e)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var uD=Object.defineProperty,hD=Object.defineProperties,fD=Object.getOwnPropertyDescriptors,kh=Object.getOwnPropertySymbols,dD=Object.prototype.hasOwnProperty,pD=Object.prototype.propertyIsEnumerable,Ja=(t,e,i)=>e in t?uD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,gD=(t,e)=>{for(var i in e||(e={}))dD.call(e,i)&&Ja(t,i,e[i]);if(kh)for(var i of kh(e))pD.call(e,i)&&Ja(t,i,e[i]);return t},yD=(t,e)=>hD(t,fD(e)),ot=(t,e,i)=>Ja(t,typeof e!="symbol"?e+"":e,i);class wD extends vS{constructor(e,i){super(e,i),this.logger=e,this.core=i,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",o$),ot(this,"version",a$),ot(this,"initialized",!1),ot(this,"storagePrefix",Kt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const r=await this.getRelayerMessages();typeof r<"u"&&(this.messages=r);const n=await this.getRelayerMessagesWithoutClientAck();typeof n<"u"&&(this.messagesWithoutClientAck=n),this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",size:this.messages.size})}catch(r){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(r)}finally{this.initialized=!0}}}),ot(this,"set",async(r,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(r);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(r,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(r)||{};this.messagesWithoutClientAck.set(r,yD(gD({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",r=>{this.isInitialized();let n=this.messages.get(r);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",r=>{this.isInitialized();const n={};for(const s of r){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(r,n)=>{this.isInitialized();const s=this.get(r),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(r,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(r);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(r):this.messagesWithoutClientAck.set(r,s),await this.persist()}),ot(this,"del",async r=>{this.isInitialized(),this.messages.delete(r),this.messagesWithoutClientAck.delete(r),await this.persist()}),this.logger=dt(e,this.name),this.core=i}get context(){return st(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,Ta(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ta(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Ra(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Ra(e):void 0}async persist(){await this.setRelayerMessages(this.messages),await this.setRelayerMessagesWithoutClientAck(this.messagesWithoutClientAck)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var mD=Object.defineProperty,bD=Object.defineProperties,vD=Object.getOwnPropertyDescriptors,jh=Object.getOwnPropertySymbols,ED=Object.prototype.hasOwnProperty,xD=Object.prototype.propertyIsEnumerable,Xa=(t,e,i)=>e in t?mD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,vr=(t,e)=>{for(var i in e||(e={}))ED.call(e,i)&&Xa(t,i,e[i]);if(jh)for(var i of jh(e))xD.call(e,i)&&Xa(t,i,e[i]);return t},Lh=(t,e)=>bD(t,vD(e)),yt=(t,e,i)=>Xa(t,typeof e!="symbol"?e+"":e,i);class ID extends ES{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,yt(this,"events",new St.EventEmitter),yt(this,"name",l$),yt(this,"queue",new Map),yt(this,"publishTimeout",L.toMiliseconds(L.ONE_MINUTE)),yt(this,"initialPublishTimeout",L.toMiliseconds(L.ONE_SECOND*15)),yt(this,"needsTransportRestart",!1),yt(this,"publish",async(r,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:r,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||c$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Ri().toString(),g=$r(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:vr({topic:r,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},_=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{Ie((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),Ie((c=w.params)==null?void 0:c.tag)&&((l=w.params)==null||delete l.tag);const C=new Promise(async b=>{const v=({id:P})=>{var T;((T=w.id)==null?void 0:T.toString())===P.toString()&&(this.removeRequestFromQueue(P),this.relayer.events.removeListener(me.publish,v),b())};this.relayer.events.on(me.publish,v);const O=zt(new Promise((P,T)=>{this.rpcPublish(w,s).then(P).catch(R=>{this.logger.warn(R,R==null?void 0:R.message),T(R)})}),this.initialPublishTimeout,`Failed initial publish, retrying.... id:${p} tag:${d}`);try{await O,this.events.removeListener(me.publish,v)}catch(P){this.queue.set(p,{request:w,opts:s,attempt:1}),this.logger.warn(P,P==null?void 0:P.message)}});this.logger.trace({type:"method",method:"publish",params:{id:p,topic:r,message:n,opts:s}}),await zt(C,this.publishTimeout,_)}catch(C){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(C),(u=s==null?void 0:s.internal)!=null&&u.throwOnFailedPublish)throw C}finally{this.queue.delete(p)}}),yt(this,"publishCustom",async r=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:r});const{payload:l,opts:u={}}=r,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,_=u.id||Ri().toString(),C=$r(Fs().protocol),b=d||C.publish,v={id:_,method:b,params:vr(Lh(vr({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},O=`Failed to publish custom payload, please try again. id:${_} tag:${g}`;try{Ie((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),Ie((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const P=new Promise(async T=>{const R=({id:U})=>{var j;((j=v.id)==null?void 0:j.toString())===U.toString()&&(this.removeRequestFromQueue(U),this.relayer.events.removeListener(me.publish,R),T())};this.relayer.events.on(me.publish,R);const A=zt(new Promise((U,j)=>{this.rpcPublish(v,u).then(U).catch(B=>{this.logger.warn(B,B==null?void 0:B.message),j(B)})}),this.initialPublishTimeout,`Failed initial custom payload publish, retrying.... method:${b} id:${_} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(_,{request:v,opts:u,attempt:1}),this.logger.warn(U,U==null?void 0:U.message)}});this.logger.trace({type:"method",method:"publish",params:{id:_,payload:l,opts:u}}),await zt(P,this.publishTimeout,O)}catch(P){if(this.logger.debug("Failed to Publish Payload"),this.logger.error(P),(c=u==null?void 0:u.internal)!=null&&c.throwOnFailedPublish)throw P}finally{this.queue.delete(_)}}),yt(this,"on",(r,n)=>{this.events.on(r,n)}),yt(this,"once",(r,n)=>{this.events.once(r,n)}),yt(this,"off",(r,n)=>{this.events.off(r,n)}),yt(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.relayer=e,this.logger=dt(i,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,i){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const r=await this.relayer.request(e);return this.relayer.events.emit(me.publish,vr(vr({},e),i)),this.logger.debug("Successfully Published Payload"),r}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,i)=>{var r;const n=e.attempt+1;this.queue.set(i,Lh(vr({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(r=e.request.params)==null?void 0:r.tag}, attempt: ${n}`),await this.rpcPublish(e.request,e.opts),this.logger.warn({},`Publisher: queue->published: ${e.request.id}`)})}registerEventListeners(){this.relayer.core.heartbeat.on(hr.pulse,()=>{if(this.needsTransportRestart){this.needsTransportRestart=!1,this.relayer.events.emit(me.connection_stalled);return}this.checkQueue()}),this.relayer.on(me.message_ack,e=>{this.removeRequestFromQueue(e.id.toString())})}}var _D=Object.defineProperty,SD=(t,e,i)=>e in t?_D(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Er=(t,e,i)=>SD(t,typeof e!="symbol"?e+"":e,i);class $D{constructor(){Er(this,"map",new Map),Er(this,"set",(e,i)=>{const r=this.get(e);this.exists(e,i)||this.map.set(e,[...r,i])}),Er(this,"get",e=>this.map.get(e)||[]),Er(this,"exists",(e,i)=>this.get(e).includes(i)),Er(this,"delete",(e,i)=>{if(typeof i>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const r=this.get(e);if(!this.exists(e,i))return;const n=r.filter(s=>s!==i);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),Er(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var DD=Object.defineProperty,OD=Object.defineProperties,AD=Object.getOwnPropertyDescriptors,Mh=Object.getOwnPropertySymbols,PD=Object.prototype.hasOwnProperty,CD=Object.prototype.propertyIsEnumerable,Qa=(t,e,i)=>e in t?DD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,rn=(t,e)=>{for(var i in e||(e={}))PD.call(e,i)&&Qa(t,i,e[i]);if(Mh)for(var i of Mh(e))CD.call(e,i)&&Qa(t,i,e[i]);return t},ia=(t,e)=>OD(t,AD(e)),ce=(t,e,i)=>Qa(t,typeof e!="symbol"?e+"":e,i);class BD extends _S{constructor(e,i){super(e,i),this.relayer=e,this.logger=i,ce(this,"subscriptions",new Map),ce(this,"topicMap",new $D),ce(this,"events",new St.EventEmitter),ce(this,"name",y$),ce(this,"version",w$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Kt),ce(this,"subscribeTimeout",L.toMiliseconds(L.ONE_MINUTE)),ce(this,"initialSubscribeTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ce(this,"clientId"),ce(this,"batchSubscribeTopicsLimit",500),ce(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),this.registerEventListeners(),await this.restore()),this.initialized=!0}),ce(this,"subscribe",async(r,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}});try{const o=Fs(n),a={topic:r,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(r,a);const c=await this.rpcSubscribe(r,o,n);return typeof c=="string"&&(this.onSubscribe(c,a),this.logger.debug("Successfully Subscribed Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:r,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(r,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(r,n.id,n):await this.unsubscribeByTopic(r,n)}),ce(this,"isSubscribed",r=>new Promise(n=>{n(this.topicMap.topics.includes(r))})),ce(this,"isKnownTopic",r=>new Promise(n=>{n(this.topicMap.topics.includes(r)||this.pending.has(r)||this.cached.some(s=>s.topic===r))})),ce(this,"on",(r,n)=>{this.events.on(r,n)}),ce(this,"once",(r,n)=>{this.events.once(r,n)}),ce(this,"off",(r,n)=>{this.events.off(r,n)}),ce(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),ce(this,"start",async()=>{await this.onConnect()}),ce(this,"stop",async()=>{await this.onDisconnect()}),ce(this,"restart",async()=>{await this.restore(),await this.onRestart()}),ce(this,"checkPending",async()=>{if(this.pending.size===0&&(!this.initialized||!this.relayer.connected))return;const r=[];this.pending.forEach(n=>{r.push(n)}),await this.batchSubscribe(r)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(hr.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async r=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()}),this.events.on(lt.deleted,async r=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:r}),await this.persist()})}),this.relayer=e,this.logger=dt(i,this.name),this.clientId=""}get context(){return st(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,i){let r=!1;try{r=this.getSubscription(e).topic===i}catch{}return r}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,i){const r=this.topicMap.get(e);await Promise.all(r.map(async n=>await this.unsubscribeById(e,n,i)))}async unsubscribeById(e,i,r){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}});try{const n=Fs(r);await this.restartToComplete({topic:e,id:i,relay:n}),await this.rpcUnsubscribe(e,i,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,i,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:i,opts:r}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,i,r){var n,s;const o=await this.getSubscriptionId(e);if((n=r==null?void 0:r.internal)!=null&&n.skipSubscribe)return o;(!r||(r==null?void 0:r.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:i});const a={method:$r(i.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=r==null?void 0:r.internal)==null?void 0:s.throwOnFailedPublish;try{if((r==null?void 0:r.transportType)===he.link_mode)return setTimeout(()=>{(this.relayer.connected||this.relayer.connecting)&&this.relayer.request(a).catch(h=>this.logger.warn(h))},L.toMiliseconds(L.ONE_SECOND)),o;const l=new Promise(async h=>{const f=d=>{d.topic===e&&(this.events.removeListener(lt.created,f),h(d.id))};this.events.on(lt.created,f);try{const d=await zt(new Promise((p,g)=>{this.relayer.request(a).catch(w=>{this.logger.warn(w,w==null?void 0:w.message),g(w)}).then(p)}),this.initialSubscribeTimeout,`Subscribing to ${e} failed, please try again`);this.events.removeListener(lt.created,f),h(d)}catch{}}),u=await zt(l,this.subscribeTimeout,`Subscribing to ${e} failed, please try again`);if(!u&&c)throw new Error(`Subscribing to ${e} failed, please try again`);return u?o:null}catch(l){if(this.logger.debug("Outgoing Relay Subscribe Payload stalled"),this.relayer.events.emit(me.connection_stalled),c)throw l}return null}async rpcBatchSubscribe(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});try{await await zt(new Promise(n=>{this.relayer.request(r).catch(s=>this.logger.warn(s)).then(n)}),this.subscribeTimeout,"rpcBatchSubscribe failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}}async rpcBatchFetchMessages(e){if(!e.length)return;const i=e[0].relay,r={method:$r(i.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:r});let n;try{n=await await zt(new Promise((s,o)=>{this.relayer.request(r).catch(a=>{this.logger.warn(a),o(a)}).then(s)}),this.subscribeTimeout,"rpcBatchFetchMessages failed, please try again")}catch{this.relayer.events.emit(me.connection_stalled)}return n}rpcUnsubscribe(e,i,r){const n={method:$r(r.protocol).unsubscribe,params:{topic:e,id:i}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,i){this.setSubscription(e,ia(rn({},i),{id:e})),this.pending.delete(i.topic)}onBatchSubscribe(e){e.length&&e.forEach(i=>{this.setSubscription(i.id,rn({},i)),this.pending.delete(i.topic)})}async onUnsubscribe(e,i,r){this.events.removeAllListeners(i),this.hasSubscription(i,e)&&this.deleteSubscription(i,r),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,i){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:i}),this.addSubscription(e,i)}addSubscription(e,i){this.subscriptions.set(e,rn({},i)),this.topicMap.set(i.topic,e),this.events.emit(lt.created,i)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const i=this.subscriptions.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}deleteSubscription(e,i){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:i});const r=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(r.topic,e),this.events.emit(lt.deleted,ia(rn({},r),{reason:i}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],i=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let r=0;r<i;r++){const n=e.splice(0,this.batchSubscribeTopicsLimit);await this.batchSubscribe(n)}}this.events.emit(lt.resubscribed)}async restore(){try{const e=await this.getRelayerSubscriptions();if(typeof e>"u"||!e.length)return;if(this.subscriptions.size&&!e.every(i=>{var r;return i.topic===((r=this.subscriptions.get(i.id))==null?void 0:r.topic)})){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async i=>ia(rn({},i),{id:await this.getSubscriptionId(i.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const i=await this.rpcBatchFetchMessages(e);i&&i.messages&&(await B3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(i.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async restartToComplete(e){!this.relayer.connected&&!this.relayer.connecting&&(this.cached.push(e),await this.relayer.transportOpen())}async getClientId(){return this.clientId||(this.clientId=await this.relayer.core.crypto.getClientId()),this.clientId}async getSubscriptionId(e){return bt(e+await this.getClientId())}}var TD=Object.defineProperty,qh=Object.getOwnPropertySymbols,RD=Object.prototype.hasOwnProperty,FD=Object.prototype.propertyIsEnumerable,ec=(t,e,i)=>e in t?TD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,zh=(t,e)=>{for(var i in e||(e={}))RD.call(e,i)&&ec(t,i,e[i]);if(qh)for(var i of qh(e))FD.call(e,i)&&ec(t,i,e[i]);return t},ne=(t,e,i)=>ec(t,typeof e!="symbol"?e+"":e,i);class ND extends xS{constructor(e){var i;super(e),ne(this,"protocol","wc"),ne(this,"version",2),ne(this,"core"),ne(this,"logger"),ne(this,"events",new St.EventEmitter),ne(this,"provider"),ne(this,"messages"),ne(this,"subscriber"),ne(this,"publisher"),ne(this,"name",h$),ne(this,"transportExplicitlyClosed",!1),ne(this,"initialized",!1),ne(this,"connectionAttemptInProgress",!1),ne(this,"relayUrl"),ne(this,"projectId"),ne(this,"packageName"),ne(this,"bundleId"),ne(this,"hasExperiencedNetworkDisruption",!1),ne(this,"pingTimeout"),ne(this,"heartBeatTimeout",L.toMiliseconds(L.THIRTY_SECONDS+L.FIVE_SECONDS)),ne(this,"reconnectTimeout"),ne(this,"connectPromise"),ne(this,"reconnectInProgress",!1),ne(this,"requestsInFlight",[]),ne(this,"connectTimeout",L.toMiliseconds(L.ONE_SECOND*15)),ne(this,"request",async r=>{var n,s;this.logger.debug("Publishing Request Payload");const o=r.id||Ri().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:r.method,topic:(n=r.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=r.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(r);return this.requestsInFlight=this.requestsInFlight.filter(l=>l!==a),c}catch(a){throw this.logger.debug(`Failed to Publish Request: ${o}`),a}}),ne(this,"resetPingTimeout",()=>{As()&&(clearTimeout(this.pingTimeout),this.pingTimeout=setTimeout(()=>{var r,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null?void 0:s.terminate)==null||o.call(s)}catch(a){this.logger.warn(a,a==null?void 0:a.message)}},this.heartBeatTimeout))}),ne(this,"onPayloadHandler",r=>{this.onProviderPayload(r),this.resetPingTimeout()}),ne(this,"onConnectHandler",()=>{this.logger.warn({},"Relayer connected 🛜"),this.startPingTimeout(),this.events.emit(me.connect)}),ne(this,"onDisconnectHandler",()=>{this.logger.warn({},"Relayer disconnected 🛑"),this.requestsInFlight=[],this.onProviderDisconnect()}),ne(this,"onProviderErrorHandler",r=>{this.logger.fatal(`Fatal socket error: ${r.message}`),this.events.emit(me.error,r),this.logger.fatal("Fatal socket error received, closing transport"),this.transportClose()}),ne(this,"registerProviderListeners",()=>{this.provider.on(gt.payload,this.onPayloadHandler),this.provider.on(gt.connect,this.onConnectHandler),this.provider.on(gt.disconnect,this.onDisconnectHandler),this.provider.on(gt.error,this.onProviderErrorHandler)}),this.core=e.core,this.logger=Kc({logger:(i=e.logger)!=null?i:u$,name:this.name}),this.messages=new wD(this.logger,e.core),this.subscriber=new BD(this,this.logger),this.publisher=new ID(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jg,y3()?this.packageName=Iu():w3()&&(this.bundleId=Iu()),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==null?void 0:e.message))}get context(){return st(this.logger)}get connected(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===1||!1}get connecting(){var e,i,r;return((r=(i=(e=this.provider)==null?void 0:e.connection)==null?void 0:i.socket)==null?void 0:r.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,i,r){this.isInitialized(),await this.publisher.publish(e,i,r),await this.recordMessageEvent({topic:e,message:i,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,i){var r,n,s;this.isInitialized(),(!(i!=null&&i.transportType)||(i==null?void 0:i.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((r=i==null?void 0:i.internal)==null?void 0:r.throwOnFailedPublish)>"u"?!0:(n=i==null?void 0:i.internal)==null?void 0:n.throwOnFailedPublish;let a=((s=this.subscriber.topicMap.get(e))==null?void 0:s[0])||"",c;const l=u=>{u.topic===e&&(this.subscriber.off(lt.created,l),c())};return await Promise.all([new Promise(u=>{c=u,this.subscriber.on(lt.created,l)}),new Promise(async(u,h)=>{a=await this.subscriber.subscribe(e,zh({internal:{throwOnFailedPublish:o}},i)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,i){this.isInitialized(),await this.subscriber.unsubscribe(e,i)}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await zt(this.provider.disconnect(),2e3,"provider.disconnect()").catch(()=>this.onProviderDisconnect()):this.onProviderDisconnect()}async transportClose(){this.transportExplicitlyClosed=!0,await this.transportDisconnect()}async transportOpen(e){if(!this.subscriber.hasAnyTopics){this.logger.info("Starting WS connection skipped because the client has no topics to work with.");return}if(this.connectPromise?(this.logger.debug({},"Waiting for existing connection attempt to resolve..."),await this.connectPromise,this.logger.debug({},"Existing connection attempt resolved")):(this.connectPromise=new Promise(async(i,r)=>{await this.connect(e).then(i).catch(r).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await gh())throw new Error("No internet connection detected. Please restart your network and try again.")}async handleBatchMessageEvents(e){if((e==null?void 0:e.length)===0){this.logger.trace("Batch message events is empty. Ignoring...");return}const i=e.sort((r,n)=>r.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${i.length} message events sorted`);for(const r of i)try{await this.onMessageEvent(r)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${i.length} message events processed`)}async onLinkMessageEvent(e,i){const{topic:r}=e;if(!i.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:r,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(r,s)}this.events.emit(me.message,e),await this.recordMessageEvent(e,ys.inbound)}async connect(e){await this.confirmOnlineStateOrThrow(),e&&e!==this.relayUrl&&(this.relayUrl=e,await this.transportDisconnect()),this.connectionAttemptInProgress=!0,this.transportExplicitlyClosed=!1;let i=1;for(;i<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${i}...`),await this.createProvider(),await new Promise(async(r,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await zt(new Promise((o,a)=>{this.provider.connect().then(o).catch(a)}),this.connectTimeout,`Socket stalled when trying to connect to ${this.relayUrl}`).catch(o=>{n(o)}).finally(()=>{this.provider.off(gt.disconnect,s),clearTimeout(this.reconnectTimeout)}),await new Promise(async(o,a)=>{const c=()=>{n(new Error("Connection interrupted while trying to subscribe"))};this.provider.once(gt.disconnect,c),await this.subscriber.start().then(o).catch(a).finally(()=>{this.provider.off(gt.disconnect,c)})}),this.hasExperiencedNetworkDisruption=!1,r()})}catch(r){await this.subscriber.stop();const n=r;this.logger.warn({},n.message),this.hasExperiencedNetworkDisruption=!0}finally{this.connectionAttemptInProgress=!1}if(this.connected){this.logger.debug({},`Connected to ${this.relayUrl} successfully on attempt: ${i}`);break}await new Promise(r=>setTimeout(r,L.toMiliseconds(i*1))),i++}}startPingTimeout(){var e,i,r,n,s;if(As())try{(i=(e=this.provider)==null?void 0:e.connection)!=null&&i.socket&&((s=(n=(r=this.provider)==null?void 0:r.connection)==null?void 0:n.socket)==null||s.on("ping",()=>{this.resetPingTimeout()})),this.resetPingTimeout()}catch(o){this.logger.warn(o,o==null?void 0:o.message)}}async createProvider(){this.provider.connection&&this.unregisterProviderListeners();const e=await this.core.crypto.signJWT(this.relayUrl);this.provider=new Yc(new QS(x3({sdkVersion:Ga,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,i){const{topic:r,message:n}=e;await this.messages.set(r,n,i)}async shouldIgnoreMessageEvent(e){const{topic:i,message:r}=e;if(!r||r.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${r}`),!0;if(!await this.subscriber.isKnownTopic(i))return this.logger.warn(`Ignoring message for unknown topic ${i}`),!0;const n=this.messages.has(i,r);return n&&this.logger.warn(`Ignoring duplicate message: ${r}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Gc(e)){if(!e.method.endsWith(f$))return;const i=e.params,{topic:r,message:n,publishedAt:s,attestation:o}=i.data,a={topic:r,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(zh({type:"event",event:i.id},a)),this.events.emit(i.id,a),await this.acknowledgePayload(e),await this.onMessageEvent(a)}else ao(e)&&this.events.emit(me.message_ack,e)}async onMessageEvent(e){await this.shouldIgnoreMessageEvent(e)||(await this.recordMessageEvent(e,ys.inbound),this.events.emit(me.message,e))}async acknowledgePayload(e){const i=Sn(e.id,!0);await this.provider.connection.send(i)}unregisterProviderListeners(){this.provider.off(gt.payload,this.onPayloadHandler),this.provider.off(gt.connect,this.onConnectHandler),this.provider.off(gt.disconnect,this.onDisconnectHandler),this.provider.off(gt.error,this.onProviderErrorHandler),clearTimeout(this.pingTimeout)}async registerEventListeners(){let e=await gh();b8(async i=>{e!==i&&(e=i,i?await this.transportOpen().catch(r=>this.logger.error(r,r==null?void 0:r.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(hr.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&x8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(i){this.logger.warn(i,i==null?void 0:i.message)}})}async onProviderDisconnect(){clearTimeout(this.pingTimeout),this.events.emit(me.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==null?void 0:e.message)),this.reconnectTimeout=void 0,this.reconnectInProgress=!1},L.toMiliseconds(d$)))))}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async toEstablishConnection(){if(await this.confirmOnlineStateOrThrow(),!this.connected){if(this.connectPromise){await this.connectPromise;return}await this.connect()}}}function UD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Vh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Hh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const kD="[object RegExp]",jD="[object String]",LD="[object Number]",MD="[object Boolean]",Kh="[object Arguments]",qD="[object Symbol]",zD="[object Date]",VD="[object Map]",HD="[object Set]",KD="[object Array]",WD="[object Function]",GD="[object ArrayBuffer]",ra="[object Object]",YD="[object Error]",ZD="[object DataView]",JD="[object Uint8Array]",XD="[object Uint8ClampedArray]",QD="[object Uint16Array]",eO="[object Uint32Array]",tO="[object BigUint64Array]",iO="[object Int8Array]",rO="[object Int16Array]",nO="[object Int32Array]",sO="[object BigInt64Array]",oO="[object Float32Array]",aO="[object Float64Array]";function cO(){}function Wh(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 lO(t,e,i){return un(t,e,void 0,void 0,void 0,void 0,i)}function un(t,e,i,r,n,s,o){const a=o(t,e,i,r,n,s);if(a!==void 0)return a;if(typeof t==typeof e)switch(typeof t){case"bigint":case"string":case"boolean":case"symbol":case"undefined":return t===e;case"number":return t===e||Object.is(t,e);case"function":return t===e;case"object":return yn(t,e,s,o)}return yn(t,e,s,o)}function yn(t,e,i,r){if(Object.is(t,e))return!0;let n=Hh(t),s=Hh(e);if(n===Kh&&(n=ra),s===Kh&&(s=ra),n!==s)return!1;switch(n){case jD:return t.toString()===e.toString();case LD:{const c=t.valueOf(),l=e.valueOf();return UD(c,l)}case MD:case zD:case qD:return Object.is(t.valueOf(),e.valueOf());case kD:return t.source===e.source&&t.flags===e.flags;case WD:return t===e}i=i??new Map;const o=i.get(t),a=i.get(e);if(o!=null&&a!=null)return o===e;i.set(t,e),i.set(e,t);try{switch(n){case VD:{if(t.size!==e.size)return!1;for(const[c,l]of t.entries())if(!e.has(c)||!un(l,e.get(c),c,t,e,i,r))return!1;return!0}case HD:{if(t.size!==e.size)return!1;const c=Array.from(t.values()),l=Array.from(e.values());for(let u=0;u<c.length;u++){const h=c[u],f=l.findIndex(d=>un(h,d,void 0,t,e,i,r));if(f===-1)return!1;l.splice(f,1)}return!0}case KD:case JD:case XD:case QD:case eO:case tO:case iO:case rO:case nO:case sO:case oO:case aO:{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(!un(t[c],e[c],c,t,e,i,r))return!1;return!0}case GD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case ZD:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),i,r);case YD:return t.name===e.name&&t.message===e.message;case ra:{if(!(yn(t.constructor,e.constructor,i,r)||Wh(t)&&Wh(e)))return!1;const c=[...Object.keys(t),...Vh(t)],l=[...Object.keys(e),...Vh(e)];if(c.length!==l.length)return!1;for(let u=0;u<c.length;u++){const h=c[u],f=t[h];if(!Object.hasOwn(e,h))return!1;const d=e[h];if(!un(f,d,h,t,e,i,r))return!1}return!0}default:return!1}}finally{i.delete(t),i.delete(e)}}function uO(t,e){return lO(t,e,cO)}var hO=Object.defineProperty,Gh=Object.getOwnPropertySymbols,fO=Object.prototype.hasOwnProperty,dO=Object.prototype.propertyIsEnumerable,tc=(t,e,i)=>e in t?hO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Yh=(t,e)=>{for(var i in e||(e={}))fO.call(e,i)&&tc(t,i,e[i]);if(Gh)for(var i of Gh(e))dO.call(e,i)&&tc(t,i,e[i]);return t},Ze=(t,e,i)=>tc(t,typeof e!="symbol"?e+"":e,i);class dr extends IS{constructor(e,i,r,n=Kt,s=void 0){super(e,i,r,n),this.core=e,this.logger=i,this.name=r,Ze(this,"map",new Map),Ze(this,"version",p$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Kt),Ze(this,"recentlyDeleted",[]),Ze(this,"recentlyDeletedLimit",200),Ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(o=>{this.getKey&&o!==null&&!Ie(o)?this.map.set(this.getKey(o),o):Z_(o)?this.map.set(o.id,o):J_(o)&&this.map.set(o.topic,o)}),this.cached=[],this.initialized=!0)}),Ze(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())}),Ze(this,"get",o=>(this.isInitialized(),this.logger.debug("Getting value"),this.logger.trace({type:"method",method:"get",key:o}),this.getData(o))),Ze(this,"getAll",o=>(this.isInitialized(),o?this.values.filter(a=>Object.keys(o).every(c=>uO(a[c],o[c]))):this.values)),Ze(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=Yh(Yh({},this.getData(o)),a);this.map.set(o,c),await this.persist()}),Ze(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=dt(i,this.name),this.storagePrefix=n,this.getKey=s}get context(){return st(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 i=this.map.get(e);if(!i){if(this.recentlyDeleted.includes(e)){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${this.name}: ${e}`);throw this.logger.error(n),new Error(n)}const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(r),new Error(r)}return i}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:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var pO=Object.defineProperty,gO=(t,e,i)=>e in t?pO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ee=(t,e,i)=>gO(t,typeof e!="symbol"?e+"":e,i);class yO{constructor(e,i){this.core=e,this.logger=i,ee(this,"name",m$),ee(this,"version",b$),ee(this,"events",new lc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Kt),ee(this,"ignoredPayloadTypes",[li]),ee(this,"registeredMethods",[]),ee(this,"init",async()=>{this.initialized||(await this.pairings.init(),await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.initialized=!0,this.logger.trace("Initialized"))}),ee(this,"register",({methods:r})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...r])]}),ee(this,"create",async r=>{this.isInitialized();const n=Ha(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:kg},c={topic:s,expiry:o,relay:a,active:!1,methods:r==null?void 0:r.methods},l=oh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:r==null?void 0:r.methods});return this.events.emit(Yi.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:r==null?void 0:r.transportType,internal:r==null?void 0:r.internal}),{topic:s,uri:l}}),ee(this,"pair",async r=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:r==null?void 0:r.uri,trace:[jt.pairing_started]}});this.isValidPair(r,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=sh(r.uri);n.props.properties.topic=s,n.addTrace(jt.pairing_uri_validation_success),n.addTrace(jt.pairing_uri_not_expired);let u;if(this.pairings.keys.includes(s)){if(u=this.pairings.get(s),n.addTrace(jt.existing_pairing),u.active)throw n.setError(ii.active_pairing_already_exists),new Error(`Pairing already exists: ${s}. Please try again with a new connection URI.`);n.addTrace(jt.pairing_not_expired)}const h=c||we(L.FIVE_MINUTES),f={topic:s,relay:a,expiry:h,active:!1,methods:l};this.core.expirer.set(s,h),await this.pairings.set(s,f),n.addTrace(jt.store_new_pairing),r.activatePairing&&await this.activate({topic:s}),this.events.emit(Yi.create,f),n.addTrace(jt.emit_inactive_pairing),this.core.crypto.keychain.has(s)||await this.core.crypto.setSymKey(o,s),n.addTrace(jt.subscribing_pairing_topic);try{await this.core.relayer.confirmOnlineStateOrThrow()}catch{n.setError(ii.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ii.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:r})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(r,n),await this.pairings.update(r,{active:!0,expiry:n})}),ee(this,"ping",async r=>{this.isInitialized(),await this.isValidPing(r),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=r;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Ki();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:r,expiry:n})=>{this.isInitialized(),await this.pairings.update(r,{expiry:n})}),ee(this,"updateMetadata",async({topic:r,metadata:n})=>{this.isInitialized(),await this.pairings.update(r,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async r=>{this.isInitialized(),await this.isValidDisconnect(r);const{topic:n}=r;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",r=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=r,c=this.core.crypto.keychain.get(n);return oh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(r,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(r,o),c=en[n].req;return this.core.history.set(r,o),this.core.relayer.publish(r,a,c),o.id}),ee(this,"sendResult",async(r,n,s)=>{const o=Sn(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(r,n,s)=>{const o=oo(r,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,r)).request.method,l=en[c]?en[c].res:en.unregistered_method.res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"deletePairing",async(r,n)=>{await this.core.relayer.unsubscribe(r),await Promise.all([this.pairings.delete(r,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(r),n?Promise.resolve():this.core.expirer.del(r)])}),ee(this,"cleanup",async()=>{const r=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(r.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async r=>{const{topic:n,payload:s}=r;switch(s.method){case"wc_pairingPing":return await this.onPairingPingRequest(n,s);case"wc_pairingDelete":return await this.onPairingDeleteRequest(n,s);default:return await this.onUnknownRpcMethodRequest(n,s)}}),ee(this,"onRelayEventResponse",async r=>{const{topic:n,payload:s}=r,o=(await this.core.history.get(n,s.id)).request.method;switch(o){case"wc_pairingPing":return this.onPairingPingResponse(n,s);default:return this.onUnknownRpcMethodResponse(o)}}),ee(this,"onPairingPingRequest",async(r,n)=>{const{id:s}=n;try{this.isValidPing({topic:r}),await this.sendResult(s,r,!0),this.events.emit(Yi.ping,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(r,n)=>{const{id:s}=n;setTimeout(()=>{Mt(n)?this.events.emit(ae("pairing_ping",s),{}):vt(n)&&this.events.emit(ae("pairing_ping",s),{error:n.error})},500)}),ee(this,"onPairingDeleteRequest",async(r,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:r}),await this.deletePairing(r),this.events.emit(Yi.delete,{id:s,topic:r})}catch(o){await this.sendError(s,r,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(r,n)=>{const{id:s,method:o}=n;try{if(this.registeredMethods.includes(o))return;const a=fe("WC_METHOD_UNSUPPORTED",o);await this.sendError(s,r,a),this.logger.error(a)}catch(a){await this.sendError(s,r,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",r=>{this.registeredMethods.includes(r)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",r))}),ee(this,"isValidPair",(r,n)=>{var s;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${r}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!Y_(r.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${r.uri}`);throw n.setError(ii.malformed_pairing_uri),new Error(a)}const o=sh(r==null?void 0:r.uri);if(!((s=o==null?void 0:o.relay)!=null&&s.protocol)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#relay-protocol");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ii.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ii.pairing_expired);const{message:a}=M("EXPIRED","pair() URI has expired. Please try again with a new connection URI.");throw new Error(a)}}),ee(this,"isValidPing",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(s)}const{topic:n}=r;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async r=>{if(!be(r,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${r}`);throw new Error(n)}if(!this.pairings.keys.includes(r)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${r}`);throw new Error(n)}if(qt(this.pairings.get(r).expiry)){await this.deletePairing(r);const{message:n}=M("EXPIRED",`pairing topic: ${r}`);throw new Error(n)}}),this.core=e,this.logger=dt(i,this.name),this.pairings=new dr(this.core,this.logger,this.name,this.storagePrefix)}get context(){return st(this.logger)}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}registerRelayerEvents(){this.core.relayer.on(me.message,async e=>{const{topic:i,message:r,transportType:n}=e;if(this.pairings.keys.includes(i)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(r)))try{const s=await this.core.crypto.decode(i,r);Gc(s)?(this.core.history.set(i,s),await this.onRelayEventRequest({topic:i,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:i,payload:s}),this.core.history.delete(i,s.id)),await this.core.relayer.messages.ack(i,r)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:i}=$p(e.target);i&&this.pairings.keys.includes(i)&&(await this.deletePairing(i,!0),this.events.emit(Yi.expire,{topic:i}))})}}var wO=Object.defineProperty,mO=(t,e,i)=>e in t?wO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Be=(t,e,i)=>mO(t,typeof e!="symbol"?e+"":e,i);class bO extends bS{constructor(e,i){super(e,i),this.core=e,this.logger=i,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",v$),Be(this,"version",E$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Kt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.records.set(r.id,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(r,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:r,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:r,request:{method:n.method,params:n.params||null},chainId:s,expiry:we(L.THIRTY_DAYS)};this.records.set(o.id,o),this.persist(),this.events.emit(Dt.created,o)}),Be(this,"resolve",async r=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:r}),!this.records.has(r.id))return;const n=await this.getRecord(r.id);typeof n.response>"u"&&(n.response=vt(r)?{error:r.error}:{result:r.result},this.records.set(n.id,n),this.persist(),this.events.emit(Dt.updated,n))}),Be(this,"get",async(r,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:r,id:n}),await this.getRecord(n))),Be(this,"delete",(r,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===r){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Dt.deleted,s)}}),this.persist()}),Be(this,"exists",async(r,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===r:!1)),Be(this,"on",(r,n)=>{this.events.on(r,n)}),Be(this,"once",(r,n)=>{this.events.once(r,n)}),Be(this,"off",(r,n)=>{this.events.off(r,n)}),Be(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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(i=>{if(typeof i.response<"u")return;const r={topic:i.topic,request:Ct(i.request.method,i.request.params,i.id),chainId:i.chainId};return e.push(r)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const i=this.records.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(r)}return i}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Dt.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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(Dt.created,e=>{const i=Dt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.updated,e=>{const i=Dt.updated;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.events.on(Dt.deleted,e=>{const i=Dt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,record:e})}),this.core.heartbeat.on(hr.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(i=>{L.toMiliseconds(i.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${i.id}`),this.records.delete(i.id),this.events.emit(Dt.deleted,i,!1),e=!0)}),e&&this.persist()}catch(e){this.logger.warn(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var vO=Object.defineProperty,EO=(t,e,i)=>e in t?vO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ze=(t,e,i)=>EO(t,typeof e!="symbol"?e+"":e,i);class xO extends SS{constructor(e,i){super(e,i),this.core=e,this.logger=i,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",x$),ze(this,"version",I$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Kt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(r=>this.expirations.set(r.target,r)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",r=>{try{const n=this.formatTarget(r);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(r,n)=>{this.isInitialized();const s=this.formatTarget(r),o={target:s,expiry:n};this.expirations.set(s,o),this.checkExpiry(s,o),this.events.emit(wt.created,{target:s,expiration:o})}),ze(this,"get",r=>{this.isInitialized();const n=this.formatTarget(r);return this.getExpiration(n)}),ze(this,"del",r=>{if(this.isInitialized(),this.has(r)){const n=this.formatTarget(r),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(r,n)=>{this.events.on(r,n)}),ze(this,"once",(r,n)=>{this.events.once(r,n)}),ze(this,"off",(r,n)=>{this.events.off(r,n)}),ze(this,"removeListener",(r,n)=>{this.events.removeListener(r,n)}),this.logger=dt(i,this.name)}get context(){return st(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 I3(e);if(typeof e=="number")return _3(e);const{message:i}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(i)}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(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:i}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(i),new Error(i)}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 i=this.expirations.get(e);if(!i){const{message:r}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(r),new Error(r)}return i}checkExpiry(e,i){const{expiry:r}=i;L.toMiliseconds(r)-Date.now()<=0&&this.expire(e,i)}expire(e,i){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:i})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,i)=>this.checkExpiry(i,e))}registerEventListeners(){this.core.heartbeat.on(hr.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const i=wt.created;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const i=wt.expired;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const i=wt.deleted;this.logger.info(`Emitting ${i}`),this.logger.debug({type:"event",event:i,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var IO=Object.defineProperty,_O=(t,e,i)=>e in t?IO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ye=(t,e,i)=>_O(t,typeof e!="symbol"?e+"":e,i);class SO extends $S{constructor(e,i,r){super(e,i,r),this.core=e,this.logger=i,this.store=r,ye(this,"name",_$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",$$),ye(this,"storagePrefix",Kt),ye(this,"version",Ug),ye(this,"publicKey"),ye(this,"fetchPromise"),ye(this,"init",async()=>{var n;this.isDevEnv||(this.publicKey=await this.store.getItem(this.storeKey),this.publicKey&&L.toMiliseconds((n=this.publicKey)==null?void 0:n.expiresAt)<Date.now()&&(this.logger.debug("verify v2 public key expired"),await this.removePublicKey()))}),ye(this,"register",async n=>{if(!Mr()||this.isDevEnv)return;const s=window.location.origin,{id:o,decryptedId:a}=n,c=`${this.verifyUrlV3}/attestation?projectId=${this.core.projectId}&origin=${s}&id=${o}&decryptedId=${a}`;try{const l=rr(),u=this.startAbortTimer(L.ONE_SECOND*5),h=await new Promise((f,d)=>{const p=()=>{window.removeEventListener("message",w),l.body.removeChild(g),d("attestation aborted")};this.abortController.signal.addEventListener("abort",p);const g=l.createElement("iframe");g.src=c,g.style.display="none",g.addEventListener("error",p,{signal:this.abortController.signal});const w=_=>{if(_.data&&typeof _.data=="string")try{const C=JSON.parse(_.data);if(C.type==="verify_attestation"){if(Aa(C.attestation).payload.id!==o)return;clearInterval(u),l.body.removeChild(g),this.abortController.signal.removeEventListener("abort",p),window.removeEventListener("message",w),f(C.attestation===null?"":C.attestation)}}catch(C){this.logger.warn(C)}};l.body.appendChild(g),window.addEventListener("message",w,{signal:this.abortController.signal})});return this.logger.debug(h,"jwt attestation"),h}catch(l){this.logger.warn(l)}return""}),ye(this,"resolve",async n=>{if(this.isDevEnv)return"";const{attestationId:s,hash:o,encryptedId:a}=n;if(s===""){this.logger.debug("resolve: attestationId is empty, skipping");return}if(s){if(Aa(s).payload.id!==a)return;const l=await this.isValidJwtAttestation(s);if(l){if(!l.isVerified){this.logger.warn("resolve: jwt attestation: origin url not verified");return}return l}}if(!o)return;const c=this.getVerifyUrl(n==null?void 0:n.verifyUrl);return this.fetchAttestation(o,c)}),ye(this,"fetchAttestation",async(n,s)=>{this.logger.debug(`resolving attestation: ${n} from url: ${s}`);const o=this.startAbortTimer(L.ONE_SECOND*5),a=await fetch(`${s}/attestation/${n}?v2Supported=true`,{signal:this.abortController.signal});return clearTimeout(o),a.status===200?await a.json():void 0}),ye(this,"getVerifyUrl",n=>{let s=n||gn;return D$.includes(s)||(this.logger.info(`verify url: ${s}, not included in trusted list, assigning default: ${gn}`),s=gn),s}),ye(this,"fetchPublicKey",async()=>{try{this.logger.debug(`fetching public key from: ${this.verifyUrlV3}`);const n=this.startAbortTimer(L.FIVE_SECONDS),s=await fetch(`${this.verifyUrlV3}/public-key`,{signal:this.abortController.signal});return clearTimeout(n),await s.json()}catch(n){this.logger.warn(n)}}),ye(this,"persistPublicKey",async n=>{this.logger.debug(n,"persisting public key to local storage"),await this.store.setItem(this.storeKey,n),this.publicKey=n}),ye(this,"removePublicKey",async()=>{this.logger.debug("removing verify v2 public key from storage"),await this.store.removeItem(this.storeKey),this.publicKey=void 0}),ye(this,"isValidJwtAttestation",async n=>{const s=await this.getPublicKey();try{if(s)return this.validateAttestation(n,s)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}const o=await this.fetchAndPersistPublicKey();try{if(o)return this.validateAttestation(n,o)}catch(a){this.logger.error(a),this.logger.warn("error validating attestation")}}),ye(this,"getPublicKey",async()=>this.publicKey?this.publicKey:await this.fetchAndPersistPublicKey()),ye(this,"fetchAndPersistPublicKey",async()=>{if(this.fetchPromise)return await this.fetchPromise,this.publicKey;this.fetchPromise=new Promise(async s=>{const o=await this.fetchPublicKey();o&&(await this.persistPublicKey(o),s(o))});const n=await this.fetchPromise;return this.fetchPromise=void 0,n}),ye(this,"validateAttestation",(n,s)=>{const o=E_(n,s.publicKey),a={hasExpired:L.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=dt(i,this.name),this.abortController=new AbortController,this.isDevEnv=Fc(),this.init()}get storeKey(){return this.storagePrefix+this.version+this.core.customStoragePrefix+"//verify:public:key"}get context(){return st(this.logger)}startAbortTimer(e){return this.abortController=new AbortController,setTimeout(()=>this.abortController.abort(),L.toMiliseconds(e))}}var $O=Object.defineProperty,DO=(t,e,i)=>e in t?$O(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Zh=(t,e,i)=>DO(t,typeof e!="symbol"?e+"":e,i);class OO extends DS{constructor(e,i){super(e,i),this.projectId=e,this.logger=i,Zh(this,"context",O$),Zh(this,"registerDeviceToken",async r=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=r,c=`${A$}/${this.projectId}/clients`;await fetch(c,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:n,type:o,token:s,always_raw:a})})}),this.logger=dt(i,this.context)}}var AO=Object.defineProperty,Jh=Object.getOwnPropertySymbols,PO=Object.prototype.hasOwnProperty,CO=Object.prototype.propertyIsEnumerable,ic=(t,e,i)=>e in t?AO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,nn=(t,e)=>{for(var i in e||(e={}))PO.call(e,i)&&ic(t,i,e[i]);if(Jh)for(var i of Jh(e))CO.call(e,i)&&ic(t,i,e[i]);return t},$e=(t,e,i)=>ic(t,typeof e!="symbol"?e+"":e,i);class BO extends OS{constructor(e,i,r=!0){super(e,i,r),this.core=e,this.logger=i,$e(this,"context",C$),$e(this,"storagePrefix",Kt),$e(this,"storageVersion",P$),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!Fc())try{const n={eventId:Su(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:_p(this.core.relayer.protocol,this.core.relayer.version,Ga)}}};await this.sendEvent([n])}catch(n){this.logger.warn(n)}}),$e(this,"createEvent",n=>{const{event:s="ERROR",type:o="",properties:{topic:a,trace:c}}=n,l=Su(),u=this.core.projectId||"",h=Date.now(),f=nn({eventId:l,timestamp:h,props:{event:s,type:o,properties:{topic:a,trace:c}},bundleId:u,domain:this.getAppDomain()},this.setMethods(l));return this.telemetryEnabled&&(this.events.set(l,f),this.shouldPersist=!0),f}),$e(this,"getEvent",n=>{const{eventId:s,topic:o}=n;if(s)return this.events.get(s);const a=Array.from(this.events.values()).find(c=>c.props.properties.topic===o);if(a)return nn(nn({},a),this.setMethods(a.eventId))}),$e(this,"deleteEvent",n=>{const{eventId:s}=n;this.events.delete(s),this.shouldPersist=!0}),$e(this,"setEventListeners",()=>{this.core.heartbeat.on(hr.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>B$&&(this.events.delete(n.eventId),this.shouldPersist=!0)})})}),$e(this,"setMethods",n=>({addTrace:s=>this.addTrace(n,s),setError:s=>this.setError(n,s)})),$e(this,"addTrace",(n,s)=>{const o=this.events.get(n);o&&(o.props.properties.trace.push(s),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"setError",(n,s)=>{const o=this.events.get(n);o&&(o.props.type=s,o.timestamp=Date.now(),this.events.set(n,o),this.shouldPersist=!0)}),$e(this,"persist",async()=>{await this.core.storage.setItem(this.storageKey,Array.from(this.events.values())),this.shouldPersist=!1}),$e(this,"restore",async()=>{try{const n=await this.core.storage.getItem(this.storageKey)||[];if(!n.length)return;n.forEach(s=>{this.events.set(s.eventId,nn(nn({},s),this.setMethods(s.eventId)))})}catch(n){this.logger.warn(n)}}),$e(this,"submit",async()=>{if(!this.telemetryEnabled||this.events.size===0)return;const n=[];for(const[s,o]of this.events)o.props.type&&n.push(o);if(n.length!==0)try{if((await this.sendEvent(n)).ok)for(const s of n)this.events.delete(s.eventId),this.shouldPersist=!0}catch(s){this.logger.warn(s)}}),$e(this,"sendEvent",async n=>{const s=this.getAppDomain()?"":"&sp=desktop";return await fetch(`${T$}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Ga}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ip().url),this.logger=dt(i,this.context),this.telemetryEnabled=r,r?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var TO=Object.defineProperty,Xh=Object.getOwnPropertySymbols,RO=Object.prototype.hasOwnProperty,FO=Object.prototype.propertyIsEnumerable,rc=(t,e,i)=>e in t?TO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Qh=(t,e)=>{for(var i in e||(e={}))RO.call(e,i)&&rc(t,i,e[i]);if(Xh)for(var i of Xh(e))FO.call(e,i)&&rc(t,i,e[i]);return t},le=(t,e,i)=>rc(t,typeof e!="symbol"?e+"":e,i);let NO=class Xg extends gS{constructor(e){var i;super(e),le(this,"protocol",Ng),le(this,"version",Ug),le(this,"name",Us),le(this,"relayUrl"),le(this,"projectId"),le(this,"customStoragePrefix"),le(this,"events",new St.EventEmitter),le(this,"logger"),le(this,"heartbeat"),le(this,"relayer"),le(this,"crypto"),le(this,"storage"),le(this,"history"),le(this,"expirer"),le(this,"pairing"),le(this,"verify"),le(this,"echoClient"),le(this,"linkModeSupportedApps"),le(this,"eventClient"),le(this,"initialized",!1),le(this,"logChunkController"),le(this,"on",(a,c)=>this.events.on(a,c)),le(this,"once",(a,c)=>this.events.once(a,c)),le(this,"off",(a,c)=>this.events.off(a,c)),le(this,"removeListener",(a,c)=>this.events.removeListener(a,c)),le(this,"dispatchEnvelope",({topic:a,message:c,sessionExists:l})=>{if(!a||!c)return;const u={topic:a,message:c,publishedAt:Date.now(),transportType:he.link_mode};this.relayer.onLinkMessageEvent(u,{sessionExists:l})});const r=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(r)try{return this.customStoragePrefix=r.customStoragePrefix,this.logger=r.logger,this.heartbeat=r.heartbeat,this.crypto=r.crypto,this.history=r.history,this.expirer=r.expirer,this.storage=r.storage,this.relayer=r.relayer,this.pairing=r.pairing,this.verify=r.verify,this.echoClient=r.echoClient,this.linkModeSupportedApps=r.linkModeSupportedApps,this.eventClient=r.eventClient,this.initialized=r.initialized,this.logChunkController=r.logChunkController,r}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||jg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=i3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:e$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Ep({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(i=this.logChunkController)!=null&&i.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=dt(s,this.name),this.heartbeat=new B8,this.crypto=new lD(this,this.logger,e==null?void 0:e.keychain),this.history=new bO(this,this.logger),this.expirer=new xO(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new fS(Qh(Qh({},t$),e==null?void 0:e.storageOptions)),this.relayer=new ND({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new yO(this,this.logger),this.verify=new SO(this,this.logger,this.storage),this.echoClient=new OO(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new BO(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const i=new Xg(e);await i.initialize();const r=await i.crypto.getClientId();return await i.storage.setItem(g$,r),i}get context(){return st(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(Ch,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(Ch)||[],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 i=`_walletConnectCore_${e}`,r=`${i}_count`;return globalThis[r]=(globalThis[r]||0)+1,globalThis[r]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[r]} times.`),globalThis[i]}catch(i){console.warn("Failed to get global WalletConnect core",i);return}}setGlobalCore(e){var i;try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${((i=e.opts)==null?void 0:i.customStoragePrefix)||""}`;globalThis[r]=e}catch(r){console.warn("Failed to set global WalletConnect core",r)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const UO=NO,Qg="wc",e0=2,t0="client",Zc=`${Qg}@${e0}:${t0}:`,na={name:t0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},ef="WALLETCONNECT_DEEPLINK_CHOICE",kO="proposal",tf="Proposal expired",jO="session",xr=L.SEVEN_DAYS,LO="engine",Te={wc_sessionPropose:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1100},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1101},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1120},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1121}},wc_sessionSettle:{req:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1102},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1103}},wc_sessionUpdate:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1104},res:{ttl:L.ONE_DAY,prompt:!1,tag:1105}},wc_sessionExtend:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1106},res:{ttl:L.ONE_DAY,prompt:!1,tag:1107}},wc_sessionRequest:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1108},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1109}},wc_sessionEvent:{req:{ttl:L.FIVE_MINUTES,prompt:!0,tag:1110},res:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1111}},wc_sessionDelete:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1112},res:{ttl:L.ONE_DAY,prompt:!1,tag:1113}},wc_sessionPing:{req:{ttl:L.ONE_DAY,prompt:!1,tag:1114},res:{ttl:L.ONE_DAY,prompt:!1,tag:1115}},wc_sessionAuthenticate:{req:{ttl:L.ONE_HOUR,prompt:!0,tag:1116},res:{ttl:L.ONE_HOUR,prompt:!1,tag:1117},reject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1118},autoReject:{ttl:L.FIVE_MINUTES,prompt:!1,tag:1119}}},sa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},MO={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:""}},qO="request",zO=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],VO="wc",HO="auth",KO="authKeys",WO="pairingTopics",GO="requests",lo=`${VO}@${1.5}:${HO}:`,ws=`${lo}:PUB_KEY`;var YO=Object.defineProperty,ZO=Object.defineProperties,JO=Object.getOwnPropertyDescriptors,rf=Object.getOwnPropertySymbols,XO=Object.prototype.hasOwnProperty,QO=Object.prototype.propertyIsEnumerable,nc=(t,e,i)=>e in t?YO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oe=(t,e)=>{for(var i in e||(e={}))XO.call(e,i)&&nc(t,i,e[i]);if(rf)for(var i of rf(e))QO.call(e,i)&&nc(t,i,e[i]);return t},Re=(t,e)=>ZO(t,JO(e)),k=(t,e,i)=>nc(t,typeof e!="symbol"?e+"":e,i);class eA extends BS{constructor(e){super(e),k(this,"name",LO),k(this,"events",new lc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new T3({limit:500})),k(this,"requestQueueDelay",L.ONE_SECOND),k(this,"expectedPairingMethodMap",new Map),k(this,"recentlyDeletedMap",new Map),k(this,"recentlyDeletedLimit",200),k(this,"relayMessageCache",[]),k(this,"pendingSessions",new Map),k(this,"init",async()=>{this.initialized||(await this.cleanup(),this.registerRelayerEvents(),this.registerExpirerEvents(),this.registerPairingEvents(),await this.registerLinkModeListeners(),this.client.core.pairing.register({methods:Object.keys(Te)}),this.initialized=!0,setTimeout(async()=>{await this.processPendingMessageEvents(),this.sessionRequestQueue.queue=this.getPendingSessionRequests(),this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay)))}),k(this,"connect",async i=>{var r;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},i),{requiredNamespaces:i.requiredNamespaces||{},optionalNamespaces:i.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=V_(n.requiredNamespaces,n.optionalNamespaces),n.requiredNamespaces={};const{pairingTopic:s,requiredNamespaces:o,optionalNamespaces:a,sessionProperties:c,scopedProperties:l,relays:u,authentication:h,walletPay:f}=n,d=((r=h==null?void 0:h[0])==null?void 0:r.ttl)||Te.wc_sessionPropose.req.ttl||L.FIVE_MINUTES;this.validateRequestExpiry(d);let p=s,g,w=!1;try{if(p){const A=this.client.core.pairing.pairings.get(p);this.client.logger.warn("connect() with existing pairing topic is deprecated and will be removed in the next major release."),w=A.active}}catch(A){throw this.client.logger.error(`connect() -> pairing.get(${p}) failed`),A}if(!p||!w){const{topic:A,uri:U}=await this.client.core.pairing.create({internal:{skipSubscribe:!0}});p=A,g=U}if(!p){const{message:A}=M("NO_MATCHING_KEY",`connect() pairing topic: ${p}`);throw new Error(A)}const _=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:kg}],proposer:{publicKey:_,metadata:this.client.metadata},expiryTimestamp:C,pairingTopic:p},c&&{sessionProperties:c}),l&&{scopedProperties:l}),{id:Lt()}),(h||f)&&{requests:{authentication:h==null?void 0:h.map(A=>{const{domain:U,chains:j,nonce:B,uri:I,exp:D,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:I,version:"1",iat:new Date().toISOString(),exp:D,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:O,resolve:P,done:T}=Ki(d,tf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:tf,code:0}}))};return this.client.events.on("proposal_expire",R),this.events.once(v,({error:A,session:U})=>{this.client.events.off("proposal_expire",R),A?O(A):U&&P(U)}),await this.setProposal(b.id,b),await this.sendProposeSession({proposal:b,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:{correlationId:b.id}}}).catch(A=>{throw this.deleteProposal(b.id),A}),{uri:g,approval:T}}),k(this,"pair",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(i)}catch(r){throw this.client.logger.error("pair() failed"),r}}),k(this,"approve",async i=>{var r,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(r=i==null?void 0:i.id)==null?void 0:r.toString(),trace:[Ot.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zi.no_internet_connection),U}try{await this.isValidProposalId(i==null?void 0:i.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${i==null?void 0:i.id}) failed`),o.setError(zi.proposal_not_found),U}try{await this.isValidApprove(i)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zi.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:_,optionalNamespaces:C}=p;let b=(n=this.client.core.eventClient)==null?void 0:n.getEvent({topic:g});b||(b=(s=this.client.core.eventClient)==null?void 0:s.createEvent({type:Ot.session_approve_started,properties:{topic:g,trace:[Ot.session_approve_started,Ot.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),O=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,O),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(xr)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Ot.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zi.subscribe_session_topic_failure),U}b.addTrace(Ot.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:_,optionalNamespaces:C,pairingTopic:g,acknowledged:!1,self:T.controller,peer:{publicKey:w.publicKey,metadata:w.metadata},controller:v,transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(P,A),b.addTrace(Ot.store_session);try{await this.sendApproveSession({sessionTopic:P,proposal:p,pairingProposalResponse:{relay:{protocol:c??"irn"},responderPublicKey:v},sessionSettleRequest:T,publishOpts:{internal:{throwOnFailedPublish:!0},tvf:oe({correlationId:a},this.getTVFApproveParams(A))}}),b.addTrace(Ot.session_approve_publish_success)}catch(U){throw this.client.logger.error(U),this.client.session.delete(P,fe("USER_DISCONNECTED")),await this.client.core.relayer.unsubscribe(P),U}return this.client.core.eventClient.deleteEvent({eventId:b.eventId}),await this.client.core.pairing.updateMetadata({topic:g,metadata:w.metadata}),await this.deleteProposal(a),await this.client.core.pairing.activate({topic:g}),await this.setExpiry(P,we(xr)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(i)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:r,reason:n}=i;let s;try{s=this.client.proposal.get(r).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${r}) failed`),o}s&&await this.sendError({id:r,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(r)}),k(this,"update",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(i)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:r,namespaces:n}=i,{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Ri().toString(),u=this.client.session.get(r).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(r,{namespaces:n}),await this.sendRequest({topic:r,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(r,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(i)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:r}=i,n=Lt(),{done:s,resolve:o,reject:a}=Ki(L.FIVE_MINUTES,"Session extend request expired without receiving any acknowledgement");return this.events.once(ae("session_extend",n),({error:c})=>{c?a(c):o()}),await this.setExpiry(r,we(xr)),this.sendRequest({topic:r,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async i=>{this.isInitialized();try{await this.isValidRequest(i)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:r,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=i,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Ri().toString(),{done:u,resolve:h,reject:f}=Ki(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:_})=>{w?f(w):h(_)});const d="wc_sessionRequest",p=this.getAppLinkIfEnabled(a.peer.metadata,a.transportType);if(p)return await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:{request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:r};return await Promise.all([new Promise(async w=>{await this.sendRequest({clientRpcId:c,relayRpcId:l,topic:s,method:d,params:g,expiry:o,throwOnFailedPublish:!0,tvf:this.getTVFParams(c,g)}).catch(_=>f(_)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:r,id:c}),w()}),new Promise(async w=>{var _;if(!((_=a.sessionConfig)!=null&&_.disableDeepLink)){const C=await O3(this.client.core.storage,ef);await S3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async i=>{var r,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(i==null?void 0:i.topic)||((n=(r=i==null?void 0:i.response)==null?void 0:r.id)==null?void 0:n.toString()),trace:[Ot.session_request_response_started]}});try{await this.isValidRespond(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_validation_failure),h}s.addTrace(Ot.session_request_response_validation_success);const{topic:o,response:a}=i,{id:c}=a,l=this.client.session.get(o);l.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const u=this.getAppLinkIfEnabled(l.peer.metadata,l.transportType);try{s.addTrace(Ot.session_request_response_publish_started),Mt(a)?await this.sendResult({id:c,topic:o,result:a.result,throwOnFailedPublish:!0,appLink:u}):vt(a)&&await this.sendError({id:c,topic:o,error:a.error,appLink:u}),this.cleanupAfterResponse(i)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zi.session_request_response_publish_failure),h}}),k(this,"ping",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(i)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:r}=i;if(this.client.session.keys.includes(r)){const n=Lt(),s=Ri().toString(),{done:o,resolve:a,reject:c}=Ki(L.FIVE_MINUTES,"Ping request expired without receiving any acknowledgement");this.events.once(ae("session_ping",n),({error:l})=>{l?c(l):a()}),await Promise.all([this.sendRequest({topic:r,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(r)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:r}))}),k(this,"emit",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(i);const{topic:r,event:n,chainId:s}=i,o=Ri().toString(),a=Lt();await this.sendRequest({topic:r,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async i=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(i);const{topic:r}=i;if(this.client.session.keys.includes(r))await this.sendRequest({topic:r,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:r,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(r))await this.client.core.pairing.disconnect({topic:r});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${r}`);throw new Error(n)}}),k(this,"find",i=>(this.isInitialized(),this.client.session.getAll().filter(r=>W_(r,i)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(i,r)=>{var n;this.isInitialized(),this.isValidAuthenticate(i);const s=r&&this.client.core.linkModeSupportedApps.includes(r)&&((n=this.client.metadata.redirect)==null?void 0:n.linkMode),o=s?he.link_mode:he.relay;o===he.relay&&await this.confirmOnlineStateOrThrow();const{chains:a,statement:c="",uri:l,domain:u,nonce:h,type:f,exp:d,nbf:p,methods:g=[],expiry:w}=i,_=[...i.resources||[]],{topic:C,uri:b}=await this.client.core.pairing.create({methods:["wc_sessionAuthenticate"],transportType:o});this.client.logger.info({message:"Generated new pairing",pairing:{topic:C,uri:b}});const v=await this.client.core.crypto.generateKeyPair(),O=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:O,publicKey:v}),this.client.auth.pairingTopics.set(O,{topic:O,pairingTopic:C})]),await this.client.core.relayer.subscribe(O,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ci(a[0]);let S=Kx(E,"request",g);fs(_)&&(S=Gx(S,_.pop())),_.push(S)}const P=w&&w>Te.wc_sessionAuthenticate.req.ttl?w:Te.wc_sessionAuthenticate.req.ttl,T={authPayload:{type:f??"caip122",chains:a,statement:c,aud:l,domain:u,version:"1",nonce:h,iat:new Date().toISOString(),exp:d,nbf:p,resources:_},requester:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(P)},R={eip155:{chains:a,methods:[...new Set(["personal_sign",...g])],events:["chainChanged","accountsChanged"]}},A={requiredNamespaces:{},optionalNamespaces:R,relays:[{protocol:"irn"}],pairingTopic:C,proposer:{publicKey:v,metadata:this.client.metadata},expiryTimestamp:we(Te.wc_sessionPropose.req.ttl),id:Lt()},{done:U,resolve:j,reject:B}=Ki(P,"Request expired"),I=Lt(),D=ae("session_connect",A.id),m=ae("session_request",I),y=async({error:E,session:S})=>{this.events.off(m,x),E?B(E):S&&j({session:S})},x=async E=>{var S,F,N;if(await this.deletePendingAuthRequest(I,{message:"fulfilled",code:0}),E.error){const W=fe("WC_METHOD_UNSUPPORTED","wc_sessionAuthenticate");return E.error.code===W.code?void 0:(this.events.off(D,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(D,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Nu({cacao:W,projectId:this.client.core.projectId})||(this.client.logger.error(W,"Signature verification failed"),B(fe("SESSION_SETTLEMENT_FAILED","Signature verification failed")));const{p:Q}=W,pe=fs(Q.resources),ve=[Fa(Q.iss)],_e=Cs(Q.iss);if(pe){const He=Uu(pe),Wt=ku(pe);q.push(...He),ve.push(...Wt)}for(const He of ve)K.push(`${He}:${_e}`)}const G=await this.client.core.crypto.generateSharedKey(v,z.publicKey);let X;q.length>0&&(X={topic:G,acknowledged:!0,self:{publicKey:v,metadata:this.client.metadata},peer:z,controller:z.publicKey,expiry:we(xr),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:uh([...new Set(q)],[...new Set(K)]),transportType:o},await this.client.core.relayer.subscribe(G,{transportType:o}),await this.client.session.set(G,X),C&&await this.client.core.pairing.updateMetadata({topic:C,metadata:z.metadata}),X=this.client.session.get(G)),(S=this.client.metadata.redirect)!=null&&S.linkMode&&(F=z.metadata.redirect)!=null&&F.linkMode&&(N=z.metadata.redirect)!=null&&N.universal&&r&&(this.client.core.addLinkModeSupportedApp(z.metadata.redirect.universal),this.client.session.update(G,{transportType:he.link_mode})),j({auths:H,session:X})};this.events.once(D,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,I);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Bi});$=is(r,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:i.expiry,throwOnFailedPublish:!0,clientRpcId:I}),this.sendRequest({topic:C,method:"wc_sessionPropose",params:A,expiry:Te.wc_sessionPropose.req.ttl,throwOnFailedPublish:!0,clientRpcId:A.id})])}catch(E){throw this.events.off(D,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(I,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async i=>{const{id:r,auths:n}=i,s=this.client.core.eventClient.createEvent({properties:{topic:r.toString(),trace:[Vi.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(r);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${r}`);const a=o.transportType||he.relay;a===he.relay&&await this.confirmOnlineStateOrThrow();const c=o.requester.publicKey,l=await this.client.core.crypto.generateKeyPair(),u=ds(c),h={type:li,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Nu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const O=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:r,topic:u,error:O,encodeOpts:h}),new Error(O.message)}s.addTrace(Vi.cacaos_verified);const{p:_}=w,C=fs(_.resources),b=[Fa(_.iss)],v=Cs(_.iss);if(C){const O=Uu(C),P=ku(C);f.push(...O),b.push(...P)}for(const O of b)d.push(`${O}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vi.create_authenticated_session_topic);let g;if((f==null?void 0:f.length)>0){g={topic:p,acknowledged:!0,self:{publicKey:l,metadata:this.client.metadata},peer:{publicKey:c,metadata:o.requester.metadata},controller:c,expiry:we(xr),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:uh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vi.subscribing_authenticated_session_topic);try{await this.client.core.relayer.subscribe(p,{transportType:a})}catch(w){throw s.setError(tn.subscribe_authenticated_session_topic_failure),w}s.addTrace(Vi.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vi.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vi.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:r,result:{cacaos:n,responder:{publicKey:l,metadata:this.client.metadata}},encodeOpts:h,throwOnFailedPublish:!0,appLink:this.getAppLinkIfEnabled(o.requester.metadata,a)})}catch(w){throw s.setError(tn.authenticated_session_approve_publish_failure),w}return await this.client.auth.requests.delete(r,{message:"fulfilled",code:0}),await this.client.core.pairing.activate({topic:o.pairingTopic}),this.client.core.eventClient.deleteEvent({eventId:s.eventId}),{session:g}}),k(this,"rejectSessionAuthenticate",async i=>{this.isInitialized();const{id:r,reason:n}=i,s=this.getPendingAuthRequest(r);if(!s)throw new Error(`Could not find pending auth request with id ${r}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:li,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:r,topic:c,error:n,encodeOpts:l,rpcOpts:Te.wc_sessionAuthenticate.reject,appLink:this.getAppLinkIfEnabled(s.requester.metadata,s.transportType)}),await this.client.auth.requests.delete(r,{message:"rejected",code:0}),await this.deleteProposal(r)}),k(this,"formatAuthMessage",i=>{this.isInitialized();const{request:r,iss:n}=i;return zp(r,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const i=this.relayMessageCache.shift();i&&await this.onRelayMessage(i)}catch(i){this.client.logger.error(i)}},50)}),k(this,"cleanupDuplicatePairings",async i=>{if(i.pairingTopic)try{const r=this.client.core.pairing.pairings.get(i.pairingTopic),n=this.client.core.pairing.pairings.getAll().filter(s=>{var o,a;return((o=s.peerMetadata)==null?void 0:o.url)&&((a=s.peerMetadata)==null?void 0:a.url)===i.peer.metadata.url&&s.topic&&s.topic!==r.topic});if(n.length===0)return;this.client.logger.info(`Cleaning up ${n.length} duplicate pairing(s)`),await Promise.all(n.map(s=>this.client.core.pairing.disconnect({topic:s.topic}))),this.client.logger.info("Duplicate pairings clean up finished")}catch(r){this.client.logger.error(r)}}),k(this,"deleteSession",async i=>{var r;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=i,{self:c}=this.client.session.get(n);await this.client.core.relayer.unsubscribe(n),await this.client.session.delete(n,fe("USER_DISCONNECTED")),this.addToRecentlyDeleted(n,"session"),this.client.core.crypto.keychain.has(c.publicKey)&&await this.client.core.crypto.deleteKeyPair(c.publicKey),this.client.core.crypto.keychain.has(n)&&await this.client.core.crypto.deleteSymKey(n),s||this.client.core.expirer.del(n),this.client.core.storage.removeItem(ef).catch(l=>this.client.logger.warn(l)),n===((r=this.sessionRequestQueue.queue[0])==null?void 0:r.topic)&&(this.sessionRequestQueue.state=kt.idle),await Promise.all(this.getPendingSessionRequests().filter(l=>l.topic===n).map(l=>this.deletePendingSessionRequest(l.id,fe("USER_DISCONNECTED")))),o&&this.client.events.emit("session_delete",{id:a,topic:n})}),k(this,"deleteProposal",async(i,r)=>{if(r)try{const n=this.client.proposal.get(i),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zi.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(i,fe("USER_DISCONNECTED")),r?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"proposal")}),k(this,"deletePendingSessionRequest",async(i,r,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)]),this.addToRecentlyDeleted(i,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==i),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:i}))}),k(this,"deletePendingAuthRequest",async(i,r,n=!1)=>{await Promise.all([this.client.auth.requests.delete(i,r),n?Promise.resolve():this.client.core.expirer.del(i)])}),k(this,"setExpiry",async(i,r)=>{this.client.session.keys.includes(i)&&(this.client.core.expirer.set(i,r),await this.client.session.update(i,{expiry:r}))}),k(this,"setProposal",async(i,r)=>{this.client.core.expirer.set(i,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(i,r)}),k(this,"setAuthRequest",async(i,r)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=r;this.client.core.expirer.set(i,n.expiryTimestamp),await this.client.auth.requests.set(i,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:i,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async i=>{const{id:r,topic:n,params:s,verifyContext:o}=i,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(r,a),await this.client.pendingRequest.set(r,{id:r,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async i=>{const{topic:r,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=i,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Bi:tt;p=await this.client.core.crypto.encode(r,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${r} failed`),C}let w;if(zO.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const _=oe(oe({},Te[n].req),f);if(_.attestation=w,o&&(_.ttl=o),a&&(_.id=a),this.client.core.history.set(r,d),g){const C=is(u,r,p);await Y.Linking.openURL(C,this.client.name)}else _.tvf=Re(oe({},h),{correlationId:d.id}),l?(_.internal=Re(oe({},_.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(r,p,_)):this.client.core.relayer.publish(r,p,_).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async i=>{const{proposal:r,publishOpts:n}=i,s=Ct("wc_sessionPropose",r,r.id);this.client.core.history.set(r.pairingTopic,s);const o=await this.client.core.crypto.encode(r.pairingTopic,s,{encoding:tt}),a=bt(JSON.stringify(s)),c=bt(o),l=await this.client.core.verify.register({id:c,decryptedId:a});await this.client.core.relayer.publishCustom({payload:{pairingTopic:r.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async i=>{const{sessionTopic:r,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=i,c=Sn(s.id,n),l=await this.client.core.crypto.encode(s.pairingTopic,c,{encoding:tt}),u=Ct("wc_sessionSettle",o,a==null?void 0:a.id),h=await this.client.core.crypto.encode(r,u,{encoding:tt});this.client.core.history.set(r,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:r,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async i=>{const{id:r,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=i,l=Sn(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},a||{}),{encoding:p}))}catch(p){throw await this.cleanup(),this.client.logger.error(`sendResult() -> core.crypto.encode() for topic ${n} failed`),p}let f,d;try{f=await this.client.core.history.get(n,r);const p=f.request;try{d=this.getTVFParams(r,p.params,s)}catch(g){this.client.logger.warn(`sendResult() -> getTVFParams() failed: ${g==null?void 0:g.message}`)}}catch(p){throw this.client.logger.error(`sendResult() -> history.get(${n}, ${r}) failed`),p}if(h){const p=is(c,n,u);await Y.Linking.openURL(p,this.client.name)}else{const p=f.request.method,g=Te[p].res;g.tvf=Re(oe({},d),{correlationId:r}),o?(g.internal=Re(oe({},g.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(n,u,g)):this.client.core.relayer.publish(n,u,g).catch(w=>this.client.logger.error(w))}await this.client.core.history.resolve(l)}),k(this,"sendError",async i=>{const{id:r,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=i,l=oo(r,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Bi:tt;u=await this.client.core.crypto.encode(n,l,Re(oe({},o||{}),{encoding:d}))}catch(d){throw await this.cleanup(),this.client.logger.error(`sendError() -> core.crypto.encode() for topic ${n} failed`),d}let f;try{f=await this.client.core.history.get(n,r)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${r}) failed`),d}if(h){const d=is(c,n,u);await Y.Linking.openURL(d,this.client.name)}else{const d=f.request.method,p=a||Te[d].res;this.client.core.relayer.publish(n,u,p)}await this.client.core.history.resolve(l)}),k(this,"cleanup",async()=>{const i=[],r=[];this.client.session.getAll().forEach(n=>{let s=!1;qt(n.expiry)&&(s=!0),this.client.core.crypto.keychain.has(n.topic)||(s=!0),s&&i.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&r.push(n.id)}),await Promise.all([...i.map(n=>this.deleteSession({topic:n})),...r.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async i=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(i):await this.onRelayMessage(i)}),k(this,"onRelayEventRequest",async i=>{this.requestQueue.queue.push(i),await this.processRequestsQueue()}),k(this,"processRequestsQueue",async()=>{if(this.requestQueue.state===kt.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=kt.active;const i=this.requestQueue.queue.shift();if(i)try{await this.processRequest(i)}catch(r){this.client.logger.warn(r)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async i=>{const{topic:r,payload:n,attestation:s,transportType:o,encryptedId:a}=i,c=n.method;if(!this.shouldIgnorePairingRequest({topic:r,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:r,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(r,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(r,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(r,n);case"wc_sessionPing":return await this.onSessionPingRequest(r,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(r,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(r,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:r,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async i=>{const{topic:r,payload:n,transportType:s}=i,o=(await this.client.core.history.get(r,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(r,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(r,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(r,n);case"wc_sessionExtend":return this.onSessionExtendResponse(r,n);case"wc_sessionPing":return this.onSessionPingResponse(r,n);case"wc_sessionRequest":return this.onSessionRequestResponse(r,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(r,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",i=>{const{topic:r}=i,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${r} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",i=>{const{topic:r,requestMethod:n}=i,s=this.expectedPairingMethodMap.get(r);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async i=>{const{topic:r,payload:n,attestation:s,encryptedId:o}=i,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:r});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ii.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:r,expiryTimestamp:u,attestation:s,encryptedId:o},a);await this.setProposal(c,h);const f=await this.getVerifyContext({attestationId:s,hash:bt(JSON.stringify(n)),encryptedId:o,metadata:h.proposer.metadata});l==null||l.addTrace(jt.emit_session_proposal),this.client.events.emit("session_proposal",{id:c,params:h,verifyContext:f})}catch(l){await this.sendError({id:c,topic:r,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(i,r,n)=>{const{id:s}=r;if(Mt(r)){const{result:o}=r;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",result:o});const a=this.client.proposal.get(s);this.client.logger.trace({type:"method",method:"onSessionProposeResponse",proposal:a});const c=a.proposer.publicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",selfPublicKey:c});const l=o.responderPublicKey;this.client.logger.trace({type:"method",method:"onSessionProposeResponse",peerPublicKey:l});const u=await this.client.core.crypto.generateSharedKey(c,l);this.pendingSessions.set(s,{sessionTopic:u,pairingTopic:i,proposalId:s,publicKey:c});const h=await this.client.core.relayer.subscribe(u,{transportType:n});this.client.logger.trace({type:"method",method:"onSessionProposeResponse",subscriptionId:h}),await this.client.core.pairing.activate({topic:i})}else if(vt(r)){await this.deleteProposal(s);const o=ae("session_connect",s);if(this.events.listenerCount(o)===0)throw new Error(`emitting ${o} without any listeners, 954`);this.events.emit(o,{error:r.error})}}),k(this,"onSessionSettleRequest",async(i,r)=>{const{id:n,params:s}=r;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r.params,p=[...this.pendingSessions.values()].find(_=>_.sessionTopic===i);if(!p)return this.client.logger.error(`Pending session not found for topic ${i}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:i,relay:o,expiry:c,namespaces:l,acknowledged:!0,pairingTopic:p.pairingTopic,requiredNamespaces:g.requiredNamespaces,optionalNamespaces:g.optionalNamespaces,controller:a.publicKey,self:{publicKey:p.publicKey,metadata:this.client.metadata},peer:{publicKey:a.publicKey,metadata:a.metadata}},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{transportType:he.relay,authentication:d==null?void 0:d.authentication,walletPayResult:d==null?void 0:d.walletPay});await this.client.session.set(w.topic,w),await this.setExpiry(w.topic,w.expiry),await this.client.core.pairing.updateMetadata({topic:p.pairingTopic,metadata:w.peer.metadata}),this.pendingSessions.delete(p.proposalId),this.deleteProposal(p.proposalId,!1),this.cleanupDuplicatePairings(w),await this.sendResult({id:r.id,topic:i,throwOnFailedPublish:!0,result:!0}),this.client.events.emit("session_connect",{session:w}),this.events.emit(ae("session_connect",p.proposalId),{session:w})}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(i,r)=>{const{id:n}=r;Mt(r)?(await this.client.session.update(i,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(r)&&(await this.client.session.delete(i,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:r.error}))}),k(this,"onSessionUpdateRequest",async(i,r)=>{const{params:n,id:s}=r;try{const o=`${i}_session_update`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:i,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:i},n));try{Qr.set(o,s),await this.client.session.update(i,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:i,result:!0})}catch(c){throw Qr.delete(o),c}this.client.events.emit("session_update",{id:s,topic:i,params:n})}catch(o){await this.sendError({id:s,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(i,r)=>r.toString().slice(0,-3)<i.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(i,r)=>{const{id:n}=r,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_update",n),{}):vt(r)&&this.events.emit(ae("session_update",n),{error:r.error})}),k(this,"onSessionExtendRequest",async(i,r)=>{const{id:n}=r;try{this.isValidExtend({topic:i}),await this.setExpiry(i,we(xr)),await this.sendResult({id:n,topic:i,result:!0}),this.client.events.emit("session_extend",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(i,r)=>{const{id:n}=r,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_extend",n),{}):vt(r)&&this.events.emit(ae("session_extend",n),{error:r.error})}),k(this,"onSessionPingRequest",async(i,r)=>{const{id:n}=r;try{this.isValidPing({topic:i}),await this.sendResult({id:n,topic:i,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:i})}catch(s){await this.sendError({id:n,topic:i,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(i,r)=>{const{id:n}=r,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(r)?this.events.emit(ae("session_ping",n),{}):vt(r)&&this.events.emit(ae("session_ping",n),{error:r.error})},500)}),k(this,"onSessionDeleteRequest",async(i,r)=>{const{id:n}=r;try{await this.isValidDisconnect({topic:i,reason:r.params}),this.cleanupPendingSentRequestsForTopic({topic:i,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:i,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async i=>{var r,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=i,{id:h,params:f}=a;try{await this.isValidRequest(oe({topic:o},f));const d=this.client.session.get(o),p=await this.getVerifyContext({attestationId:c,hash:bt(JSON.stringify(Ct("wc_sessionRequest",f,h))),encryptedId:l,metadata:d.peer.metadata,transportType:u}),g={id:h,topic:o,params:f,verifyContext:p};await this.setPendingSessionRequest(g),u===he.link_mode&&(r=d.peer.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp((n=d.peer.metadata.redirect)==null?void 0:n.universal),(s=this.client.signConfig)!=null&&s.disableRequestQueue?this.emitSessionRequest(g):(this.addSessionRequestToSessionRequestQueue(g),this.processSessionRequestQueue())}catch(d){await this.sendError({id:h,topic:o,error:d}),this.client.logger.error(d)}}),k(this,"onSessionRequestResponse",(i,r)=>{const{id:n}=r,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionEventRequest",async(i,r)=>{const{id:n,params:s}=r;try{const o=`${i}_session_event_${s.event.name}`,a=Qr.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:i},s)),this.client.events.emit("session_event",{id:n,topic:i,params:s}),Qr.set(o,n)}catch(o){await this.sendError({id:n,topic:i,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(i,r)=>{const{id:n}=r;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:i,payload:r}),Mt(r)?this.events.emit(ae("session_request",n),{result:r.result}):vt(r)&&this.events.emit(ae("session_request",n),{error:r.error})}),k(this,"onSessionAuthenticateRequest",async i=>{var r;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=i;try{const{requester:l,authPayload:u,expiryTimestamp:h}=s.params,f=await this.getVerifyContext({attestationId:o,hash:bt(JSON.stringify(s)),encryptedId:a,metadata:l.metadata,transportType:c}),d={requester:l,pairingTopic:n,id:s.id,authPayload:u,verifyContext:f,expiryTimestamp:h};await this.setAuthRequest(s.id,{request:d,pairingTopic:n,transportType:c}),c===he.link_mode&&(r=l.metadata.redirect)!=null&&r.universal&&this.client.core.addLinkModeSupportedApp(l.metadata.redirect.universal),this.client.events.emit("session_authenticate",{topic:n,params:s.params,id:s.id,verifyContext:f})}catch(l){this.client.logger.error(l);const u=s.params.requester.publicKey,h=await this.client.core.crypto.generateKeyPair(),f=this.getAppLinkIfEnabled(s.params.requester.metadata,c),d={type:li,receiverPublicKey:u,senderPublicKey:h};await this.sendError({id:s.id,topic:n,error:l,encodeOpts:d,rpcOpts:Te.wc_sessionAuthenticate.autoReject,appLink:f})}}),k(this,"addSessionRequestToSessionRequestQueue",i=>{this.sessionRequestQueue.queue.push(i)}),k(this,"cleanupAfterResponse",i=>{this.deletePendingSessionRequest(i.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:i,error:r})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===i&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:r})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const i=this.sessionRequestQueue.queue[0];if(!i){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(i)}catch(r){this.client.logger.error(r)}}),k(this,"emitSessionRequest",i=>{if(this.emittedSessionRequests.has(i.id)){this.client.logger.warn({id:i.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${i.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(i.id),this.client.events.emit("session_request",i)}),k(this,"onPairingCreated",i=>{if(i.methods&&this.expectedPairingMethodMap.set(i.topic,i.methods),i.active)return;const r=this.client.proposal.getAll().find(n=>n.pairingTopic===i.topic);r&&this.onSessionProposeRequest({topic:i.topic,payload:Ct("wc_sessionPropose",Re(oe({},r),{requiredNamespaces:r.requiredNamespaces,optionalNamespaces:r.optionalNamespaces,relays:r.relays,proposer:r.proposer,sessionProperties:r.sessionProperties,scopedProperties:r.scopedProperties}),r.id),attestation:r.attestation,encryptedId:r.encryptedId})}),k(this,"isValidConnect",async i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(i)}`);throw new Error(l)}const{pairingTopic:r,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=i;if(Ie(r)||await this.isValidPairingTopic(r),!s8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!Ie(n)&&Ht(n)!==0){const l="requiredNamespaces are deprecated and are automatically assigned to optionalNamespaces";["fatal","error","silent"].includes(this.client.logger.level)?console.warn(l):this.client.logger.warn(l),this.validateNamespaces(n,"requiredNamespaces")}if(s&&!Ie(s)&&Ht(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const l=Object.keys(n||{}).concat(Object.keys(s||{}));if(!Object.keys(a).every(u=>l.includes(u.split(":")[0])))throw new Error(`Scoped properties must be a subset of required/optional namespaces, received: ${JSON.stringify(a)}, required/optional namespaces: ${JSON.stringify(l)}`)}}),k(this,"validateNamespaces",(i,r)=>{const n=n8(i,"connect()",r);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async i=>{if(!Xe(i))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${i}`).message);const{id:r,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=i;this.checkRecentlyDeleted(r),await this.isValidProposalId(r);const c=this.client.proposal.get(r),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=dh(c.requiredNamespaces,n,"approve()");if(u)throw new Error(u.message);if(!be(s,!0)){const{message:h}=M("MISSING_OR_INVALID",`approve() relayProtocol: ${s}`);throw new Error(h)}if(o&&!Ie(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!Ie(a)){this.validateSessionProps(a,"scopedProperties");const h=new Set(Object.keys(n));if(!Object.keys(a).every(f=>h.has(f.split(":")[0])))throw new Error(`Scoped properties must be a subset of approved namespaces, received: ${JSON.stringify(a)}, approved namespaces: ${Array.from(h).join(", ")}`)}}),k(this,"isValidReject",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${i}`);throw new Error(s)}const{id:r,reason:n}=i;if(this.checkRecentlyDeleted(r),await this.isValidProposalId(r),!a8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",i=>{if(!Xe(i)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${i}`);throw new Error(l)}const{relay:r,controller:n,namespaces:s,expiry:o}=i;if(!Dg(r)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=X_(n,"onSessionSettleRequest()");if(a)throw new Error(a.message);const c=Jo(s,"onSessionSettleRequest()");if(c)throw new Error(c.message);if(qt(o)){const{message:l}=M("EXPIRED","onSessionSettleRequest()");throw new Error(l)}}),k(this,"isValidUpdate",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${i}`);throw new Error(c)}const{topic:r,namespaces:n}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const s=this.client.session.get(r),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=dh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${i}`);throw new Error(n)}const{topic:r}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r)}),k(this,"isValidRequest",async i=>{if(!Xe(i)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${i}`);throw new Error(c)}const{topic:r,request:n,chainId:s,expiry:o}=i;this.checkRecentlyDeleted(r),await this.isValidSessionTopic(r);const{namespaces:a}=this.client.session.get(r);if(!fh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!c8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!h8(a,s,n.method)){const{message:c}=M("MISSING_OR_INVALID",`request() method: ${n.method}`);throw new Error(c)}this.validateRequestExpiry(o)}),k(this,"isValidRespond",async i=>{var r;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${i}`);throw new Error(a)}const{topic:n,response:s}=i;try{await this.isValidSessionTopic(n)}catch(a){throw(r=i==null?void 0:i.response)!=null&&r.id&&this.cleanupAfterResponse(i),a}if(!l8(s)){const{message:a}=M("MISSING_OR_INVALID",`respond() response: ${JSON.stringify(s)}`);throw new Error(a)}const o=this.client.pendingRequest.get(s.id);if(o.topic!==n){const{message:a}=M("MISMATCHED_TOPIC",`Request response topic mismatch. reqId: ${s.id}, expected topic: ${o.topic}, received topic: ${n}`);throw new Error(a)}}),k(this,"isValidPing",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidEmit",async i=>{if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${i}`);throw new Error(a)}const{topic:r,event:n,chainId:s}=i;await this.isValidSessionTopic(r);const{namespaces:o}=this.client.session.get(r);if(!fh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!u8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!f8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(n)}const{topic:r}=i;await this.isValidSessionOrPairingTopic(r)}),k(this,"isValidAuthenticate",i=>{const{chains:r,uri:n,domain:s,nonce:o}=i;if(!Array.isArray(r)||r.length===0)throw new Error("chains is required and must be a non-empty array");if(!be(n,!1))throw new Error("uri is required parameter");if(!be(s,!1))throw new Error("domain is required parameter");if(!be(o,!1))throw new Error("nonce is required parameter");if([...new Set(r.map(c=>ci(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ci(r[0]);if(a!=="eip155")throw new Error("Only eip155 namespace is supported for authenticated sessions. Please use .connect() for non-eip155 chains.")}),k(this,"getVerifyContext",async i=>{const{attestationId:r,hash:n,encryptedId:s,metadata:o,transportType:a}=i,c={verified:{verifyUrl:o.verifyUrl||gn,validation:"UNKNOWN",origin:o.url||""}};try{if(a===he.link_mode){const u=this.getAppLinkIfEnabled(o,a);return c.verified.validation=u&&new URL(u).origin===new URL(o.url).origin?"VALID":"INVALID",c}const l=await this.client.core.verify.resolve({attestationId:r,hash:n,encryptedId:s,verifyUrl:o.verifyUrl});l&&(c.verified.origin=l.origin,c.verified.isScam=l.isScam,c.verified.validation=l.origin===new URL(o.url).origin?"VALID":"INVALID")}catch(l){this.client.logger.warn(l)}return this.client.logger.debug(`Verify context: ${JSON.stringify(c)}`),c}),k(this,"validateSessionProps",(i,r)=>{Object.values(i).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${r} must contain an existing value for each key. Received: ${n} for key ${Object.keys(i)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",i=>{const r=this.client.auth.requests.get(i);return typeof r=="object"?r:void 0}),k(this,"addToRecentlyDeleted",(i,r)=>{if(this.recentlyDeletedMap.set(i,r),this.recentlyDeletedMap.size>=this.recentlyDeletedLimit){let n=0;const s=this.recentlyDeletedLimit/2;for(const o of this.recentlyDeletedMap.keys()){if(n++>=s)break;this.recentlyDeletedMap.delete(o)}}}),k(this,"checkRecentlyDeleted",i=>{const r=this.recentlyDeletedMap.get(i);if(r){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${r}: ${i}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(i,r)=>{var n,s,o,a,c,l,u,h,f;return!i||r!==he.link_mode?!1:((s=(n=this.client.metadata)==null?void 0:n.redirect)==null?void 0:s.linkMode)===!0&&((a=(o=this.client.metadata)==null?void 0:o.redirect)==null?void 0:a.universal)!==void 0&&((l=(c=this.client.metadata)==null?void 0:c.redirect)==null?void 0:l.universal)!==""&&((u=i==null?void 0:i.redirect)==null?void 0:u.universal)!==void 0&&((h=i==null?void 0:i.redirect)==null?void 0:h.universal)!==""&&((f=i==null?void 0:i.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(i.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(i,r)=>{var n;return this.isLinkModeEnabled(i,r)?(n=i==null?void 0:i.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:i})=>{if(!i||!i.includes("wc_ev")||!i.includes("topic"))return;const r=_u(i,"topic")||"",n=decodeURIComponent(_u(i,"wc_ev")||""),s=this.client.session.keys.includes(r);s&&this.client.session.update(r,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:r,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var i;if(Fc()||ki()&&(i=this.client.metadata.redirect)!=null&&i.linkMode){const r=Y==null?void 0:Y.Linking;if(typeof r<"u"){r.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await r.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",i=>{try{const r=Sg(i.namespaces),n=j_(i.namespaces),s=L_(i.namespaces),o=i.sessionProperties,a=i.scopedProperties;return{approvedChains:r,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(r){return this.client.logger.warn(r,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(i,r,n)=>{var s,o,a;if(!((s=r.request)!=null&&s.method))return{};const c={correlationId:i,rpcMethods:[r.request.method],chainId:r.chainId};try{const l=this.extractTxHashesFromResult(r.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(r.request.params)?[(a=(o=r.request.params)==null?void 0:o[0])==null?void 0:a.to]:[]}catch(l){this.client.logger.warn(l,"Error getting TVF params")}return c}),k(this,"isValidContractData",i=>{var r;if(!i)return!1;try{const n=(i==null?void 0:i.data)||((r=i==null?void 0:i[0])==null?void 0:r.data);if(!n.startsWith("0x"))return!1;const s=n.slice(2);return/^[0-9a-fA-F]*$/.test(s)?s.length%2===0:!1}catch{}return!1}),k(this,"extractTxHashesFromResult",(i,r)=>{var n;try{if(!r)return[];const s=i.method,o=MO[s];if(s==="sui_signTransaction")return[Dx(r.transactionBytes)];if(s==="near_signTransaction")return[Bu(r)];if(s==="near_signTransactions")return r.map(c=>Bu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=r.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[P8({transaction:i.params.transactionPayload,signature:r.signature})];if(s==="algo_signTxn")return It(r)?r.map(c=>Tu(c)):[Tu(r)];if(s==="cosmos_signDirect")return[Ax(r)];if(s==="wallet_sendCalls")return Px(r);if(typeof r=="string")return[r];const a=r[o.key];if(It(a))return s==="solana_signAllTransactions"?a.map(c=>$x(c)):a;if(typeof a=="string")return[a]}catch(s){this.client.logger.warn(s,"Error extracting tx hashes from result")}return[]})}async processPendingMessageEvents(){try{const e=this.client.session.keys,i=this.client.core.relayer.messages.getWithoutAck(e);for(const[r,n]of Object.entries(i))for(const s of n)try{await this.onProviderMessageEvent({topic:r,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${r}, message: ${s}`)}}catch(e){this.client.logger.warn(e,"processPendingMessageEvents failed")}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}async confirmOnlineStateOrThrow(){await this.client.core.relayer.confirmOnlineStateOrThrow()}registerRelayerEvents(){this.client.core.relayer.on(me.message,e=>{this.onProviderMessageEvent(e)})}async onRelayMessage(e){const{topic:i,message:r,attestation:n,transportType:s}=e,{publicKey:o}=this.client.auth.authKeys.keys.includes(ws)?this.client.auth.authKeys.get(ws):{responseTopic:void 0,publicKey:void 0};try{const a=await this.client.core.crypto.decode(i,r,{receiverPublicKey:o,encoding:s===he.link_mode?Bi:tt});Gc(a)?(this.client.core.history.set(i,a),await this.onRelayEventRequest({topic:i,payload:a,attestation:n,transportType:s,encryptedId:bt(r)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:i,payload:a,transportType:s}),this.client.core.history.delete(i,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:i,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(i,r)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${r}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:i,id:r}=$p(e.target);if(r&&this.client.pendingRequest.keys.includes(r))return await this.deletePendingSessionRequest(r,M("EXPIRED"),!0);if(r&&this.client.auth.requests.keys.includes(r))return await this.deletePendingAuthRequest(r,M("EXPIRED"),!0);i?this.client.session.keys.includes(i)&&(await this.deleteSession({topic:i,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:i})):r&&(await this.deleteProposal(r,!0),this.client.events.emit("proposal_expire",{id:r}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yi.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yi.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(i)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:i}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(i)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:i}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(i)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:i}=M("EXPIRED",`session topic: ${e}`);throw new Error(i)}if(!this.client.core.crypto.keychain.has(e)){const{message:i}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(i)}}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(be(e,!1)){const{message:i}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(i)}else{const{message:i}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(i)}}async isValidProposalId(e){if(!o8(e)){const{message:i}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(i)}if(!this.client.proposal.keys.includes(e)){const{message:i}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(i)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:i}=M("EXPIRED",`proposal id: ${e}`);throw new Error(i)}}validateRequestExpiry(e){if(e&&!g8(e,sa)){const{message:i}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${sa.min} and ${sa.max}`);throw new Error(i)}}}class tA extends dr{constructor(e,i){super(e,i,kO,Zc),this.core=e,this.logger=i}}let iA=class extends dr{constructor(e,i){super(e,i,jO,Zc),this.core=e,this.logger=i}};class rA extends dr{constructor(e,i){super(e,i,qO,Zc,r=>r.id),this.core=e,this.logger=i}}class nA extends dr{constructor(e,i){super(e,i,KO,lo,()=>ws),this.core=e,this.logger=i}}class sA extends dr{constructor(e,i){super(e,i,WO,lo),this.core=e,this.logger=i}}class oA extends dr{constructor(e,i){super(e,i,GO,lo,r=>r.id),this.core=e,this.logger=i}}var aA=Object.defineProperty,cA=(t,e,i)=>e in t?aA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,oa=(t,e,i)=>cA(t,typeof e!="symbol"?e+"":e,i);class lA{constructor(e,i){this.core=e,this.logger=i,oa(this,"authKeys"),oa(this,"pairingTopics"),oa(this,"requests"),this.authKeys=new nA(this.core,this.logger),this.pairingTopics=new sA(this.core,this.logger),this.requests=new oA(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var uA=Object.defineProperty,hA=(t,e,i)=>e in t?uA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,te=(t,e,i)=>hA(t,typeof e!="symbol"?e+"":e,i);class Jc extends CS{constructor(e){super(e),te(this,"protocol",Qg),te(this,"version",e0),te(this,"name",na.name),te(this,"metadata"),te(this,"core"),te(this,"logger"),te(this,"events",new St.EventEmitter),te(this,"engine"),te(this,"session"),te(this,"proposal"),te(this,"pendingRequest"),te(this,"auth"),te(this,"signConfig"),te(this,"on",(r,n)=>this.events.on(r,n)),te(this,"once",(r,n)=>this.events.once(r,n)),te(this,"off",(r,n)=>this.events.off(r,n)),te(this,"removeListener",(r,n)=>this.events.removeListener(r,n)),te(this,"removeAllListeners",r=>this.events.removeAllListeners(r)),te(this,"connect",async r=>{try{return await this.engine.connect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async r=>{try{return await this.engine.pair(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async r=>{try{return await this.engine.approve(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async r=>{try{return await this.engine.reject(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async r=>{try{return await this.engine.update(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async r=>{try{return await this.engine.extend(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async r=>{try{return await this.engine.request(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async r=>{try{return await this.engine.respond(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async r=>{try{return await this.engine.ping(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async r=>{try{return await this.engine.emit(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async r=>{try{return await this.engine.disconnect(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",r=>{try{return this.engine.find(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(r){throw this.logger.error(r.message),r}}),te(this,"authenticate",async(r,n)=>{try{return await this.engine.authenticate(r,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",r=>{try{return this.engine.formatAuthMessage(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async r=>{try{return await this.engine.approveSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async r=>{try{return await this.engine.rejectSessionAuthenticate(r)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||na.name,this.metadata=b3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const i=Kc({logger:(e==null?void 0:e.logger)||na.logger,name:this.name});this.logger=i,this.core=(e==null?void 0:e.core)||new UO(e),this.session=new iA(this.core,this.logger),this.proposal=new tA(this.core,this.logger),this.pendingRequest=new rA(this.core,this.logger),this.engine=new eA(this),this.auth=new lA(this.core,this.logger)}static async init(e){const i=new Jc(e);return await i.initialize(),i}get context(){return st(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 fA=Jc;var dA=Object.defineProperty,pA=Object.defineProperties,gA=Object.getOwnPropertyDescriptors,nf=Object.getOwnPropertySymbols,yA=Object.prototype.hasOwnProperty,wA=Object.prototype.propertyIsEnumerable,sf=(t,e,i)=>e in t?dA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,of=(t,e)=>{for(var i in e||(e={}))yA.call(e,i)&&sf(t,i,e[i]);if(nf)for(var i of nf(e))wA.call(e,i)&&sf(t,i,e[i]);return t},af=(t,e)=>pA(t,gA(e));const mA={Accept:"application/json","Content-Type":"application/json"},bA="POST",cf={headers:mA,method:bA},lf=10;let i0=class{constructor(e,i=!1){if(this.url=e,this.disableProviderPing=i,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=i}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}off(e,i){this.events.off(e,i)}removeListener(e,i){this.events.removeListener(e,i)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const i=ui(e),r=await(await ll(this.url,af(of({},cf),{body:i}))).json();this.onPayload({data:r})}catch(i){this.onError(e.id,i)}}async register(e=this.url){if(!$h(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const i=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=i||this.events.listenerCount("open")>=i)&&this.events.setMaxListeners(i+1),new Promise((r,n)=>{this.events.once("register_error",s=>{this.resetMaxListeners(),n(s)}),this.events.once("open",()=>{if(this.resetMaxListeners(),typeof this.isAvailable>"u")return n(new Error("HTTP connection is missing or invalid"));r()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const i=ui({id:1,jsonrpc:"2.0",method:"test",params:[]});await ll(e,af(of({},cf),{body:i}))}this.onOpen()}catch(i){const r=this.parseError(i);throw this.events.emit("register_error",r),this.onClose(),r}}onOpen(){this.isAvailable=!0,this.registering=!1,this.events.emit("open")}onClose(){this.isAvailable=!1,this.registering=!1,this.events.emit("close")}onPayload(e){if(typeof e.data>"u")return;const i=typeof e.data=="string"?sr(e.data):e.data;this.events.emit("payload",i)}onError(e,i){const r=this.parseError(i),n=r.message||r.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,i=this.url){return Bg(e,i,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>lf&&this.events.setMaxListeners(lf)}};function Xc(t){return t==null||typeof t!="object"&&typeof t!="function"}function r0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function n0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const vA="[object RegExp]",s0="[object String]",o0="[object Number]",a0="[object Boolean]",c0="[object Arguments]",EA="[object Symbol]",xA="[object Date]",IA="[object Map]",_A="[object Set]",SA="[object Array]",$A="[object ArrayBuffer]",DA="[object Object]",OA="[object DataView]",AA="[object Uint8Array]",PA="[object Uint8ClampedArray]",CA="[object Uint16Array]",BA="[object Uint32Array]",TA="[object Int8Array]",RA="[object Int16Array]",FA="[object Int32Array]",NA="[object Float32Array]",UA="[object Float64Array]";function Qc(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function kA(t,e){return Or(t,void 0,t,new Map,e)}function Or(t,e,i,r=new Map,n=void 0){const s=n==null?void 0:n(t,e,i,r);if(s!=null)return s;if(Xc(t))return t;if(r.has(t))return r.get(t);if(Array.isArray(t)){const o=new Array(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return Object.hasOwn(t,"index")&&(o.index=t.index),Object.hasOwn(t,"input")&&(o.input=t.input),o}if(t instanceof Date)return new Date(t.getTime());if(t instanceof RegExp){const o=new RegExp(t.source,t.flags);return o.lastIndex=t.lastIndex,o}if(t instanceof Map){const o=new Map;r.set(t,o);for(const[a,c]of t)o.set(a,Or(c,a,i,r,n));return o}if(t instanceof Set){const o=new Set;r.set(t,o);for(const a of t)o.add(Or(a,void 0,i,r,n));return o}if(typeof ie<"u"&&ie.isBuffer(t))return t.subarray();if(Qc(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);r.set(t,o);for(let a=0;a<t.length;a++)o[a]=Or(t[a],a,i,r,n);return o}if(t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);if(t instanceof DataView){const o=new DataView(t.buffer.slice(0),t.byteOffset,t.byteLength);return r.set(t,o),Zi(o,t,i,r,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return r.set(t,o),Zi(o,t,i,r,n),o}if(t instanceof Error){const o=new t.constructor;return r.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zi(o,t,i,r,n),o}if(typeof t=="object"&&jA(t)){const o=Object.create(Object.getPrototypeOf(t));return r.set(t,o),Zi(o,t,i,r,n),o}return t}function Zi(t,e,i=t,r,n){const s=[...Object.keys(e),...r0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Or(e[a],a,i,r,n))}}function jA(t){switch(n0(t)){case c0:case SA:case $A:case OA:case a0:case xA:case NA:case UA:case TA:case RA:case FA:case IA:case o0:case DA:case vA:case _A:case s0:case EA:case AA:case PA:case CA:case BA:return!0;default:return!1}}function LA(t,e){return kA(t,(i,r,n,s)=>{const o=e==null?void 0:e(i,r,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case o0:case s0:case a0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zi(a,t),a}case c0:{const a={};return Zi(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function uf(t){return LA(t)}function hf(t){return t!==null&&typeof t=="object"&&n0(t)==="[object Arguments]"}function ff(t){return typeof t=="object"&&t!==null}function MA(){}function qA(t){return Qc(t)}function zA(t){var i;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const r=t[Symbol.toStringTag];return r==null||!((i=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&i.writable)?!1:t.toString()===`[object ${r}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function VA(t){if(Xc(t))return t;if(Array.isArray(t)||Qc(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),i=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new i(t);if(t instanceof RegExp){const r=new i(t);return r.lastIndex=t.lastIndex,r}if(t instanceof DataView)return new i(t.buffer.slice(0));if(t instanceof Error){const r=new i(t.message);return r.stack=t.stack,r.name=t.name,r.cause=t.cause,r}if(typeof File<"u"&&t instanceof File)return new i([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const r=Object.create(e);return Object.assign(r,t)}return t}function HA(t,...e){const i=e.slice(0,-1),r=e[e.length-1];let n=t;for(let s=0;s<i.length;s++){const o=i[s];n=sc(n,o,r,new Map)}return n}function sc(t,e,i,r){if(Xc(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(r.has(e))return VA(r.get(e));if(r.set(e,t),Array.isArray(e)){e=e.slice();for(let s=0;s<e.length;s++)e[s]=e[s]??void 0}const n=[...Object.keys(e),...r0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(hf(a)&&(a={...a}),hf(c)&&(c={...c}),typeof ie<"u"&&ie.isBuffer(a)&&(a=uf(a)),Array.isArray(a))if(typeof c=="object"&&c!=null){const u=[],h=Reflect.ownKeys(c);for(let f=0;f<h.length;f++){const d=h[f];u[d]=c[d]}c=u}else c=[];const l=i(c,a,o,t,e,r);l!=null?t[o]=l:Array.isArray(a)||ff(c)&&ff(a)?t[o]=sc(c,a,i,r):c==null&&zA(a)?t[o]=sc({},a,i,r):c==null&&qA(a)?t[o]=uf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function KA(t,...e){return HA(t,...e,MA)}const df="error",WA="wss://relay.walletconnect.org",GA="wc",l0="universal_provider",ss=`${GA}@2:${l0}:`,u0="https://rpc.walletconnect.org/v1/",h0="generic",YA=`${u0}bundler`,Tr="call_status",ZA=86400,el={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var JA=Object.defineProperty,XA=Object.defineProperties,QA=Object.getOwnPropertyDescriptors,pf=Object.getOwnPropertySymbols,e4=Object.prototype.hasOwnProperty,t4=Object.prototype.propertyIsEnumerable,gf=(t,e,i)=>e in t?JA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,os=(t,e)=>{for(var i in e||(e={}))e4.call(e,i)&&gf(t,i,e[i]);if(pf)for(var i of pf(e))t4.call(e,i)&&gf(t,i,e[i]);return t},i4=(t,e)=>XA(t,QA(e));function f0(t,e,i){var r;const n=ci(t);return((r=e.rpcMap)==null?void 0:r[n.reference])||`${u0}?chainId=${n.namespace}:${n.reference}&projectId=${i}`}function r4(t){return t.includes(":")?t.split(":")[1]:t}function d0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function n4(t,e){const i=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!i.length)return[];const r=[];return i.forEach(n=>{const s=e.namespaces[n].accounts;r.push(...s)}),r}function yf(t){return Object.fromEntries(Object.entries(t).filter(([e,i])=>{var r,n;return((r=i==null?void 0:i.chains)==null?void 0:r.length)&&((n=i==null?void 0:i.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const i=yf(wf(t)),r=yf(wf(e));return KA(i,r)}function wf(t){var e,i,r,n,s;const o={};if(!Ht(t))return o;for(const[a,c]of Object.entries(t)){const l=so(a)?[a]:c.chains,u=c.methods||[],h=c.events||[],f=c.rpcMap||{},d=Dr(a);o[d]=i4(os(os({},o[d]),c),{chains:Vt(l,(e=o[d])==null?void 0:e.chains),methods:Vt(u,(i=o[d])==null?void 0:i.methods),events:Vt(h,(r=o[d])==null?void 0:r.events)}),(Ht(f)||Ht(((n=o[d])==null?void 0:n.rpcMap)||{}))&&(o[d].rpcMap=os(os({},f),(s=o[d])==null?void 0:s.rpcMap))}return o}function mf(t){return t.includes(":")?t.split(":")[2]:t}function bf(t){const e={};for(const[i,r]of Object.entries(t)){const n=r.methods||[],s=r.events||[],o=r.accounts||[],a=so(i)?[i]:r.chains?r.chains:d0(r.accounts);e[i]={chains:a,methods:n,events:s,accounts:o}}return e}function aa(t){return typeof t=="number"?t:t.includes("0x")?parseInt(t,16):(t=t.includes(":")?t.split(":")[1]:t,isNaN(Number(t))?t:Number(t))}function s4(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const p0={},Rr=t=>p0[t],ca=(t,e)=>{p0[t]=e};var o4=Object.defineProperty,vf=Object.getOwnPropertySymbols,a4=Object.prototype.hasOwnProperty,c4=Object.prototype.propertyIsEnumerable,Ef=(t,e,i)=>e in t?o4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,xf=(t,e)=>{for(var i in e||(e={}))a4.call(e,i)&&Ef(t,i,e[i]);if(vf)for(var i of vf(e))c4.call(e,i)&&Ef(t,i,e[i]);return t};const If="eip155",l4=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],u4=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,la=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,_f=t=>Object.keys(t).filter(e=>l4.includes(e)).reduce((e,i)=>(e[i]=h4(t[i]),e),{}),h4=t=>typeof t=="string"&&s4(t)?JSON.parse(t):t,f4=(t,e,i)=>{const{sessionProperties:r={},scopedProperties:n={}}=t,s={};if(!Ht(n)&&!Ht(r))return;const o=_f(r);for(const a of i){const c=u4(a);if(!c)continue;s[la(c)]=o;const l=n==null?void 0:n[`${If}:${c}`];if(l){const u=l==null?void 0:l[`${If}:${c}:${e}`];s[la(c)]=xf(xf({},s[la(c)]),_f(u||l))}}for(const[a,c]of Object.entries(s))Object.keys(c).length===0&&delete s[a];return Object.keys(s).length>0?s:void 0};var d4=Object.defineProperty,p4=(t,e,i)=>e in t?d4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,g4=(t,e,i)=>p4(t,typeof e!="symbol"?e+"":e,i);let ua,y4=class g0{constructor(e){g4(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,i){return await this.storage.setItem(e,i)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ua||(ua=new g0(e)),ua}};var w4=Object.defineProperty,m4=Object.defineProperties,b4=Object.getOwnPropertyDescriptors,Sf=Object.getOwnPropertySymbols,v4=Object.prototype.hasOwnProperty,E4=Object.prototype.propertyIsEnumerable,$f=(t,e,i)=>e in t?w4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,x4=(t,e)=>{for(var i in e||(e={}))v4.call(e,i)&&$f(t,i,e[i]);if(Sf)for(var i of Sf(e))E4.call(e,i)&&$f(t,i,e[i]);return t},I4=(t,e)=>m4(t,b4(e));async function _4(t,e){const i=ci(t.result.capabilities.caip345.caip2),r=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(r.map(h=>S4(i.reference,h,e))),s=n.filter(h=>h.status==="fulfilled").map(h=>h.value).filter(h=>h);n.filter(h=>h.status==="rejected").forEach(h=>console.warn("Failed to fetch transaction receipt:",h.reason));const o=!s.length||s.some(h=>!h),a=s.every(h=>(h==null?void 0:h.status)==="0x1"),c=s.every(h=>(h==null?void 0:h.status)==="0x0"),l=s.some(h=>(h==null?void 0:h.status)==="0x0");let u;return o?u=100:a?u=200:c?u=500:l&&(u=600),{id:t.result.id,version:t.request.version,atomic:t.request.atomicRequired,chainId:t.request.chainId,capabilities:t.result.capabilities,receipts:s,status:u}}async function S4(t,e,i){return await i(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function $4({sendCalls:t,storage:e}){const i=await e.getItem(Tr);await e.setItem(Tr,I4(x4({},i),{[t.result.id]:{request:t.request,result:t.result,expiry:we(ZA)}}))}async function D4({resultId:t,storage:e}){const i=await e.getItem(Tr);if(i){delete i[t],await e.setItem(Tr,i);for(const r in i)qt(i[r].expiry)&&delete i[r];await e.setItem(Tr,i)}}async function O4({resultId:t,storage:e}){const i=await e.getItem(Tr),r=i==null?void 0:i[t];if(r&&!qt(r.expiry))return r;await D4({resultId:t,storage:e})}var A4=Object.defineProperty,P4=Object.defineProperties,C4=Object.getOwnPropertyDescriptors,Df=Object.getOwnPropertySymbols,B4=Object.prototype.hasOwnProperty,T4=Object.prototype.propertyIsEnumerable,oc=(t,e,i)=>e in t?A4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,ha=(t,e)=>{for(var i in e||(e={}))B4.call(e,i)&&oc(t,i,e[i]);if(Df)for(var i of Df(e))T4.call(e,i)&&oc(t,i,e[i]);return t},fa=(t,e)=>P4(t,C4(e)),Hi=(t,e,i)=>oc(t,typeof e!="symbol"?e+"":e,i);class R4{constructor(e){Hi(this,"name","eip155"),Hi(this,"client"),Hi(this,"chainId"),Hi(this,"namespace"),Hi(this,"httpProviders"),Hi(this,"events"),Hi(this,"storage"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=y4.getStorage(this.client.core.storage)}async request(e){switch(e.request.method){case"eth_requestAccounts":return this.getAccounts();case"eth_accounts":return this.getAccounts();case"wallet_switchEthereumChain":return await this.handleSwitchChain(e);case"eth_chainId":return parseInt(this.getDefaultChain());case"wallet_getCapabilities":return await this.getCapabilities(e);case"wallet_getCallsStatus":return await this.getCallStatus(e);case"wallet_sendCalls":return await this.sendCalls(e)}return this.namespace.methods.includes(e.request.method)?await this.client.request(e):this.getHttpProvider().request(e.request)}updateNamespace(e){this.namespace=Object.assign(this.namespace,e)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(parseInt(e),i);const r=this.chainId;this.chainId=parseInt(e),this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}requestAccounts(){return this.getAccounts()}getDefaultChain(){if(this.chainId)return this.chainId.toString();if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}createHttpProvider(e,i){const r=i||f0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProviders(){const e={};return this.namespace.chains.forEach(i=>{var r;const n=parseInt(r4(i));e[n]=this.createHttpProvider(n,(r=this.namespace.rpcMap)==null?void 0:r[i])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}getHttpProvider(e){const i=e||this.chainId;return this.httpProviders[i]||(this.httpProviders=fa(ha({},this.httpProviders),{[i]:this.createHttpProvider(i)}),this.httpProviders[i])}async handleSwitchChain(e){var i,r;let n=e.request.params?(i=e.request.params[0])==null?void 0:i.chainId:"0x0";n=n.startsWith("0x")?n:`0x${n}`;const s=parseInt(n,16);if(this.isChainApproved(s))this.setDefaultChain(`${s}`);else if(this.namespace.methods.includes("wallet_switchEthereumChain"))await this.client.request({topic:e.topic,request:{method:e.request.method,params:[{chainId:n}]},chainId:(r=this.namespace.chains)==null?void 0:r[0]}),this.setDefaultChain(`${s}`);else throw new Error(`Failed to switch to chain 'eip155:${s}'. The chain is not approved or the wallet does not support 'wallet_switchEthereumChain' method.`);return null}isChainApproved(e){return this.namespace.chains.includes(`${this.name}:${e}`)}async getCapabilities(e){var i,r,n,s,o;const a=(r=(i=e.request)==null?void 0:i.params)==null?void 0:r[0],c=((s=(n=e.request)==null?void 0:n.params)==null?void 0:s[1])||[];if(!a)throw new Error("Missing address parameter in `wallet_getCapabilities` request");const l=this.client.session.get(e.topic),u=((o=l==null?void 0:l.sessionProperties)==null?void 0:o.capabilities)||{},h=`${a}${c.join(",")}`,f=u==null?void 0:u[h];if(f)return f;let d;try{d=f4(l,a,c)}catch(g){console.warn("Failed to extract capabilities from session",g)}if(d)return d;const p=await this.client.request(e);try{await this.client.session.update(e.topic,{sessionProperties:fa(ha({},l.sessionProperties||{}),{capabilities:fa(ha({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var i,r,n;const s=this.client.session.get(e.topic),o=(i=s.sessionProperties)==null?void 0:i.bundler_name;if(o){const l=this.getBundlerUrl(e.chainId,o);try{return await this.getUserOperationReceipt(l,e)}catch(u){console.warn("Failed to fetch call status from bundler",u,l)}}const a=(r=s.sessionProperties)==null?void 0:r.bundler_url;if(a)try{return await this.getUserOperationReceipt(a,e)}catch(l){console.warn("Failed to fetch call status from custom bundler",l,a)}const c=await O4({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await _4(c,this.getHttpProvider.bind(this))}catch(l){console.warn("Failed to fetch call status from stored send calls",l,c)}if(this.namespace.methods.includes(e.request.method))return await this.client.request(e);throw new Error("Fetching call status not approved by the wallet.")}async getUserOperationReceipt(e,i){var r;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(r=i.request.params)==null?void 0:r[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,i){return`${YA}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${i}`}async sendCalls(e){var i,r,n;const s=await this.client.request(e),o=(i=e.request.params)==null?void 0:i[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(r=c==null?void 0:c.caip345)==null?void 0:r.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await $4({sendCalls:{request:o,result:s},storage:this.storage}),s}}var F4=Object.defineProperty,N4=(t,e,i)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Ir=(t,e,i)=>N4(t,typeof e!="symbol"?e+"":e,i);class U4{constructor(e){Ir(this,"name",h0),Ir(this,"client"),Ir(this,"httpProviders"),Ir(this,"events"),Ir(this,"namespace"),Ir(this,"chainId"),this.namespace=e.namespace,this.events=Rr("events"),this.client=Rr("client"),this.chainId=this.getDefaultChain(),this.name=this.getNamespaceName(),this.httpProviders=this.createHttpProviders()}updateNamespace(e){this.namespace.chains=[...new Set((this.namespace.chains||[]).concat(e.chains||[]))],this.namespace.accounts=[...new Set((this.namespace.accounts||[]).concat(e.accounts||[]))],this.namespace.methods=[...new Set((this.namespace.methods||[]).concat(e.methods||[]))],this.namespace.events=[...new Set((this.namespace.events||[]).concat(e.events||[]))],this.httpProviders=this.createHttpProviders()}requestAccounts(){return this.getAccounts()}request(e){return this.namespace.methods.includes(e.request.method)?this.client.request(e):this.getHttpProvider(e.chainId).request(e.request)}setDefaultChain(e,i){this.httpProviders[e]||this.setHttpProvider(e,i);const r=this.chainId;this.chainId=e,this.events.emit(el.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${r}`})}getDefaultChain(){if(this.chainId)return this.chainId;if(this.namespace.defaultChain)return this.namespace.defaultChain;const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return e.split(":")[1]}getNamespaceName(){const e=this.namespace.chains[0];if(!e)throw new Error("ChainId not found");return ci(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(i=>i.split(":")[1]===this.chainId.toString()).map(i=>i.split(":")[2]))]:[]}createHttpProviders(){var e,i;const r={};return(i=(e=this.namespace)==null?void 0:e.accounts)==null||i.forEach(n=>{var s,o;const a=ci(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];r[a.reference]=this.createHttpProvider(n,c)}),r}getHttpProvider(e){const i=ci(e).reference,r=this.httpProviders[i];if(typeof r>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return r}setHttpProvider(e,i){const r=this.createHttpProvider(e,i);r&&(this.httpProviders[e]=r)}createHttpProvider(e,i){const r=i||f0(e,this.namespace,this.client.core.projectId);if(!r)throw new Error(`No RPC url provided for chainId: ${e}`);return new Yc(new i0(r,Rr("disableProviderPing")))}}var k4=Object.defineProperty,j4=Object.defineProperties,L4=Object.getOwnPropertyDescriptors,Of=Object.getOwnPropertySymbols,M4=Object.prototype.hasOwnProperty,q4=Object.prototype.propertyIsEnumerable,ac=(t,e,i)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,sn=(t,e)=>{for(var i in e||(e={}))M4.call(e,i)&&ac(t,i,e[i]);if(Of)for(var i of Of(e))q4.call(e,i)&&ac(t,i,e[i]);return t},cs=(t,e)=>j4(t,L4(e)),at=(t,e,i)=>ac(t,typeof e!="symbol"?e+"":e,i);class tl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new lc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var i,r;this.providerOpts=e,this.logger=Kc({logger:(i=e.logger)!=null?i:df,name:(r=this.providerOpts.name)!=null?r:l0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const i=new tl(e);return await i.initialize(),i}async request(e,i,r){const[n,s]=this.validateChain(i);if(!this.session)throw new Error("Please call connect() before request()");return await this.getProvider(n).request({request:sn({},e),chainId:`${n}:${s}`,topic:this.session.topic,expiry:r})}sendAsync(e,i,r,n){const s=new Date().getTime();this.request(e,r,n).then(o=>i(null,Sn(s,o))).catch(o=>i(o,void 0))}async enable(){if(!this.client)throw new Error("Sign Client not initialized");return this.session||await this.connect({namespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties}),await this.requestAccounts()}async disconnect(){var e;if(!this.session)throw new Error("Please call connect() before enable()");await this.client.disconnect({topic:(e=this.session)==null?void 0:e.topic,reason:fe("USER_DISCONNECTED")}),await this.cleanup()}async connect(e){if(!this.client)throw new Error("Sign Client not initialized");if(this.connectParams=e,this.setNamespaces(e),this.cleanupPendingPairings(),!e.skipPairing)return await this.pair(e.pairingTopic)}async authenticate(e,i){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:r,response:n}=await this.client.authenticate(e,i);r&&(this.uri=r,this.events.emit("display_uri",r));const s=await n();if(this.session=s.session,this.session){const o=bf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,i){this.events.on(e,i)}once(e,i){this.events.once(e,i)}removeListener(e,i){this.events.removeListener(e,i)}off(e,i){this.events.off(e,i)}get isWalletConnect(){return!0}async pair(e){var i,r;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(i=this.connectParams)==null?void 0:i.authentication,walletPay:(r=this.connectParams)==null?void 0:r.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=bf(o.namespaces);return this.namespaces=as(this.namespaces,a),await this.persist("namespaces",this.namespaces),await this.persist("optionalNamespaces",this.optionalNamespaces),this.onConnect(),this.session}setDefaultChain(e,i){try{if(!this.session)return;const[r,n]=this.validateChain(e);this.getProvider(r).setDefaultChain(n,i)}catch(r){if(!/Please call connect/.test(r.message))throw r}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const i=this.client.pairing.getAll();if(!It(i))return;for(const r of i)e.deletePairings?this.client.core.expirer.set(r.topic,0):await this.client.core.relayer.subscriber.unsubscribe(r.topic);this.logger.info(`Inactive pairings cleared: ${i.length}`)}catch(i){this.logger.warn(i,"Failed to cleanup pending pairings")}}abortPairingAttempt(){this.logger.warn("abortPairingAttempt is deprecated. This is now a no-op.")}async checkStorage(){this.namespaces=await this.getFromStore("namespaces")||{},this.optionalNamespaces=await this.getFromStore("optionalNamespaces")||{},this.session&&this.createProviders()}async initialize(){this.logger.trace("Initialized"),await this.createClient(),await this.checkStorage(),this.registerEventListeners()}async createClient(){var e,i;if(this.client=this.providerOpts.client||await fA.init({core:this.providerOpts.core,logger:this.providerOpts.logger||df,relayUrl:this.providerOpts.relayUrl||WA,projectId:this.providerOpts.projectId,metadata:this.providerOpts.metadata,storageOptions:this.providerOpts.storageOptions,storage:this.providerOpts.storage,name:this.providerOpts.name,customStoragePrefix:this.providerOpts.customStoragePrefix,telemetryEnabled:this.providerOpts.telemetryEnabled}),this.providerOpts.session)try{this.session=this.client.session.get(this.providerOpts.session.topic)}catch(r){throw this.logger.error(r,"Failed to get session"),new Error(`The provided session: ${(i=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:i.topic} doesn't exist in the Sign client`)}else{const r=this.client.session.getAll();this.session=r[0]}this.logger.trace("SignClient Initialized")}createProviders(){if(!this.client)throw new Error("Sign Client not initialized");if(!this.session)throw new Error("Session not initialized. Please call connect() before enable()");const e=[...new Set(Object.keys(this.session.namespaces).map(i=>Dr(i)))];ca("client",this.client),ca("events",this.events),ca("disableProviderPing",this.disableProviderPing),e.forEach(i=>{if(!this.session)return;const r=n4(i,this.session);if((r==null?void 0:r.length)===0)return;const n=d0(r),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[i]),{accounts:r,chains:n});switch(i){case"eip155":this.rpcProviders[i]=new R4({namespace:o});break;default:this.rpcProviders[i]=new U4({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var i;const{topic:r}=e;r===((i=this.session)==null?void 0:i.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var i;const{params:r,topic:n}=e;if(n!==((i=this.session)==null?void 0:i.topic))return;const{event:s}=r;if(s.name==="accountsChanged"){const o=s.data;o&&It(o)&&this.events.emit("accountsChanged",o.map(mf))}else if(s.name==="chainChanged"){const o=r.chainId,a=r.event.data,c=Dr(o),l=aa(o)!==aa(a)?`${c}:${aa(a)}`:o;this.onChainChanged({currentCaipChainId:l})}else this.events.emit(s.name,s.data);this.events.emit("session_event",e)}),this.client.on("session_update",({topic:e,params:i})=>{var r,n;if(e!==((r=this.session)==null?void 0:r.topic))return;const{namespaces:s}=i,o=(n=this.client)==null?void 0:n.session.get(e);this.session=cs(sn({},o),{namespaces:s}),this.onSessionUpdate(),this.events.emit("session_update",{topic:e,params:i})}),this.client.on("session_delete",async e=>{var i;e.topic===((i=this.session)==null?void 0:i.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(el.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[h0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var i;this.getProvider(e).updateNamespace((i=this.session)==null?void 0:i.namespaces[e])})}setNamespaces(e){const{namespaces:i={},optionalNamespaces:r={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(i,r),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[i,r]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[i,r];if(i&&!Object.keys(this.namespaces||{}).map(o=>Dr(o)).includes(i))throw new Error(`Namespace '${i}' is not configured. Please call connect() first with namespace config.`);if(i&&r)return[i,r];const n=Dr(Object.keys(this.namespaces)[0]),s=this.rpcProviders[n].getDefaultChain();return[n,s]}async requestAccounts(){const[e]=this.validateChain();return await this.getProvider(e).requestAccounts()}async onChainChanged({currentCaipChainId:e,previousCaipChainId:i,internal:r=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),r?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:i})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:i,previousCaipChainId:r}){var n,s;try{if(r===i)return;const o=(s=(n=this.session)==null?void 0:n.namespaces[e])==null?void 0:s.accounts;if(!o)return;const a=o.filter(c=>c.includes(`${i}:`)).map(mf);if(!It(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,i){if(!this.namespaces)return;const r=this.namespaces[e]?e:`${e}:${i}`,n={chains:[],methods:[],events:[],defaultChain:i};this.namespaces[r]?this.namespaces[r]&&(this.namespaces[r].defaultChain=i):this.namespaces[r]=n}onConnect(){this.createProviders(),this.events.emit("connect",{session:this.session})}async cleanup(){this.connectParams=void 0,this.namespaces=void 0,this.optionalNamespaces=void 0,this.sessionProperties=void 0,await this.deleteFromStore("namespaces"),await this.deleteFromStore("optionalNamespaces"),await this.deleteFromStore("sessionProperties"),this.session=void 0,this.cleanupPendingPairings({deletePairings:!0}),await this.cleanupStorage()}async persist(e,i){var r;const n=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,i)}async getFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${r}`)}async deleteFromStore(e){var i;const r=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${r}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const i=await this.client.core.storage.getKeys();for(const r of i)r.startsWith(ss)&&await this.client.core.storage.removeItem(r)}catch(i){this.logger.warn(i,"Failed to cleanup storage")}}}const z4=tl,V4="wc",H4="ethereum_provider",K4=`${V4}@2:${H4}:`,W4="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],y0=["eth_accounts","eth_requestAccounts","eth_sendRawTransaction","eth_sign","eth_signTransaction","eth_signTypedData","eth_signTypedData_v3","eth_signTypedData_v4","eth_sendTransaction","personal_sign","wallet_switchEthereumChain","wallet_addEthereumChain","wallet_getPermissions","wallet_requestPermissions","wallet_registerOnboarding","wallet_watchAsset","wallet_scanQRCode","wallet_sendCalls","wallet_getCapabilities","wallet_getCallsStatus","wallet_showCallsStatus"],js=["chainChanged","accountsChanged"],w0=["chainChanged","accountsChanged","message","disconnect","connect"],G4=async()=>{const{createAppKit:t}=await O0(()=>import("./core-84b3ed1e.js").then(e=>e.bK),["assets/core-84b3ed1e.js","assets/index-fec77d48.js","assets/index-91d98a83.css"]);return t};var Y4=Object.defineProperty,Z4=Object.defineProperties,J4=Object.getOwnPropertyDescriptors,Af=Object.getOwnPropertySymbols,X4=Object.prototype.hasOwnProperty,Q4=Object.prototype.propertyIsEnumerable,cc=(t,e,i)=>e in t?Y4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,Wi=(t,e)=>{for(var i in e||(e={}))X4.call(e,i)&&cc(t,i,e[i]);if(Af)for(var i of Af(e))Q4.call(e,i)&&cc(t,i,e[i]);return t},on=(t,e)=>Z4(t,J4(e)),ct=(t,e,i)=>cc(t,typeof e!="symbol"?e+"":e,i);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function e5(t){const{chains:e,optionalChains:i,methods:r,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!It(e))throw new Error("Invalid chains");const c={chains:e,methods:r||ks,events:s||js,rpcMap:Wi({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=r==null?void 0:r.filter(d=>!ks.includes(d));if(!i&&!o&&!n&&!(l!=null&&l.length)&&!(u!=null&&u.length))return{required:e.length?c:void 0};const h=(l==null?void 0:l.length)&&(u==null?void 0:u.length)||!i,f={chains:[...new Set(h?c.chains.concat(i||[]):i)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:y0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:w0))],rpcMap:a};return{required:e.length?c:void 0,optional:i.length?f:void 0}}class uo{constructor(){ct(this,"events",new St.EventEmitter),ct(this,"namespace","eip155"),ct(this,"accounts",[]),ct(this,"signer"),ct(this,"chainId",1),ct(this,"modal"),ct(this,"rpc"),ct(this,"STORAGE_KEY",K4),ct(this,"on",(e,i)=>(this.events.on(e,i),this)),ct(this,"once",(e,i)=>(this.events.once(e,i),this)),ct(this,"removeListener",(e,i)=>(this.events.removeListener(e,i),this)),ct(this,"off",(e,i)=>(this.events.off(e,i),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const i=new uo;return await i.initialize(e),i}async request(e,i){return await this.signer.request(e,this.formatChainId(this.chainId),i)}sendAsync(e,i,r){this.signer.sendAsync(e,i,this.formatChainId(this.chainId),r)}get connected(){return this.signer.client?this.signer.client.core.relayer.connected:!1}get connecting(){return this.signer.client?this.signer.client.core.relayer.connecting:!1}async enable(){return this.session||await this.connect(),await this.request({method:"eth_requestAccounts"})}async connect(e){var i;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:r,optional:n}=e5(this.rpc);try{const s=await new Promise(async(a,c)=>{var l,u;this.rpc.showQrModal&&((l=this.modal)==null||l.open(),(u=this.modal)==null||u.subscribeState(f=>{!f.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),c(new Error("Connection request reset. Please try again.")))}));const h=e!=null&&e.scopedProperties?{[this.namespace]:e.scopedProperties}:void 0;await this.signer.connect(on(Wi({namespaces:Wi({},r&&{[this.namespace]:r})},n&&{optionalNamespaces:{[this.namespace]:n}}),{pairingTopic:e==null?void 0:e.pairingTopic,scopedProperties:h})).then(f=>{a(f)}).catch(f=>{var d;(d=this.modal)==null||d.showErrorMessage("Unable to connect"),c(new Error(f.message))})});if(!s)return;const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}catch(s){throw this.signer.logger.error(s),s}finally{(i=this.modal)==null||i.close()}}async authenticate(e,i){var r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts({chains:e==null?void 0:e.chains});try{const n=await new Promise(async(o,a)=>{var c,l;this.rpc.showQrModal&&((c=this.modal)==null||c.open(),(l=this.modal)==null||l.subscribeState(u=>{!u.open&&!this.signer.session&&(this.signer.abortPairingAttempt(),a(new Error("Connection request reset. Please try again.")))})),await this.signer.authenticate(on(Wi({},e),{chains:this.rpc.chains}),i).then(u=>{o(u)}).catch(u=>{var h;(h=this.modal)==null||h.showErrorMessage("Unable to connect"),a(new Error(u.message))})}),s=n.session;if(s){const o=bu(s.namespaces,[this.namespace]);this.setChainIds(this.rpc.chains.length?this.rpc.chains:o),this.setAccounts(o),this.events.emit("connect",{chainId:ls(this.chainId)})}return n}catch(n){throw this.signer.logger.error(n),n}finally{(r=this.modal)==null||r.close()}}async disconnect(){this.session&&await this.signer.disconnect(),this.reset()}get isWalletConnect(){return!0}get session(){return this.signer.session}registerEventListeners(){this.signer.on("session_event",e=>{const{params:i}=e,{event:r}=i;r.name==="accountsChanged"?(this.accounts=this.parseAccounts(r.data),this.events.emit("accountsChanged",this.accounts)):r.name==="chainChanged"?this.setChainId(this.formatChainId(r.data)):this.events.emit(r.name,r.data),this.events.emit("session_event",e)}),this.signer.on("accountsChanged",e=>{this.accounts=this.parseAccounts(e),this.events.emit("accountsChanged",this.accounts)}),this.signer.on("chainChanged",e=>{const i=parseInt(e);this.chainId=i,this.events.emit("chainChanged",ls(this.chainId)),this.persist()}),this.signer.on("session_update",e=>{this.events.emit("session_update",e)}),this.signer.on("session_delete",e=>{this.reset(),this.events.emit("session_delete",e),this.events.emit("disconnect",on(Wi({},fe("USER_DISCONNECTED")),{data:e.topic,name:"USER_DISCONNECTED"}))}),this.signer.on("display_uri",e=>{this.events.emit("display_uri",e)})}switchEthereumChain(e){this.request({method:"wallet_switchEthereumChain",params:[{chainId:e.toString(16)}]})}isCompatibleChainId(e){return typeof e=="string"?e.startsWith(`${this.namespace}:`):!1}formatChainId(e){return`${this.namespace}:${e}`}parseChainId(e){return Number(e.split(":")[1])}setChainIds(e){const i=e.filter(r=>this.isCompatibleChainId(r)).map(r=>this.parseChainId(r));i.length&&(this.chainId=i[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const i=this.parseChainId(e);this.chainId=i,this.switchEthereumChain(i)}}parseAccountId(e){const[i,r,n]=e.split(":");return{chainId:`${i}:${r}`,address:n}}setAccounts(e){this.accounts=e.filter(i=>this.parseChainId(this.parseAccountId(i).chainId)===this.chainId).map(i=>this.parseAccountId(i).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var i,r;const n=(i=e==null?void 0:e.chains)!=null?i:[],s=(r=e==null?void 0:e.optionalChains)!=null?r:[],o=n.concat(s);if(!o.length)throw new Error("No chains specified in either `chains` or `optionalChains`");const a=n.length?(e==null?void 0:e.methods)||ks:[],c=n.length?(e==null?void 0:e.events)||js:[],l=(e==null?void 0:e.optionalMethods)||[],u=(e==null?void 0:e.optionalEvents)||[],h=(e==null?void 0:e.rpcMap)||this.buildRpcMap(o,e.projectId),f=(e==null?void 0:e.qrModalOptions)||void 0;return{chains:n==null?void 0:n.map(d=>this.formatChainId(d)),optionalChains:s.map(d=>this.formatChainId(d)),methods:a,events:c,optionalMethods:l,optionalEvents:u,rpcMap:h,showQrModal:!!(e!=null&&e.showQrModal),qrModalOptions:f,projectId:e.projectId,metadata:e.metadata}}buildRpcMap(e,i){const r={};return e.forEach(n=>{r[n]=this.getRpcUrl(n,i)}),r}async initialize(e){var i;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await z4.init({projectId:this.rpc.projectId,metadata:this.rpc.metadata,disableProviderPing:e.disableProviderPing,relayUrl:e.relayUrl,storage:e.storage,storageOptions:e.storageOptions,customStoragePrefix:e.customStoragePrefix,telemetryEnabled:e.telemetryEnabled,logger:e.logger}),this.registerEventListeners(),await this.loadPersistedSession(),this.rpc.showQrModal){let r;try{const n=await G4(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return h5}),o=s(on(Wi({},this.rpc.qrModalOptions),{chains:[...new Set([...this.rpc.chains,...this.rpc.optionalChains])],metadata:this.rpc.metadata,projectId:this.rpc.projectId}));if(!o.networks.length)throw new Error("No networks found for WalletConnect");r=n(on(Wi({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((i=this.rpc.qrModalOptions)==null?void 0:i.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(r)try{this.modal=r}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:i,optionalChains:r,rpcMap:n}=e;i&&It(i)&&(this.rpc.chains=i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),r&&It(r)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=r==null?void 0:r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,i){var r;return((r=this.rpc.rpcMap)==null?void 0:r[e])||`${W4}?chainId=eip155:${e}&projectId=${i||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),i=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:i==null?void 0:i.accounts),this.setAccounts(i==null?void 0:i.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(i=>this.signer.logger.warn(i))}}reset(){this.chainId=1,this.accounts=[]}persist(){this.session&&this.signer.client.core.storage.setItem(`${this.STORAGE_KEY}/chainId`,this.chainId)}parseAccounts(e){return typeof e=="string"||e instanceof String?[this.parseAccount(e)]:e.map(i=>this.parseAccount(i))}}const t5=uo;var i5=Object.defineProperty,r5=Object.defineProperties,n5=Object.getOwnPropertyDescriptors,Pf=Object.getOwnPropertySymbols,s5=Object.prototype.hasOwnProperty,o5=Object.prototype.propertyIsEnumerable,Cf=(t,e,i)=>e in t?i5(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i,m0=(t,e)=>{for(var i in e||(e={}))s5.call(e,i)&&Cf(t,i,e[i]);if(Pf)for(var i of Pf(e))o5.call(e,i)&&Cf(t,i,e[i]);return t},a5=(t,e)=>r5(t,n5(e));function c5(t){if(t)return{"--w3m-font-family":t["--wcm-font-family"],"--w3m-accent":t["--wcm-accent-color"],"--w3m-color-mix":t["--wcm-background-color"],"--w3m-z-index":t["--wcm-z-index"]?Number(t["--wcm-z-index"]):void 0,"--w3m-qr-color":t["--wcm-accent-color"],"--w3m-font-size-master":t["--wcm-text-medium-regular-size"],"--w3m-border-radius-master":t["--wcm-container-border-radius"],"--w3m-color-mix-strength":0}}const l5=t=>{const[e,i]=t.split(":");return b0({id:i,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function u5(t){var e,i,r,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(l5).filter(Boolean);if(c.length===0)throw new Error("At least one chain must be specified");const l=c.find(h=>{var f;return h.id===((f=t.defaultChain)==null?void 0:f.id)}),u={projectId:t.projectId,networks:c,themeMode:t.themeMode,themeVariables:c5(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:a5(m0({},t.metadata),{name:((i=t.metadata)==null?void 0:i.name)||"WalletConnect",description:((r=t.metadata)==null?void 0:r.description)||"Connect to WalletConnect-compatible wallets",url:((n=t.metadata)==null?void 0:n.url)||"https://walletconnect.org",icons:((s=t.metadata)==null?void 0:s.icons)||["https://walletconnect.org/walletconnect-logo.png"]}),showWallets:!0,featuredWalletIds:t.explorerRecommendedWalletIds==="NONE"?[]:Array.isArray(t.explorerRecommendedWalletIds)?t.explorerRecommendedWalletIds:[],excludeWalletIds:t.explorerExcludedWalletIds==="ALL"?[]:Array.isArray(t.explorerExcludedWalletIds)?t.explorerExcludedWalletIds:[],enableEIP6963:!1,enableInjected:!1,enableCoinbase:!0,enableWalletConnect:!0,features:{email:!1,socials:!1}};if((o=t.mobileWallets)!=null&&o.length||(a=t.desktopWallets)!=null&&a.length){const h=[...(t.mobileWallets||[]).map(p=>({id:p.id,name:p.name,links:p.links})),...(t.desktopWallets||[]).map(p=>({id:p.id,name:p.name,links:{native:p.links.native,universal:p.links.universal}}))],f=[...u.featuredWalletIds||[],...u.excludeWalletIds||[]],d=h.filter(p=>!f.includes(p.id));d.length&&(u.customWallets=d)}return u}function b0(t){return m0({formatters:void 0,fees:void 0,serializers:void 0},t)}var h5=Object.freeze({__proto__:null,convertWCMToAppKitOptions:u5,defineChain:b0});const tP=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:t5,OPTIONAL_EVENTS:w0,OPTIONAL_METHODS:y0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{B8 as A,Yc as B,oE as C,i3 as D,QS as E,Gc as F,ao as G,Sn as H,ur as I,hr as J,Ct as K,l2 as L,Ri as M,oo as N,Mt as O,lu as P,Xd as Q,vt as R,Lt as S,i0 as T,tP as U,dt as X,Ep as Y,J8 as a,X8 as b,Ag as c,rs as d,Q8 as e,sr as f,bh as g,Ff as h,L as i,Et as j,tS as k,rr as l,uc as m,An as n,c1 as o,Qm as p,mm as q,Im as r,ui as s,nt as t,mE as u,U0 as v,Rf as w,fn as x,Aa as y,st as z};
|