@dcl/governance-site 1.15.1-20105651460.commit-7620061 → 1.15.1-20473093943.commit-ad8dc42
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/UserAvatar-41371133.js +1 -0
- package/assets/{basic-22d207a7.js → basic-de12c849.js} +1 -1
- package/assets/core-0c13d1dd.js +249 -0
- package/assets/{features-abf09337.js → features-e842dc9f.js} +2 -2
- package/assets/fortmatic-dbae6d9f.js +13 -0
- package/assets/{index-0ed42625.js → index-16e232ba.js} +1 -1
- package/assets/index-2a49049d.js +22 -0
- package/assets/index-37d53923.js +39 -0
- package/assets/index-6dad6f13.js +94 -0
- package/assets/{index-6c5c6262.js → index-726bc846.js} +325 -301
- package/assets/{index-3632219d.css → index-a5cbd387.css} +4 -4
- package/assets/{index-94684a9b.js → index-bc60e460.js} +1 -1
- package/assets/index-c2e969f4.js +47 -0
- package/assets/{tslib.es6-01357a01.js → tslib.es6-1071ccd0.js} +2 -2
- package/assets/{w3m-modal-f845d089.js → w3m-modal-d813356f.js} +1 -1
- package/index.html +4 -4
- package/package.json +3 -3
- package/assets/UserAvatar-9036979f.js +0 -1
- package/assets/core-85d4a2c0.js +0 -253
- package/assets/fortmatic-e88a6ce4.js +0 -13
- package/assets/index-19828012.js +0 -46
- package/assets/index-91cd95cb.js +0 -122
- package/assets/index-f10062b6.js +0 -39
- package/assets/native-847e235b.js +0 -1
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import{e as xt,g as kf,h as Y,B as re,i as St,c as gi,x as dc,o as dl,_ as T0}from"./index-726bc846.js";var pl=globalThis&&globalThis.__spreadArray||function(t,e,r){if(r||arguments.length===2)for(var i=0,n=e.length,s;i<n;i++)(s||!(i in e))&&(s||(s=Array.prototype.slice.call(e,0,i)),s[i]=e[i]);return t.concat(s||Array.prototype.slice.call(e))},R0=function(){function t(e,r,i){this.name=e,this.version=r,this.os=i,this.type="browser"}return t}(),F0=function(){function t(e){this.version=e,this.type="node",this.name="node",this.os=xt.platform}return t}(),N0=function(){function t(e,r,i,n){this.name=e,this.version=r,this.os=i,this.bot=n,this.type="bot-device"}return t}(),U0=function(){function t(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null}return t}(),k0=function(){function t(){this.type="react-native",this.name="react-native",this.version=null,this.os=null}return t}(),j0=/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/,L0=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,gl=3,M0=[["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",j0]],yl=[["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 q0(t){return t?wl(t):typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"?new k0:typeof navigator<"u"?wl(navigator.userAgent):H0()}function z0(t){return t!==""&&M0.reduce(function(e,r){var i=r[0],n=r[1];if(e)return e;var s=n.exec(t);return!!s&&[i,s]},!1)}function wl(t){var e=z0(t);if(!e)return null;var r=e[0],i=e[1];if(r==="searchbot")return new U0;var n=i[1]&&i[1].split(".").join("_").split("_").slice(0,3);n?n.length<gl&&(n=pl(pl([],n,!0),K0(gl-n.length),!0)):n=[];var s=n.join("."),o=V0(t),a=L0.exec(t);return a&&a[1]?new N0(r,s,o,a[1]):new R0(r,s,o)}function V0(t){for(var e=0,r=yl.length;e<r;e++){var i=yl[e],n=i[0],s=i[1],o=s.exec(t);if(o)return n}return null}function H0(){var t=typeof xt<"u"&&xt.version;return t?new F0(xt.version.slice(1)):null}function K0(t){for(var e=[],r=0;r<t;r++)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 pa=function(t,e){return pa=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},pa(t,e)};function W0(t,e){pa(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var ga=function(){return ga=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},ga.apply(this,arguments)};function G0(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function Y0(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function Z0(t,e){return function(r,i){e(r,i,t)}}function J0(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function X0(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function Q0(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,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(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=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 r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function ey(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function ty(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function ya(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function jf(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function ry(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(jf(arguments[e]));return t}function iy(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function wn(t){return this instanceof wn?(this.v=t,this):new wn(t)}function ny(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[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(i[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 sy(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:wn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function oy(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof ya=="function"?ya(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[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 ay(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function cy(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function ly(t){return t&&t.__esModule?t:{default:t}}function uy(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function hy(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const fy=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return ga},__asyncDelegator:sy,__asyncGenerator:ny,__asyncValues:oy,__await:wn,__awaiter:X0,__classPrivateFieldGet:uy,__classPrivateFieldSet:hy,__createBinding:ey,__decorate:Y0,__exportStar:ty,__extends:W0,__generator:Q0,__importDefault:ly,__importStar:cy,__makeTemplateObject:ay,__metadata:J0,__param:Z0,__read:jf,__rest:G0,__spread:ry,__spreadArrays:iy,__values:ya},Symbol.toStringTag,{value:"Module"})),Ms=kf(fy);var fo={},zi={},ml;function dy(){if(ml)return zi;ml=1,Object.defineProperty(zi,"__esModule",{value:!0}),zi.delay=void 0;function t(e){return new Promise(r=>{setTimeout(()=>{r(!0)},e)})}return zi.delay=t,zi}var Lr={},po={},Mr={},bl;function py(){return bl||(bl=1,Object.defineProperty(Mr,"__esModule",{value:!0}),Mr.ONE_THOUSAND=Mr.ONE_HUNDRED=void 0,Mr.ONE_HUNDRED=100,Mr.ONE_THOUSAND=1e3),Mr}var go={},vl;function gy(){return vl||(vl=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 El;function Lf(){return El||(El=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(py(),t),e.__exportStar(gy(),t)}(po)),po}var xl;function yy(){if(xl)return Lr;xl=1,Object.defineProperty(Lr,"__esModule",{value:!0}),Lr.fromMiliseconds=Lr.toMiliseconds=void 0;const t=Lf();function e(i){return i*t.ONE_THOUSAND}Lr.toMiliseconds=e;function r(i){return Math.floor(i/t.ONE_THOUSAND)}return Lr.fromMiliseconds=r,Lr}var _l;function wy(){return _l||(_l=1,function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(dy(),t),e.__exportStar(yy(),t)}(fo)),fo}var yi={},Il;function my(){if(Il)return yi;Il=1,Object.defineProperty(yi,"__esModule",{value:!0}),yi.Watch=void 0;class t{constructor(){this.timestamps=new Map}start(r){if(this.timestamps.has(r))throw new Error(`Watch already started for label: ${r}`);this.timestamps.set(r,{started:Date.now()})}stop(r){const i=this.get(r);if(typeof i.elapsed<"u")throw new Error(`Watch already stopped for label: ${r}`);const n=Date.now()-i.started;this.timestamps.set(r,{started:i.started,elapsed:n})}get(r){const i=this.timestamps.get(r);if(typeof i>"u")throw new Error(`No timestamp found for label: ${r}`);return i}elapsed(r){const i=this.get(r);return i.elapsed||Date.now()-i.started}}return yi.Watch=t,yi.default=t,yi}var yo={},Vi={},Sl;function by(){if(Sl)return Vi;Sl=1,Object.defineProperty(Vi,"__esModule",{value:!0}),Vi.IWatch=void 0;class t{}return Vi.IWatch=t,Vi}var $l;function vy(){return $l||($l=1,function(t){Object.defineProperty(t,"__esModule",{value:!0}),Ms.__exportStar(by(),t)}(yo)),yo}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=Ms;e.__exportStar(wy(),t),e.__exportStar(my(),t),e.__exportStar(vy(),t),e.__exportStar(Lf(),t)})(L);var ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.getLocalStorage=ue.getLocalStorageOrThrow=ue.getCrypto=ue.getCryptoOrThrow=Mf=ue.getLocation=ue.getLocationOrThrow=pc=ue.getNavigator=ue.getNavigatorOrThrow=ii=ue.getDocument=ue.getDocumentOrThrow=ue.getFromWindowOrThrow=ue.getFromWindow=void 0;function li(t){let e;return typeof window<"u"&&typeof window[t]<"u"&&(e=window[t]),e}ue.getFromWindow=li;function ji(t){const e=li(t);if(!e)throw new Error(`${t} is not defined in Window`);return e}ue.getFromWindowOrThrow=ji;function Ey(){return ji("document")}ue.getDocumentOrThrow=Ey;function xy(){return li("document")}var ii=ue.getDocument=xy;function _y(){return ji("navigator")}ue.getNavigatorOrThrow=_y;function Iy(){return li("navigator")}var pc=ue.getNavigator=Iy;function Sy(){return ji("location")}ue.getLocationOrThrow=Sy;function $y(){return li("location")}var Mf=ue.getLocation=$y;function Oy(){return ji("crypto")}ue.getCryptoOrThrow=Oy;function Dy(){return li("crypto")}ue.getCrypto=Dy;function Ay(){return ji("localStorage")}ue.getLocalStorageOrThrow=Ay;function Py(){return li("localStorage")}ue.getLocalStorage=Py;var gc={};Object.defineProperty(gc,"__esModule",{value:!0});var qf=gc.getWindowMetadata=void 0;const Ol=ue;function Cy(){let t,e;try{t=Ol.getDocumentOrThrow(),e=Ol.getLocationOrThrow()}catch{return null}function r(){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 I=e.protocol+"//"+e.host;if(w.indexOf("/")===0)I+=w;else{const C=e.pathname.split("/");C.pop();const b=C.join("/");I+=b+"/"+w}f.push(I)}else if(w.indexOf("//")===0){const I=e.protocol+w;f.push(I)}else f.push(w)}}return f}function i(...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=i("name","og:site_name","og:title","twitter:title");return h||(h=t.title),h}function s(){return i("description","og:description","twitter:description","keywords")}const o=n(),a=s(),c=e.origin,l=r();return{description:a,url:c,icons:l,name:o}}qf=gc.getWindowMetadata=Cy;const By="0.1.1";function Ty(){return By}class de extends Error{constructor(e,r={}){const i=(()=>{var c;if(r.cause instanceof de){if(r.cause.details)return r.cause.details;if(r.cause.shortMessage)return r.cause.shortMessage}return r.cause&&"details"in r.cause&&typeof r.cause.details=="string"?r.cause.details:(c=r.cause)!=null&&c.message?r.cause.message:r.details})(),n=(()=>r.cause instanceof de&&r.cause.docsPath||r.docsPath)(),o=`https://oxlib.sh${n??""}`,a=[e||"An error occurred.",...r.metaMessages?["",...r.metaMessages]:[],...i||n?["",i?`Details: ${i}`:void 0,n?`See: ${o}`:void 0]:[]].filter(c=>typeof c=="string").join(`
|
|
15
|
+
`);super(a,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cause",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:`ox@${Ty()}`}),this.cause=r.cause,this.details=i,this.docs=o,this.docsPath=n,this.shortMessage=e}walk(e){return zf(this,e)}}function zf(t,e){return e!=null&&e(t)?t:t&&typeof t=="object"&&"cause"in t&&t.cause?zf(t.cause,e):e?null:t}const wi=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0;/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Ry(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 ni(t,...e){if(!Ry(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 Fy(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 Fi(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 Vf(t,e){ni(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Ny(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ni(...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 Uy=(()=>new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68)();function ky(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}function jy(t){for(let e=0;e<t.length;e++)t[e]=ky(t[e]);return t}const Dl=Uy?t=>t:jy;function Ly(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function qs(t){return typeof t=="string"&&(t=Ly(t)),ni(t),t}function My(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];ni(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}class yc{}function Hf(t){const e=i=>t().update(qs(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function qy(t=32){if(wi&&typeof wi.getRandomValues=="function")return wi.getRandomValues(new Uint8Array(t));if(wi&&typeof wi.randomBytes=="function")return Uint8Array.from(wi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}function zy(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function Vy(t,e,r){return t&e^~t&r}function Hy(t,e,r){return t&e^t&r^e&r}class Ky extends yc{constructor(e,r,i,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=wo(this.buffer)}update(e){Fi(this),e=qs(e),ni(e);const{view:r,buffer:i,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}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Fi(this),Vf(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,Ni(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;zy(i,n-8,BigInt(this.length*8),s),this.process(i,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:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}}const pr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),jn=BigInt(2**32-1),Al=BigInt(32);function Wy(t,e=!1){return e?{h:Number(t&jn),l:Number(t>>Al&jn)}:{h:Number(t>>Al&jn)|0,l:Number(t&jn)|0}}function Gy(t,e=!1){const r=t.length;let i=new Uint32Array(r),n=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Wy(t[s],e);[i[s],n[s]]=[o,a]}return[i,n]}const Yy=(t,e,r)=>t<<r|e>>>32-r,Zy=(t,e,r)=>e<<r|t>>>32-r,Jy=(t,e,r)=>e<<r-32|t>>>64-r,Xy=(t,e,r)=>t<<r-32|e>>>64-r,Qy=BigInt(0),Hi=BigInt(1),ew=BigInt(2),tw=BigInt(7),rw=BigInt(256),iw=BigInt(113),Kf=[],Wf=[],Gf=[];for(let t=0,e=Hi,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Kf.push(2*(5*i+r)),Wf.push((t+1)*(t+2)/2%64);let n=Qy;for(let s=0;s<7;s++)e=(e<<Hi^(e>>tw)*iw)%rw,e&ew&&(n^=Hi<<(Hi<<BigInt(s))-Hi);Gf.push(n)}const Yf=Gy(Gf,!0),nw=Yf[0],sw=Yf[1],Pl=(t,e,r)=>r>32?Jy(t,e,r):Yy(t,e,r),Cl=(t,e,r)=>r>32?Xy(t,e,r):Zy(t,e,r);function ow(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Pl(l,u,1)^r[a],f=Cl(l,u,1)^r[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=Wf[o],c=Pl(n,s,a),l=Cl(n,s,a),u=Kf[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++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=nw[i],t[1]^=sw[i]}Ni(r)}class wc extends yc{constructor(e,r,i,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=r,this.outputLen=i,this.enableXOF=n,this.rounds=s,mn(i),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Ny(this.state)}clone(){return this._cloneInto()}keccak(){Dl(this.state32),ow(this.state32,this.rounds),Dl(this.state32),this.posOut=0,this.pos=0}update(e){Fi(this),e=qs(e),ni(e);const{blockLen:r,state:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);for(let a=0;a<o;a++)i[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:n}=this;e[i]^=r,r&128&&i===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Fi(this,!1),ni(e),this.finish();const r=this.state,{blockLen:i}=this;for(let n=0,s=e.length;n<s;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,s-n);e.set(r.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(Vf(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,Ni(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new wc(r,i,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=i,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const aw=(t,e,r)=>Hf(()=>new wc(e,t,r)),cw=(()=>aw(1,136,256/8))(),lw=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),gr=new Uint32Array(64);class uw extends Ky{constructor(e=32){super(64,e,8,!1),this.A=pr[0]|0,this.B=pr[1]|0,this.C=pr[2]|0,this.D=pr[3]|0,this.E=pr[4]|0,this.F=pr[5]|0,this.G=pr[6]|0,this.H=pr[7]|0}get(){const{A:e,B:r,C:i,D:n,E:s,F:o,G:a,H:c}=this;return[e,r,i,n,s,o,a,c]}set(e,r,i,n,s,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)gr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=gr[h-15],d=gr[h-2],p=Rt(f,7)^Rt(f,18)^f>>>3,g=Rt(d,17)^Rt(d,19)^d>>>10;gr[h]=g+gr[h-7]+p+gr[h-16]|0}let{A:i,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+Vy(a,c,l)+lw[h]+gr[h]|0,g=(Rt(i,2)^Rt(i,13)^Rt(i,22))+Hy(i,n,s)|0;u=l,l=c,c=a,a=o+d|0,o=s,s=n,n=i,i=d+g|0}i=i+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(i,n,s,o,a,c,l,u)}roundClean(){Ni(gr)}destroy(){this.set(0,0,0,0,0,0,0,0),Ni(this.buffer)}}const hw=Hf(()=>new uw);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const mc=BigInt(0),wa=BigInt(1);function On(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function bc(t){if(!On(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===""?mc:BigInt("0x"+t)}const Jf=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",fw=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function vn(t){if(bc(t),Jf)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=fw[t[r]];return e}const Yt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Bl(t){if(t>=Yt._0&&t<=Yt._9)return t-Yt._0;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 ms(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(Jf)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Bl(t.charCodeAt(s)),a=Bl(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)}i[n]=o*16+a}return i}function ri(t){return Zf(vn(t))}function Xf(t){return bc(t),Zf(vn(Uint8Array.from(t).reverse()))}function Dn(t,e){return ms(t.toString(16).padStart(e*2,"0"))}function Qf(t,e){return Dn(t,e).reverse()}function mt(t,e,r){let i;if(typeof e=="string")try{i=ms(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(On(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}function bs(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];bc(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}const mo=t=>typeof t=="bigint"&&mc<=t;function vc(t,e,r){return mo(t)&&mo(e)&&mo(r)&&e<=t&&t<r}function Ai(t,e,r,i){if(!vc(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function dw(t){let e;for(e=0;t>mc;t>>=wa,e+=1);return e}const zs=t=>(wa<<BigInt(t))-wa,bo=t=>new Uint8Array(t),Tl=t=>Uint8Array.from(t);function pw(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");let i=bo(t),n=bo(t),s=0;const o=()=>{i.fill(1),n.fill(0),s=0},a=(...h)=>r(n,i,...h),c=(h=bo(0))=>{n=a(Tl([0]),h),i=a(),h.length!==0&&(n=a(Tl([1]),h),i=a())},l=()=>{if(s++>=1e3)throw new Error("drbg: tried 1000 values");let h=0;const f=[];for(;h<e;){i=a();const d=i.slice();f.push(d),h+=i.length}return bs(...f)};return(h,f)=>{o(),c(h);let d;for(;!(d=f(l()));)c();return o(),d}}const gw={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"||On(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 Vs(t,e,r={}){const i=(n,s,o)=>{const a=gw[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))i(n,s,!1);for(const[n,s]of Object.entries(r))i(n,s,!0);return t}function Rl(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}function yw(t,e){if(kl(t)>e)throw new Uw({givenSize:kl(t),maxSize:e})}const Zt={zero:48,nine:57,A:65,F:70,a:97,f:102};function Fl(t){if(t>=Zt.zero&&t<=Zt.nine)return t-Zt.zero;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 ww(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;if(t.length>i)throw new kw({size:t.length,targetSize:i,type:"Bytes"});const n=new Uint8Array(i);for(let s=0;s<i;s++){const o=r==="right";n[o?s:i-s-1]=t[o?s:t.length-s-1]}return n}function ed(t,e){if(Nr(t)>e)throw new Ow({givenSize:Nr(t),maxSize:e})}function mw(t,e){if(typeof e=="number"&&e>0&&e>Nr(t)-1)throw new id({offset:e,position:"start",size:Nr(t)})}function bw(t,e,r){if(typeof e=="number"&&typeof r=="number"&&Nr(t)!==r-e)throw new id({offset:r,position:"end",size:Nr(t)})}function td(t,e={}){const{dir:r,size:i=32}=e;if(i===0)return t;const n=t.replace("0x","");if(n.length>i*2)throw new Dw({size:Math.ceil(n.length/2),targetSize:i,type:"Hex"});return`0x${n[r==="right"?"padEnd":"padStart"](i*2,"0")}`}const vw="#__bigint";function Ec(t,e,r){return JSON.stringify(t,(i,n)=>typeof e=="function"?e(i,n):typeof n=="bigint"?n.toString()+vw:n,r)}const Ew=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function xw(t,e={}){const{strict:r=!1}=e;if(!t)throw new Nl(t);if(typeof t!="string")throw new Nl(t);if(r&&!/^0x[0-9a-fA-F]*$/.test(t))throw new Ul(t);if(!t.startsWith("0x"))throw new Ul(t)}function _w(...t){return`0x${t.reduce((e,r)=>e+r.replace("0x",""),"")}`}function xc(t){return t instanceof Uint8Array?vs(t):Array.isArray(t)?vs(new Uint8Array(t)):t}function vs(t,e={}){let r="";for(let n=0;n<t.length;n++)r+=Ew[t[n]];const i=`0x${r}`;return typeof e.size=="number"?(ed(i,e.size),rd(i,e.size)):i}function vo(t,e={}){const{signed:r,size:i}=e,n=BigInt(t);let s;i?r?s=(1n<<BigInt(i)*8n-1n)-1n:s=2n**(BigInt(i)*8n)-1n:typeof t=="number"&&(s=BigInt(Number.MAX_SAFE_INTEGER));const o=typeof s=="bigint"&&r?-s-1n:0;if(s&&n>s||n<o){const l=typeof t=="bigint"?"n":"";throw new $w({max:s?`${s}${l}`:void 0,min:`${o}${l}`,signed:r,size:i,value:`${t}${l}`})}const c=`0x${(r&&n<0?(1n<<BigInt(i*8))+BigInt(n):n).toString(16)}`;return i?Iw(c,i):c}function Iw(t,e){return td(t,{dir:"left",size:e})}function rd(t,e){return td(t,{dir:"right",size:e})}function nr(t,e,r,i={}){const{strict:n}=i;mw(t,e);const s=`0x${t.replace("0x","").slice((e??0)*2,(r??t.length)*2)}`;return n&&bw(s,e,r),s}function Nr(t){return Math.ceil((t.length-2)/2)}function Sw(t,e={}){const{strict:r=!1}=e;try{return xw(t,{strict:r}),!0}catch{return!1}}class $w extends de{constructor({max:e,min:r,signed:i,size:n,value:s}){super(`Number \`${s}\` is not in safe${n?` ${n*8}-bit`:""}${i?" signed":" unsigned"} integer range ${e?`(\`${r}\` to \`${e}\`)`:`(above \`${r}\`)`}`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.IntegerOutOfRangeError"})}}class Nl extends de{constructor(e){super(`Value \`${typeof e=="object"?Ec(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 Ul 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 Ow=class extends de{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeOverflowError"})}};class id extends de{constructor({offset:e,position:r,size:i}){super(`Slice ${r==="start"?"starting":"ending"} at offset \`${e}\` is out-of-bounds (size: \`${i}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SliceOffsetOutOfBoundsError"})}}let Dw=class extends de{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Hex.SizeExceedsPaddingSizeError"})}};const Aw=new TextEncoder;function Pw(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 Cw(t){return t instanceof Uint8Array?t:typeof t=="string"?Tw(t):Bw(t)}function Bw(t){return t instanceof Uint8Array?t:new Uint8Array(t)}function Tw(t,e={}){const{size:r}=e;let i=t;r&&(ed(t,r),i=rd(t,r));let n=i.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=Fl(n.charCodeAt(c++)),u=Fl(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 Rw(t,e={}){const{size:r}=e,i=Aw.encode(t);return typeof r=="number"?(yw(i,r),Fw(i,r)):i}function Fw(t,e){return ww(t,{dir:"right",size:e})}function kl(t){return t.length}function Nw(t){try{return Pw(t),!0}catch{return!1}}class Mn extends de{constructor(e){super(`Value \`${typeof e=="object"?Ec(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 Uw extends de{constructor({givenSize:e,maxSize:r}){super(`Size cannot exceed \`${r}\` bytes. Given size: \`${e}\` bytes.`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeOverflowError"})}}class kw extends de{constructor({size:e,targetSize:r,type:i}){super(`${i.charAt(0).toUpperCase()}${i.slice(1).toLowerCase()} size (\`${e}\`) exceeds padding size (\`${r}\`).`),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Bytes.SizeExceedsPaddingSizeError"})}}function nd(t,e={}){const{as:r=typeof t=="string"?"Hex":"Bytes"}=e,i=cw(Cw(t));return r==="Bytes"?i:vs(i)}class jw extends Map{constructor(e){super(),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSize=e}get(e){const r=super.get(e);return super.has(e)&&r!==void 0&&(this.delete(e),super.set(e,r)),r}set(e,r){if(super.set(e,r),this.maxSize&&this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}const Lw={checksum:new jw(8192)},Eo=Lw.checksum;function sd(t,e={}){const{compressed:r}=e,{prefix:i,x:n,y:s}=t;if(r===!1||typeof n=="bigint"&&typeof s=="bigint"){if(i!==4)throw new jl({prefix:i,cause:new Kw});return}if(r===!0||typeof n=="bigint"&&typeof s>"u"){if(i!==3&&i!==2)throw new jl({prefix:i,cause:new Hw});return}throw new Vw({publicKey:t})}function Mw(t){const e=(()=>{if(Sw(t))return od(t);if(Nw(t))return qw(t);const{prefix:r,x:i,y:n}=t;return typeof i=="bigint"&&typeof n=="bigint"?{prefix:r??4,x:i,y:n}:{prefix:r,x:i}})();return sd(e),e}function qw(t){return od(vs(t))}function od(t){if(t.length!==132&&t.length!==130&&t.length!==68)throw new Ww({publicKey:t});if(t.length===130){const i=BigInt(nr(t,0,32)),n=BigInt(nr(t,32,64));return{prefix:4,x:i,y:n}}if(t.length===132){const i=Number(nr(t,0,1)),n=BigInt(nr(t,1,33)),s=BigInt(nr(t,33,65));return{prefix:i,x:n,y:s}}const e=Number(nr(t,0,1)),r=BigInt(nr(t,1,33));return{prefix:e,x:r}}function zw(t,e={}){sd(t);const{prefix:r,x:i,y:n}=t,{includePrefix:s=!0}=e;return _w(s?vo(r,{size:1}):"0x",vo(i,{size:32}),typeof n=="bigint"?vo(n,{size:32}):"0x")}class Vw extends de{constructor({publicKey:e}){super(`Value \`${Ec(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 jl extends de{constructor({prefix:e,cause:r}){super(`Prefix "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidPrefixError"})}}class Hw 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 Kw 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 Ww=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 ${Nr(xc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"PublicKey.InvalidSerializedSizeError"})}};const Gw=/^0x[a-fA-F0-9]{40}$/;function ad(t,e={}){const{strict:r=!0}=e;if(!Gw.test(t))throw new Ll({address:t,cause:new Jw});if(r){if(t.toLowerCase()===t)return;if(cd(t)!==t)throw new Ll({address:t,cause:new Xw})}}function cd(t){if(Eo.has(t))return Eo.get(t);ad(t,{strict:!1});const e=t.substring(2).toLowerCase(),r=nd(Rw(e),{as:"Bytes"}),i=e.split("");for(let s=0;s<40;s+=2)r[s>>1]>>4>=8&&i[s]&&(i[s]=i[s].toUpperCase()),(r[s>>1]&15)>=8&&i[s+1]&&(i[s+1]=i[s+1].toUpperCase());const n=`0x${i.join("")}`;return Eo.set(t,n),n}function Yw(t,e={}){const{checksum:r=!1}=e;return ad(t),r?cd(t):t}function Zw(t,e={}){const r=nd(`0x${zw(t).slice(4)}`).substring(26);return Yw(`0x${r}`,e)}class Ll extends de{constructor({address:e,cause:r}){super(`Address "${e}" is invalid.`,{cause:r}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Address.InvalidAddressError"})}}class Jw 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 Xw 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 ld extends yc{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Fy(e);const i=qs(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(i.length>n?e.create().update(i).digest():i);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),Ni(s)}update(e){return Fi(this),this.iHash.update(e),this}digestInto(e){Fi(this),ni(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:i,finished: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=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ud=(t,e,r)=>new ld(t,e).update(r).digest();ud.create=(t,e)=>new ld(t,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const rt=BigInt(0),Ke=BigInt(1),Jr=BigInt(2),Qw=BigInt(3),hd=BigInt(4),fd=BigInt(5),dd=BigInt(8);function Qe(t,e){const r=t%e;return r>=rt?r:e+r}function pt(t,e,r){let i=t;for(;e-- >rt;)i*=i,i%=r;return i}function ma(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 r=Qe(t,e),i=e,n=rt,s=Ke;for(;r!==rt;){const a=i/r,c=i%r,l=n-s*a;i=r,r=c,n=s,s=l}if(i!==Ke)throw new Error("invert: does not exist");return Qe(n,e)}function pd(t,e){const r=(t.ORDER+Ke)/hd,i=t.pow(e,r);if(!t.eql(t.sqr(i),e))throw new Error("Cannot find square root");return i}function em(t,e){const r=(t.ORDER-fd)/dd,i=t.mul(e,Jr),n=t.pow(i,r),s=t.mul(e,n),o=t.mul(t.mul(s,Jr),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 tm(t){if(t<BigInt(3))throw new Error("sqrt is not defined for small field");let e=t-Ke,r=0;for(;e%Jr===rt;)e/=Jr,r++;let i=Jr;const n=_c(t);for(;Ml(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return pd;let s=n.pow(i,e);const o=(e+Ke)/Jr;return function(c,l){if(c.is0(l))return l;if(Ml(c,l)!==1)throw new Error("Cannot find square root");let u=r,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),I=c.pow(h,w);u=p,h=c.sqr(I),f=c.mul(f,h),d=c.mul(d,I)}return d}}function rm(t){return t%hd===Qw?pd:t%dd===fd?em:tm(t)}const im=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function nm(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=im.reduce((i,n)=>(i[n]="function",i),e);return Vs(t,r)}function sm(t,e,r){if(r<rt)throw new Error("invalid exponent, negatives unsupported");if(r===rt)return t.ONE;if(r===Ke)return e;let i=t.ONE,n=e;for(;r>rt;)r&Ke&&(i=t.mul(i,n)),n=t.sqr(n),r>>=Ke;return i}function gd(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),s),i}function Ml(t,e){const r=(t.ORDER-Ke)/Jr,i=t.pow(e,r),n=t.eql(i,t.ONE),s=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function yd(t,e){e!==void 0&&mn(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function _c(t,e,r=!1,i={}){if(t<=rt)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=yd(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:n,BYTES:s,MASK:zs(n),ZERO:rt,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 rt<=c&&c<t},is0:c=>c===rt,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)=>sm(a,c,l),div:(c,l)=>Qe(c*ma(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>ma(c,t),sqrt:i.sqrt||(c=>(o||(o=rm(t)),o(a,c))),toBytes:c=>r?Qf(c,s):Dn(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?Xf(c):ri(c)},invertBatch:c=>gd(a,c),cmov:(c,l,u)=>u?l:c});return Object.freeze(a)}function wd(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 md(t){const e=wd(t);return e+Math.ceil(e/2)}function om(t,e,r=!1){const i=t.length,n=wd(e),s=md(e);if(i<16||i<s||i>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+i);const o=r?Xf(t):ri(t),a=Qe(o,e-Ke)+Ke;return r?Qf(a,n):Dn(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ql=BigInt(0),ba=BigInt(1);function xo(t,e){const r=e.negate();return t?r:e}function bd(t,e){if(!Number.isSafeInteger(t)||t<=0||t>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+t)}function _o(t,e){bd(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),n=2**t,s=zs(t),o=BigInt(t);return{windows:r,windowSize:i,mask:s,maxNumber:n,shiftBy:o}}function zl(t,e,r){const{windowSize:i,mask:n,maxNumber:s,shiftBy:o}=r;let a=Number(t&n),c=t>>o;a>i&&(a-=s,c+=ba);const l=e*i,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 am(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function cm(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Io=new WeakMap,vd=new WeakMap;function So(t){return vd.get(t)||1}function lm(t,e){return{constTimeNegate:xo,hasPrecomputes(r){return So(r)!==1},unsafeLadder(r,i,n=t.ZERO){let s=r;for(;i>ql;)i&ba&&(n=n.add(s)),s=s.double(),i>>=ba;return n},precomputeWindow(r,i){const{windows:n,windowSize:s}=_o(i,e),o=[];let a=r,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(r,i,n){let s=t.ZERO,o=t.BASE;const a=_o(r,e);for(let c=0;c<a.windows;c++){const{nextN:l,offset:u,isZero:h,isNeg:f,isNegF:d,offsetF:p}=zl(n,c,a);n=l,h?o=o.add(xo(d,i[p])):s=s.add(xo(f,i[u]))}return{p:s,f:o}},wNAFUnsafe(r,i,n,s=t.ZERO){const o=_o(r,e);for(let a=0;a<o.windows&&n!==ql;a++){const{nextN:c,offset:l,isZero:u,isNeg:h}=zl(n,a,o);if(n=c,!u){const f=i[l];s=s.add(h?f.negate():f)}}return s},getPrecomputes(r,i,n){let s=Io.get(i);return s||(s=this.precomputeWindow(i,r),r!==1&&Io.set(i,n(s))),s},wNAFCached(r,i,n){const s=So(r);return this.wNAF(s,this.getPrecomputes(s,r,n),i)},wNAFCachedUnsafe(r,i,n,s){const o=So(r);return o===1?this.unsafeLadder(r,i,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,n),i,s)},setWindowSize(r,i){bd(i,e),vd.set(r,i),Io.delete(r)}}}function um(t,e,r,i){am(r,t),cm(i,e);const n=r.length,s=i.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=dw(BigInt(n));let c=1;a>12?c=a-3:a>4?c=a-2:a>0&&(c=2);const l=zs(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=i[g],I=Number(w>>BigInt(d)&l);u[I]=u[I].add(r[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 Ed(t){return nm(t.Fp),Vs(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...yd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Vl(t){t.lowS!==void 0&&bn("lowS",t.lowS),t.prehash!==void 0&&bn("prehash",t.prehash)}function hm(t){const e=Ed(t);Vs(e,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});const{endo:r,Fp:i,a:n}=e;if(r){if(!i.eql(n,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if(typeof r!="object"||typeof r.beta!="bigint"||typeof r.splitScalar!="function")throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze({...e})}class fm extends Error{constructor(e=""){super(e)}}const sr={Err:fm,_tlv:{encode:(t,e)=>{const{Err:r}=sr;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,n=Ln(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const s=i>127?Ln(n.length/2|128):"";return Ln(t)+s+n+e},decode(t,e){const{Err:r}=sr;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const n=e[i++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=sr;if(t<ar)throw new e("integer: negative integers are not allowed");let r=Ln(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=sr;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 ri(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=sr,n=mt("signature",t),{v:s,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,s),{v:l,l:u}=i.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=sr,i=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),s=i+n;return e.encode(48,s)}};function $o(t,e){return vn(Dn(t,e))}const ar=BigInt(0),De=BigInt(1);BigInt(2);const Oo=BigInt(3),dm=BigInt(4);function pm(t){const e=hm(t),{Fp:r}=e,i=_c(e.n,e.nBitLength),n=e.toBytes||((b,v,D)=>{const P=v.toAffine();return bs(Uint8Array.from([4]),r.toBytes(P.x),r.toBytes(P.y))}),s=e.fromBytes||(b=>{const v=b.subarray(1),D=r.fromBytes(v.subarray(0,r.BYTES)),P=r.fromBytes(v.subarray(r.BYTES,2*r.BYTES));return{x:D,y:P}});function o(b){const{a:v,b:D}=e,P=r.sqr(b),T=r.mul(P,b);return r.add(r.add(T,r.mul(b,v)),D)}function a(b,v){const D=r.sqr(v),P=o(b);return r.eql(D,P)}if(!a(e.Gx,e.Gy))throw new Error("bad curve params: generator point");const c=r.mul(r.pow(e.a,Oo),dm),l=r.mul(r.sqr(e.b),BigInt(27));if(r.is0(r.add(c,l)))throw new Error("bad curve params: a or b");function u(b){return vc(b,De,e.n)}function h(b){const{allowedPrivateKeyLengths:v,nByteLength:D,wrapPrivateKey:P,n:T}=e;if(v&&typeof b!="bigint"){if(On(b)&&(b=vn(b)),typeof b!="string"||!v.includes(b.length))throw new Error("invalid private key");b=b.padStart(D*2,"0")}let R;try{R=typeof b=="bigint"?b:ri(mt("private key",b,D))}catch{throw new Error("invalid private key, expected hex or "+D+" bytes, got "+typeof b)}return P&&(R=Qe(R,T)),Ai("private key",R,De,T),R}function f(b){if(!(b instanceof g))throw new Error("ProjectivePoint expected")}const d=Rl((b,v)=>{const{px:D,py:P,pz:T}=b;if(r.eql(T,r.ONE))return{x:D,y:P};const R=b.is0();v==null&&(v=R?r.ONE:r.inv(T));const A=r.mul(D,v),U=r.mul(P,v),j=r.mul(T,v);if(R)return{x:r.ZERO,y:r.ZERO};if(!r.eql(j,r.ONE))throw new Error("invZ was invalid");return{x:A,y:U}}),p=Rl(b=>{if(b.is0()){if(e.allowInfinityPoint&&!r.is0(b.py))return;throw new Error("bad point: ZERO")}const{x:v,y:D}=b.toAffine();if(!r.isValid(v)||!r.isValid(D))throw new Error("bad point: x or y not FE");if(!a(v,D))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,D,P){if(v==null||!r.isValid(v))throw new Error("x required");if(D==null||!r.isValid(D)||r.is0(D))throw new Error("y required");if(P==null||!r.isValid(P))throw new Error("z required");this.px=v,this.py=D,this.pz=P,Object.freeze(this)}static fromAffine(v){const{x:D,y:P}=v||{};if(!v||!r.isValid(D)||!r.isValid(P))throw new Error("invalid affine point");if(v instanceof g)throw new Error("projective point not allowed");const T=R=>r.eql(R,r.ZERO);return T(D)&&T(P)?g.ZERO:new g(D,P,r.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(v){const D=gd(r,v.map(P=>P.pz));return v.map((P,T)=>P.toAffine(D[T])).map(g.fromAffine)}static fromHex(v){const D=g.fromAffine(s(mt("pointHex",v)));return D.assertValidity(),D}static fromPrivateKey(v){return g.BASE.multiply(h(v))}static msm(v,D){return um(g,i,v,D)}_setWindowSize(v){C.setWindowSize(this,v)}assertValidity(){p(this)}hasEvenY(){const{y:v}=this.toAffine();if(r.isOdd)return!r.isOdd(v);throw new Error("Field doesn't support isOdd")}equals(v){f(v);const{px:D,py:P,pz:T}=this,{px:R,py:A,pz:U}=v,j=r.eql(r.mul(D,U),r.mul(R,T)),B=r.eql(r.mul(P,U),r.mul(A,T));return j&&B}negate(){return new g(this.px,r.neg(this.py),this.pz)}double(){const{a:v,b:D}=e,P=r.mul(D,Oo),{px:T,py:R,pz:A}=this;let U=r.ZERO,j=r.ZERO,B=r.ZERO,_=r.mul(T,T),O=r.mul(R,R),m=r.mul(A,A),y=r.mul(T,R);return y=r.add(y,y),B=r.mul(T,A),B=r.add(B,B),U=r.mul(v,B),j=r.mul(P,m),j=r.add(U,j),U=r.sub(O,j),j=r.add(O,j),j=r.mul(U,j),U=r.mul(y,U),B=r.mul(P,B),m=r.mul(v,m),y=r.sub(_,m),y=r.mul(v,y),y=r.add(y,B),B=r.add(_,_),_=r.add(B,_),_=r.add(_,m),_=r.mul(_,y),j=r.add(j,_),m=r.mul(R,A),m=r.add(m,m),_=r.mul(m,y),U=r.sub(U,_),B=r.mul(m,O),B=r.add(B,B),B=r.add(B,B),new g(U,j,B)}add(v){f(v);const{px:D,py:P,pz:T}=this,{px:R,py:A,pz:U}=v;let j=r.ZERO,B=r.ZERO,_=r.ZERO;const O=e.a,m=r.mul(e.b,Oo);let y=r.mul(D,R),x=r.mul(P,A),$=r.mul(T,U),E=r.add(D,P),S=r.add(R,A);E=r.mul(E,S),S=r.add(y,x),E=r.sub(E,S),S=r.add(D,T);let F=r.add(R,U);return S=r.mul(S,F),F=r.add(y,$),S=r.sub(S,F),F=r.add(P,T),j=r.add(A,U),F=r.mul(F,j),j=r.add(x,$),F=r.sub(F,j),_=r.mul(O,S),j=r.mul(m,$),_=r.add(j,_),j=r.sub(x,_),_=r.add(x,_),B=r.mul(j,_),x=r.add(y,y),x=r.add(x,y),$=r.mul(O,$),S=r.mul(m,S),x=r.add(x,$),$=r.sub(y,$),$=r.mul(O,$),S=r.add(S,$),y=r.mul(x,S),B=r.add(B,y),y=r.mul(F,S),j=r.mul(E,j),j=r.sub(j,y),y=r.mul(E,x),_=r.mul(F,_),_=r.add(_,y),new g(j,B,_)}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:D,n:P}=e;Ai("scalar",v,ar,P);const T=g.ZERO;if(v===ar)return T;if(this.is0()||v===De)return this;if(!D||C.hasPrecomputes(this))return C.wNAFCachedUnsafe(this,v,g.normalizeZ);let{k1neg:R,k1:A,k2neg:U,k2:j}=D.splitScalar(v),B=T,_=T,O=this;for(;A>ar||j>ar;)A&De&&(B=B.add(O)),j&De&&(_=_.add(O)),O=O.double(),A>>=De,j>>=De;return R&&(B=B.negate()),U&&(_=_.negate()),_=new g(r.mul(_.px,D.beta),_.py,_.pz),B.add(_)}multiply(v){const{endo:D,n:P}=e;Ai("scalar",v,De,P);let T,R;if(D){const{k1neg:A,k1:U,k2neg:j,k2:B}=D.splitScalar(v);let{p:_,f:O}=this.wNAF(U),{p:m,f:y}=this.wNAF(B);_=C.constTimeNegate(A,_),m=C.constTimeNegate(j,m),m=new g(r.mul(m.px,D.beta),m.py,m.pz),T=_.add(m),R=O.add(y)}else{const{p:A,f:U}=this.wNAF(v);T=A,R=U}return g.normalizeZ([T,R])[0]}multiplyAndAddUnsafe(v,D,P){const T=g.BASE,R=(U,j)=>j===ar||j===De||!U.equals(T)?U.multiplyUnsafe(j):U.multiply(j),A=R(this,D).add(R(v,P));return A.is0()?void 0:A}toAffine(v){return d(this,v)}isTorsionFree(){const{h:v,isTorsionFree:D}=e;if(v===De)return!0;if(D)return D(g,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){const{h:v,clearCofactor:D}=e;return v===De?this:D?D(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,r.ONE),g.ZERO=new g(r.ZERO,r.ONE,r.ZERO);const{endo:w,nBitLength:I}=e,C=lm(g,w?Math.ceil(I/2):I);return{CURVE:e,ProjectivePoint:g,normPrivateKeyToScalar:h,weierstrassEquation:o,isWithinCurveOrder:u}}function gm(t){const e=Ed(t);return Vs(e,{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze({lowS:!0,...e})}function ym(t){const e=gm(t),{Fp:r,n:i,nByteLength:n,nBitLength:s}=e,o=r.BYTES+1,a=2*r.BYTES+1;function c(m){return Qe(m,i)}function l(m){return ma(m,i)}const{ProjectivePoint:u,normPrivateKeyToScalar:h,weierstrassEquation:f,isWithinCurveOrder:d}=pm({...e,toBytes(m,y,x){const $=y.toAffine(),E=r.toBytes($.x),S=bs;return bn("isCompressed",x),x?S(Uint8Array.from([y.hasEvenY()?2:3]),E):S(Uint8Array.from([4]),E,r.toBytes($.y))},fromBytes(m){const y=m.length,x=m[0],$=m.subarray(1);if(y===o&&(x===2||x===3)){const E=ri($);if(!vc(E,De,r.ORDER))throw new Error("Point is not on curve");const S=f(E);let F;try{F=r.sqrt(S)}catch(z){const q=z instanceof Error?": "+z.message:"";throw new Error("Point is not on curve"+q)}const N=(F&De)===De;return(x&1)===1!==N&&(F=r.neg(F)),{x:E,y:F}}else if(y===a&&x===4){const E=r.fromBytes($.subarray(0,r.BYTES)),S=r.fromBytes($.subarray(r.BYTES,2*r.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=i>>De;return m>y}function g(m){return p(m)?c(-m):m}const w=(m,y,x)=>ri(m.slice(y,x));class I{constructor(y,x,$){Ai("r",y,De,i),Ai("s",x,De,i),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 I(w(y,0,x),w(y,x,2*x))}static fromDER(y){const{r:x,s:$}=sr.toSig(mt("DER",y));return new I(x,$)}assertValidity(){}addRecoveryBit(y){return new I(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>=r.ORDER)throw new Error("recovery id 2 or 3 invalid");const N=E&1?"03":"02",H=u.fromHex(N+$o(F,r.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 I(this.r,c(-this.s),this.recovery):this}toDERRawBytes(){return ms(this.toDERHex())}toDERHex(){return sr.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=md(e.n);return om(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,$=r.BYTES,E=$+1,S=2*$+1;if(!(e.allowedPrivateKeyLengths||n===E))return x===E||x===S}function D(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=ri(m),x=m.length*8-s;return x>0?y>>BigInt(x):y},T=e.bits2int_modN||function(m){return c(P(m))},R=zs(s);function A(m){return Ai("num < 2^"+s,m,ar,R),Dn(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),Vl(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(r.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(),Ie=c(ve.x);if(Ie===ar)return;const He=c(pe*c(G+Ie*z));if(He===ar)return;let Gt=(ve.x===Ie?0:2)|Number(ve.y&De),dr=He;return S&&p(He)&&(dr=g(He),Gt^=1),new I(Ie,dr,Gt)}return{seed:K,k2sig:X}}const j={lowS:e.lowS,prehash:!1},B={lowS:e.lowS,prehash:!1};function _(m,y,x=j){const{seed:$,k2sig:E}=U(m,y,x),S=e;return pw(S.hash.outputLen,S.nByteLength,S.hmac)($,E)}u.BASE._setWindowSize(8);function O(m,y,x,$=B){var Gt;const E=m;y=mt("msgHash",y),x=mt("publicKey",x);const{lowS:S,prehash:F,format:N}=$;if(Vl($),"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"||On(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 I(E.r,E.s)),H){try{N!=="compact"&&(q=I.fromDER(E))}catch(dr){if(!(dr instanceof sr.Err))throw dr}!q&&N!=="der"&&(q=I.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),Ie=(Gt=u.BASE.multiplyAndAddUnsafe(K,pe,ve))==null?void 0:Gt.toAffine();return Ie?c(Ie.x)===G:!1}return{CURVE:e,getPublicKey:b,getSharedSecret:D,sign:_,verify:O,ProjectivePoint:u,Signature:I,utils:C}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */function wm(t){return{hash:t,hmac:(e,...r)=>ud(t,e,My(...r)),randomBytes:qy}}function mm(t,e){const r=i=>ym({...t,...wm(i)});return{...r(e),create:r}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const xd=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hl=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),bm=BigInt(0),vm=BigInt(1),va=BigInt(2),Kl=(t,e)=>(t+e/va)/e;function Em(t){const e=xd,r=BigInt(3),i=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,r,e)*u%e,f=pt(h,r,e)*u%e,d=pt(f,va,e)*l%e,p=pt(d,n,e)*d%e,g=pt(p,s,e)*p%e,w=pt(g,a,e)*g%e,I=pt(w,c,e)*w%e,C=pt(I,a,e)*g%e,b=pt(C,r,e)*u%e,v=pt(b,o,e)*p%e,D=pt(v,i,e)*l%e,P=pt(D,va,e);if(!Ea.eql(Ea.sqr(P),t))throw new Error("Cannot find square root");return P}const Ea=_c(xd,void 0,void 0,{sqrt:Em}),xm=mm({a:bm,b:BigInt(7),Fp:Ea,n:Hl,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:t=>{const e=Hl,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),i=-vm*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),n=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),s=r,o=BigInt("0x100000000000000000000000000000000"),a=Kl(s*t,e),c=Kl(-i*t,e);let l=Qe(t-a*r-c*n,e),u=Qe(-a*i-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}}}},hw);function _m(t){if(t.length!==130&&t.length!==132)throw new Sm({signature:t});const e=BigInt(nr(t,0,32)),r=BigInt(nr(t,32,64)),i=(()=>{const n=+`0x${t.slice(130)}`;if(!Number.isNaN(n))try{return Im(n)}catch{throw new $m({value:n})}})();return typeof i>"u"?{r:e,s:r}:{r:e,s:r,yParity:i}}function Im(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 Om({value:t})}class Sm extends de{constructor({signature:e}){super(`Value \`${e}\` is an invalid signature size.`,{metaMessages:["Expected: 64 bytes or 65 bytes.",`Received ${Nr(xc(e))} bytes.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"Signature.InvalidSerializedSizeError"})}}class $m 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 Om 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"})}}/*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Dm(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function _d(t,e){return Array.isArray(e)?e.length===0?!0:t?e.every(r=>typeof r=="string"):e.every(r=>Number.isSafeInteger(r)):!1}function Es(t,e){if(typeof e!="string")throw new Error(`${t}: string expected`);return!0}function Ic(t){if(!Number.isSafeInteger(t))throw new Error(`invalid integer: ${t}`)}function xa(t){if(!Array.isArray(t))throw new Error("array expected")}function xs(t,e){if(!_d(!0,e))throw new Error(`${t}: array of strings expected`)}function Am(t,e){if(!_d(!1,e))throw new Error(`${t}: array of numbers expected`)}function Pm(...t){const e=s=>s,r=(s,o)=>a=>s(o(a)),i=t.map(s=>s.encode).reduceRight(r,e),n=t.map(s=>s.decode).reduce(r,e);return{encode:i,decode:n}}function Cm(t){const e=typeof t=="string"?t.split(""):t,r=e.length;xs("alphabet",e);const i=new Map(e.map((n,s)=>[n,s]));return{encode:n=>(xa(n),n.map(s=>{if(!Number.isSafeInteger(s)||s<0||s>=r)throw new Error(`alphabet.encode: digit index outside alphabet "${s}". Allowed: ${t}`);return e[s]})),decode:n=>(xa(n),n.map(s=>{Es("alphabet.decode",s);const o=i.get(s);if(o===void 0)throw new Error(`Unknown letter: "${s}". Allowed: ${t}`);return o}))}}function Bm(t=""){return Es("join",t),{encode:e=>(xs("join.decode",e),e.join(t)),decode:e=>(Es("join.decode",e),e.split(t))}}function Tm(t,e="="){return Ic(t),Es("padding",e),{encode(r){for(xs("padding.encode",r);r.length*t%8;)r.push(e);return r},decode(r){xs("padding.decode",r);let i=r.length;if(i*t%8)throw new Error("padding: invalid, string should have whole number of bytes");for(;i>0&&r[i-1]===e;i--)if((i-1)*t%8===0)throw new Error("padding: invalid, string has too much padding");return r.slice(0,i)}}}const Id=(t,e)=>e===0?t:Id(e,t%e),_s=(t,e)=>t+(e-Id(t,e)),Do=(()=>{let t=[];for(let e=0;e<40;e++)t.push(2**e);return t})();function Wl(t,e,r,i){if(xa(t),e<=0||e>32)throw new Error(`convertRadix2: wrong from=${e}`);if(r<=0||r>32)throw new Error(`convertRadix2: wrong to=${r}`);if(_s(e,r)>32)throw new Error(`convertRadix2: carry overflow from=${e} to=${r} carryBits=${_s(e,r)}`);let n=0,s=0;const o=Do[e],a=Do[r]-1,c=[];for(const l of t){if(Ic(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>=r;s-=r)c.push((n>>s-r&a)>>>0);const u=Do[s];if(u===void 0)throw new Error("invalid carry");n&=u-1}if(n=n<<r-s&a,!i&&s>=e)throw new Error("Excess padding");if(!i&&n>0)throw new Error(`Non-zero padding: ${n}`);return i&&s>0&&c.push(n>>>0),c}function Rm(t,e=!1){if(Ic(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:r=>{if(!Dm(r))throw new Error("radix2.encode input should be Uint8Array");return Wl(Array.from(r),8,t,!e)},decode:r=>(Am("radix2.decode",r),Uint8Array.from(Wl(r,t,8,e)))}}const Fm=Pm(Rm(5),Cm("ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"),Tm(5),Bm(""));function Nm(t){return Zw(Um(t))}function Um(t){const{payload:e,signature:r}=t,{r:i,s:n,yParity:s}=r,a=new xm.Signature(BigInt(i),BigInt(n)).addRecoveryBit(s).recoverPublicKey(xc(e).substring(2));return Mw(a)}function km(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 r=t.length,i=t.charAt(0),n=Math.log(r)/Math.log(256),s=Math.log(256)/Math.log(r);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%r>>>0,C=C/r>>>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 I=i.repeat(u);for(;w<p;++w)I+=t.charAt(g[w]);return I}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]===i;)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 D=d-1;(b!==0||v<f)&&D!==-1;D--,v++)b+=r*p[D]>>>0,p[D]=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 I=h;for(;g!==d;)w[I++]=p[g++];return w}function c(l){const u=a(l);if(u)return u;throw new Error("Non-base"+r+" character")}return{encode:o,decodeUnsafe:a,decode:c}}var jm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";const An=km(jm);function Lm(t){const e=t.length;let r=0,i=0;for(;i<e;){let n=t.charCodeAt(i++);if(n&4294967168)if(!(n&4294965248))r+=2;else{if(n>=55296&&n<=56319&&i<e){const s=t.charCodeAt(i);(s&64512)===56320&&(++i,n=((n&1023)<<10)+(s&1023)+65536)}n&4294901760?r+=4:r+=3}else{r++;continue}}return r}function Mm(t,e,r){const i=t.length;let n=r,s=0;for(;s<i;){let o=t.charCodeAt(s++);if(o&4294967168)if(!(o&4294965248))e[n++]=o>>6&31|192;else{if(o>=55296&&o<=56319&&s<i){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 qm=new TextEncoder,zm=50;function Vm(t,e,r){qm.encodeInto(t,e.subarray(r))}function Hm(t,e,r){t.length>zm?Vm(t,e,r):Mm(t,e,r)}const Km=4096;function Sd(t,e,r){let i=e;const n=i+r,s=[];let o="";for(;i<n;){const a=t[i++];if(!(a&128))s.push(a);else if((a&224)===192){const c=t[i++]&63;s.push((a&31)<<6|c)}else if((a&240)===224){const c=t[i++]&63,l=t[i++]&63;s.push((a&31)<<12|c<<6|l)}else if((a&248)===240){const c=t[i++]&63,l=t[i++]&63,u=t[i++]&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>=Km&&(o+=String.fromCharCode(...s),s.length=0)}return s.length>0&&(o+=String.fromCharCode(...s)),o}const Wm=new TextDecoder,Gm=200;function Ym(t,e,r){const i=t.subarray(e,e+r);return Wm.decode(i)}function Zm(t,e,r){return r>Gm?Ym(t,e,r):Sd(t,e,r)}class qn{constructor(e,r){this.type=e,this.data=r}}class ut extends Error{constructor(e){super(e);const r=Object.create(ut.prototype);Object.setPrototypeOf(this,r),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:ut.name})}}const Ki=4294967295;function Jm(t,e,r){const i=r/4294967296,n=r;t.setUint32(e,i),t.setUint32(e+4,n)}function $d(t,e,r){const i=Math.floor(r/4294967296),n=r;t.setUint32(e,i),t.setUint32(e+4,n)}function Od(t,e){const r=t.getInt32(e),i=t.getUint32(e+4);return r*4294967296+i}function Xm(t,e){const r=t.getUint32(e),i=t.getUint32(e+4);return r*4294967296+i}const Qm=-1,e1=4294967296-1,t1=17179869184-1;function r1({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=t1)if(e===0&&t<=e1){const r=new Uint8Array(4);return new DataView(r.buffer).setUint32(0,t),r}else{const r=t/4294967296,i=t&4294967295,n=new Uint8Array(8),s=new DataView(n.buffer);return s.setUint32(0,e<<2|r&3),s.setUint32(4,i),n}else{const r=new Uint8Array(12),i=new DataView(r.buffer);return i.setUint32(0,e),$d(i,4,t),r}}function i1(t){const e=t.getTime(),r=Math.floor(e/1e3),i=(e-r*1e3)*1e6,n=Math.floor(i/1e9);return{sec:r+n,nsec:i-n*1e9}}function n1(t){if(t instanceof Date){const e=i1(t);return r1(e)}else return null}function s1(t){const e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{const r=e.getUint32(0),i=e.getUint32(4),n=(r&3)*4294967296+i,s=r>>>2;return{sec:n,nsec:s}}case 12:{const r=Od(e,4),i=e.getUint32(0);return{sec:r,nsec:i}}default:throw new ut(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function o1(t){const e=s1(t);return new Date(e.sec*1e3+e.nsec/1e6)}const a1={type:Qm,encode:n1,decode:o1};class Is{constructor(){this.builtInEncoders=[],this.builtInDecoders=[],this.encoders=[],this.decoders=[],this.register(a1)}register({type:e,encode:r,decode:i}){if(e>=0)this.encoders[e]=r,this.decoders[e]=i;else{const n=-1-e;this.builtInEncoders[n]=r,this.builtInDecoders[n]=i}}tryToEncode(e,r){for(let i=0;i<this.builtInEncoders.length;i++){const n=this.builtInEncoders[i];if(n!=null){const s=n(e,r);if(s!=null){const o=-1-i;return new qn(o,s)}}}for(let i=0;i<this.encoders.length;i++){const n=this.encoders[i];if(n!=null){const s=n(e,r);if(s!=null){const o=i;return new qn(o,s)}}}return e instanceof qn?e:null}decode(e,r,i){const n=r<0?this.builtInDecoders[-1-r]:this.decoders[r];return n?n(e,r,i):new qn(r,e)}}Is.defaultCodec=new Is;function c1(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function _a(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):c1(t)?new Uint8Array(t):Uint8Array.from(t)}const l1=100,u1=2048;let h1=class Dd{constructor(e){this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Is.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)??l1,this.initialBufferSize=(e==null?void 0:e.initialBufferSize)??u1,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 Dd({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,r){if(r>this.maxDepth)throw new Error(`Too deep objects in depth ${r}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,r)}ensureBufferSizeToWrite(e){const r=this.pos+e;this.view.byteLength<r&&this.resizeBuffer(r*2)}resizeBuffer(e){const r=new ArrayBuffer(e),i=new Uint8Array(r),n=new DataView(r);i.set(this.bytes),this.view=n,this.bytes=i}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){const i=Lm(e);this.ensureBufferSizeToWrite(5+i),this.writeStringHeader(i),Hm(e,this.bytes,this.pos),this.pos+=i}encodeObject(e,r){const i=this.extensionCodec.tryToEncode(e,this.context);if(i!=null)this.encodeExtension(i);else if(Array.isArray(e))this.encodeArray(e,r);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,r);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){const r=e.byteLength;if(r<256)this.writeU8(196),this.writeU8(r);else if(r<65536)this.writeU8(197),this.writeU16(r);else if(r<4294967296)this.writeU8(198),this.writeU32(r);else throw new Error(`Too large binary: ${r}`);const i=_a(e);this.writeU8a(i)}encodeArray(e,r){const i=e.length;if(i<16)this.writeU8(144+i);else if(i<65536)this.writeU8(220),this.writeU16(i);else if(i<4294967296)this.writeU8(221),this.writeU32(i);else throw new Error(`Too large array: ${i}`);for(const n of e)this.doEncode(n,r+1)}countWithoutUndefined(e,r){let i=0;for(const n of r)e[n]!==void 0&&i++;return i}encodeMap(e,r){const i=Object.keys(e);this.sortKeys&&i.sort();const n=this.ignoreUndefined?this.countWithoutUndefined(e,i):i.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 i){const o=e[s];this.ignoreUndefined&&o===void 0||(this.encodeString(s),this.doEncode(o,r+1))}}encodeExtension(e){if(typeof e.data=="function"){const i=e.data(this.pos+6),n=i.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(i);return}const r=e.data.length;if(r===1)this.writeU8(212);else if(r===2)this.writeU8(213);else if(r===4)this.writeU8(214);else if(r===8)this.writeU8(215);else if(r===16)this.writeU8(216);else if(r<256)this.writeU8(199),this.writeU8(r);else if(r<65536)this.writeU8(200),this.writeU16(r);else if(r<4294967296)this.writeU8(201),this.writeU32(r);else throw new Error(`Too large extension object: ${r}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){const r=e.length;this.ensureBufferSizeToWrite(r),this.bytes.set(e,this.pos),this.pos+=r}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),Jm(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),$d(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 f1(t,e){return new h1(e).encodeSharedRef(t)}function Ao(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}const d1=16,p1=16;class g1{constructor(e=d1,r=p1){this.hit=0,this.miss=0,this.maxKeyLength=e,this.maxLengthPerKey=r,this.caches=[];for(let i=0;i<this.maxKeyLength;i++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,r,i){const n=this.caches[i-1];e:for(const s of n){const o=s.bytes;for(let a=0;a<i;a++)if(o[a]!==e[r+a])continue e;return s.str}return null}store(e,r){const i=this.caches[e.length-1],n={bytes:e,str:r};i.length>=this.maxLengthPerKey?i[Math.random()*i.length|0]=n:i.push(n)}decode(e,r,i){const n=this.find(e,r,i);if(n!=null)return this.hit++,n;this.miss++;const s=Sd(e,r,i),o=Uint8Array.prototype.slice.call(e,r,r+i);return this.store(o,s),s}}const Ia="array",hn="map_key",Ad="map_value",y1=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 w1{constructor(){this.stack=[],this.stackHeadPosition=-1}get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){const r=this.getUninitializedStateFromPool();r.type=Ia,r.position=0,r.size=e,r.array=new Array(e)}pushMapState(e){const r=this.getUninitializedStateFromPool();r.type=hn,r.readCount=0,r.size=e,r.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){const e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===Ia){const i=e;i.size=0,i.array=void 0,i.position=0,i.type=void 0}if(e.type===hn||e.type===Ad){const i=e;i.size=0,i.map=void 0,i.readCount=0,i.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}}const Wi=-1,Sc=new DataView(new ArrayBuffer(0)),m1=new Uint8Array(Sc.buffer);try{Sc.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 Gl=new RangeError("Insufficient data"),b1=new g1;let v1=class Pd{constructor(e){this.totalPos=0,this.pos=0,this.view=Sc,this.bytes=m1,this.headByte=Wi,this.stack=new w1,this.entered=!1,this.extensionCodec=(e==null?void 0:e.extensionCodec)??Is.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)??Ki,this.maxBinLength=(e==null?void 0:e.maxBinLength)??Ki,this.maxArrayLength=(e==null?void 0:e.maxArrayLength)??Ki,this.maxMapLength=(e==null?void 0:e.maxMapLength)??Ki,this.maxExtLength=(e==null?void 0:e.maxExtLength)??Ki,this.keyDecoder=(e==null?void 0:e.keyDecoder)!==void 0?e.keyDecoder:b1,this.mapKeyConverter=(e==null?void 0:e.mapKeyConverter)??y1}clone(){return new Pd({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Wi,this.stack.reset()}setBuffer(e){const r=_a(e);this.bytes=r,this.view=new DataView(r.buffer,r.byteOffset,r.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Wi&&!this.hasRemaining(1))this.setBuffer(e);else{const r=this.bytes.subarray(this.pos),i=_a(e),n=new Uint8Array(r.length+i.length);n.set(r),n.set(i,r.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){const{view:r,pos:i}=this;return new RangeError(`Extra ${r.byteLength-i} of ${r.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);const r=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return r}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let r=!1,i;for await(const a of e){if(r)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(a);try{i=this.doDecodeSync(),r=!0}catch(c){if(!(c instanceof RangeError))throw c}this.totalPos+=this.pos}if(r){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return i}const{headByte:n,pos:s,totalPos:o}=this;throw new RangeError(`Insufficient data in parsing ${Ao(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,r){if(this.entered){yield*this.clone().decodeMultiAsync(e,r);return}try{this.entered=!0;let i=r,n=-1;for await(const s of e){if(r&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(s),i&&(n=this.readArraySize(),i=!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 r;if(e>=224)r=e-256;else if(e<192)if(e<128)r=e;else if(e<144){const n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e<160){const n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else{const n=e-160;r=this.decodeString(n,0)}else if(e===192)r=null;else if(e===194)r=!1;else if(e===195)r=!0;else if(e===202)r=this.readF32();else if(e===203)r=this.readF64();else if(e===204)r=this.readU8();else if(e===205)r=this.readU16();else if(e===206)r=this.readU32();else if(e===207)this.useBigInt64?r=this.readU64AsBigInt():r=this.readU64();else if(e===208)r=this.readI8();else if(e===209)r=this.readI16();else if(e===210)r=this.readI32();else if(e===211)this.useBigInt64?r=this.readI64AsBigInt():r=this.readI64();else if(e===217){const n=this.lookU8();r=this.decodeString(n,1)}else if(e===218){const n=this.lookU16();r=this.decodeString(n,2)}else if(e===219){const n=this.lookU32();r=this.decodeString(n,4)}else if(e===220){const n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===221){const n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else r=[]}else if(e===222){const n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===223){const n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else r={}}else if(e===196){const n=this.lookU8();r=this.decodeBinary(n,1)}else if(e===197){const n=this.lookU16();r=this.decodeBinary(n,2)}else if(e===198){const n=this.lookU32();r=this.decodeBinary(n,4)}else if(e===212)r=this.decodeExtension(1,0);else if(e===213)r=this.decodeExtension(2,0);else if(e===214)r=this.decodeExtension(4,0);else if(e===215)r=this.decodeExtension(8,0);else if(e===216)r=this.decodeExtension(16,0);else if(e===199){const n=this.lookU8();r=this.decodeExtension(n,1)}else if(e===200){const n=this.lookU16();r=this.decodeExtension(n,2)}else if(e===201){const n=this.lookU32();r=this.decodeExtension(n,4)}else throw new ut(`Unrecognized type byte: ${Ao(e)}`);this.complete();const i=this.stack;for(;i.length>0;){const n=i.top();if(n.type===Ia)if(n.array[n.position]=r,n.position++,n.position===n.size)r=n.array,i.release(n);else continue e;else if(n.type===hn){if(r==="__proto__")throw new ut("The key __proto__ is not allowed");n.key=this.mapKeyConverter(r),n.type=Ad;continue e}else if(n.map[n.key]=r,n.readCount++,n.readCount===n.size)r=n.map,i.release(n);else{n.key=null,n.type=hn;continue e}}return r}}readHeadByte(){return this.headByte===Wi&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Wi}readArraySize(){const e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new ut(`Unrecognized array type byte: ${Ao(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,r){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,r):this.decodeBinary(e,r)}decodeUtf8String(e,r){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+r+e)throw Gl;const i=this.pos+r;let n;return this.stateIsMapKey()&&((s=this.keyDecoder)!=null&&s.canBeCached(e))?n=this.keyDecoder.decode(this.bytes,i,e):n=Zm(this.bytes,i,e),this.pos+=r+e,n}stateIsMapKey(){return this.stack.length>0?this.stack.top().type===hn:!1}decodeBinary(e,r){if(e>this.maxBinLength)throw new ut(`Max length exceeded: bin length (${e}) > maxBinLength (${this.maxBinLength})`);if(!this.hasRemaining(e+r))throw Gl;const i=this.pos+r,n=this.bytes.subarray(i,i+e);return this.pos+=r+e,n}decodeExtension(e,r){if(e>this.maxExtLength)throw new ut(`Max length exceeded: ext length (${e}) > maxExtLength (${this.maxExtLength})`);const i=this.view.getInt8(this.pos+r),n=this.decodeBinary(e,r+1);return this.extensionCodec.decode(n,i,this.context)}lookU8(){return this.view.getUint8(this.pos)}lookU16(){return this.view.getUint16(this.pos)}lookU32(){return this.view.getUint32(this.pos)}readU8(){const e=this.view.getUint8(this.pos);return this.pos++,e}readI8(){const e=this.view.getInt8(this.pos);return this.pos++,e}readU16(){const e=this.view.getUint16(this.pos);return this.pos+=2,e}readI16(){const e=this.view.getInt16(this.pos);return this.pos+=2,e}readU32(){const e=this.view.getUint32(this.pos);return this.pos+=4,e}readI32(){const e=this.view.getInt32(this.pos);return this.pos+=4,e}readU64(){const e=Xm(this.view,this.pos);return this.pos+=8,e}readI64(){const e=Od(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 E1(t,e){return new v1(e).decode(t)}const x1=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r),_1=t=>{const e=/([\[:])?(\d{17,}|(?:[9](?:[1-9]07199254740991|0[1-9]7199254740991|00[8-9]199254740991|007[2-9]99254740991|007199[3-9]54740991|0071992[6-9]4740991|00719925[5-9]740991|007199254[8-9]40991|0071992547[5-9]0991|00719925474[1-9]991|00719925474099[2-9])))([,\}\]])/g,r=t.replace(e,'$1"$2n"$3');return JSON.parse(r,(i,n)=>typeof n=="string"&&n.match(/^\d+n$/)?BigInt(n.substring(0,n.length-1)):n)};function si(t){if(typeof t!="string")throw new Error(`Cannot safe json parse value of type ${typeof t}`);try{return _1(t)}catch{return t}}function oi(t){return typeof t=="string"?t:x1(t)||""}function I1(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Cd(t,...e){if(!I1(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 Yl(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 S1(t,e){Cd(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}const mi=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 $1(t){if(typeof t!="string")throw new Error("utf8ToBytes expected string, got "+typeof t);return new Uint8Array(new TextEncoder().encode(t))}function Bd(t){return typeof t=="string"&&(t=$1(t)),Cd(t),t}let O1=class{clone(){return this._cloneInto()}};function D1(t){const e=i=>t().update(Bd(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function Td(t=32){if(mi&&typeof mi.getRandomValues=="function")return mi.getRandomValues(new Uint8Array(t));if(mi&&typeof mi.randomBytes=="function")return mi.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}function A1(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}let P1=class extends O1{constructor(e,r,i,n){super(),this.blockLen=e,this.outputLen=r,this.padOffset=i,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){Yl(this);const{view:r,buffer:i,blockLen:n}=this;e=Bd(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}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Yl(this),S1(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,this.buffer.subarray(o).fill(0),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;A1(i,n-8,BigInt(this.length*8),s),this.process(i,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:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.length=n,e.pos=a,e.finished=s,e.destroyed=o,n%r&&e.buffer.set(i),e}};const zn=BigInt(2**32-1),Sa=BigInt(32);function Rd(t,e=!1){return e?{h:Number(t&zn),l:Number(t>>Sa&zn)}:{h:Number(t>>Sa&zn)|0,l:Number(t&zn)|0}}function C1(t,e=!1){let r=new Uint32Array(t.length),i=new Uint32Array(t.length);for(let n=0;n<t.length;n++){const{h:s,l:o}=Rd(t[n],e);[r[n],i[n]]=[s,o]}return[r,i]}const B1=(t,e)=>BigInt(t>>>0)<<Sa|BigInt(e>>>0),T1=(t,e,r)=>t>>>r,R1=(t,e,r)=>t<<32-r|e>>>r,F1=(t,e,r)=>t>>>r|e<<32-r,N1=(t,e,r)=>t<<32-r|e>>>r,U1=(t,e,r)=>t<<64-r|e>>>r-32,k1=(t,e,r)=>t>>>r-32|e<<64-r,j1=(t,e)=>e,L1=(t,e)=>t,M1=(t,e,r)=>t<<r|e>>>32-r,q1=(t,e,r)=>e<<r|t>>>32-r,z1=(t,e,r)=>e<<r-32|t>>>64-r,V1=(t,e,r)=>t<<r-32|e>>>64-r;function H1(t,e,r,i){const n=(e>>>0)+(i>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}const K1=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),W1=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,G1=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),Y1=(t,e,r,i,n)=>e+r+i+n+(t/2**32|0)|0,Z1=(t,e,r,i,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(n>>>0),J1=(t,e,r,i,n,s)=>e+r+i+n+s+(t/2**32|0)|0,J={fromBig:Rd,split:C1,toBig:B1,shrSH:T1,shrSL:R1,rotrSH:F1,rotrSL:N1,rotrBH:U1,rotrBL:k1,rotr32H:j1,rotr32L:L1,rotlSH:M1,rotlSL:q1,rotlBH:z1,rotlBL:V1,add:H1,add3L:K1,add3H:W1,add4L:G1,add4H:Y1,add5H:J1,add5L:Z1},[X1,Q1]=(()=>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))))(),yr=new Uint32Array(80),wr=new Uint32Array(80);let eb=class extends P1{constructor(){super(128,64,16,!1),this.Ah=1779033703,this.Al=-205731576,this.Bh=-1150833019,this.Bl=-2067093701,this.Ch=1013904242,this.Cl=-23791573,this.Dh=-1521486534,this.Dl=1595750129,this.Eh=1359893119,this.El=-1377402159,this.Fh=-1694144372,this.Fl=725511199,this.Gh=528734635,this.Gl=-79577749,this.Hh=1541459225,this.Hl=327033209}get(){const{Ah:e,Al:r,Bh:i,Bl: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,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|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,r){for(let b=0;b<16;b++,r+=4)yr[b]=e.getUint32(r),wr[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const v=yr[b-15]|0,D=wr[b-15]|0,P=J.rotrSH(v,D,1)^J.rotrSH(v,D,8)^J.shrSH(v,D,7),T=J.rotrSL(v,D,1)^J.rotrSL(v,D,8)^J.shrSL(v,D,7),R=yr[b-2]|0,A=wr[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,wr[b-7],wr[b-16]),_=J.add4H(B,P,U,yr[b-7],yr[b-16]);yr[b]=_|0,wr[b]=B|0}let{Ah:i,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:I,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),D=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,D,T,Q1[b],wr[b]),A=J.add5H(R,I,v,P,X1[b],yr[b]),U=R|0,j=J.rotrSH(i,n,28)^J.rotrBH(i,n,34)^J.rotrBH(i,n,39),B=J.rotrSL(i,n,28)^J.rotrBL(i,n,34)^J.rotrBL(i,n,39),_=i&s^i&a^s&a,O=n&o^n&c^o&c;I=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=i|0,o=n|0;const m=J.add3L(U,B,O);i=J.add3H(m,A,j,_),n=m|0}({h:i,l:n}=J.add(this.Ah|0,this.Al|0,i|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:I,l:C}=J.add(this.Hh|0,this.Hl|0,I|0,C|0),this.set(i,n,s,o,a,c,l,u,h,f,d,p,g,w,I,C)}roundClean(){yr.fill(0),wr.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 tb=D1(()=>new eb);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const $c=BigInt(0),Fd=BigInt(1),rb=BigInt(2);function Oc(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Dc(t){if(!Oc(t))throw new Error("Uint8Array expected")}function Co(t,e){if(typeof e!="boolean")throw new Error(t+" boolean expected, got "+e)}const ib=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ac(t){Dc(t);let e="";for(let r=0;r<t.length;r++)e+=ib[t[r]];return e}function Nd(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?$c:BigInt("0x"+t)}const Jt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Zl(t){if(t>=Jt._0&&t<=Jt._9)return t-Jt._0;if(t>=Jt.A&&t<=Jt.F)return t-(Jt.A-10);if(t>=Jt.a&&t<=Jt.f)return t-(Jt.a-10)}function Ud(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Zl(t.charCodeAt(s)),a=Zl(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)}i[n]=o*16+a}return i}function nb(t){return Nd(Ac(t))}function us(t){return Dc(t),Nd(Ac(Uint8Array.from(t).reverse()))}function kd(t,e){return Ud(t.toString(16).padStart(e*2,"0"))}function $a(t,e){return kd(t,e).reverse()}function Xt(t,e,r){let i;if(typeof e=="string")try{i=Ud(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Oc(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}function Jl(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];Dc(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}const Bo=t=>typeof t=="bigint"&&$c<=t;function sb(t,e,r){return Bo(t)&&Bo(e)&&Bo(r)&&e<=t&&t<r}function Gi(t,e,r,i){if(!sb(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function ob(t){let e;for(e=0;t>$c;t>>=Fd,e+=1);return e}const ab=t=>(rb<<BigInt(t-1))-Fd,cb={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"||Oc(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 Pc(t,e,r={}){const i=(n,s,o)=>{const a=cb[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))i(n,s,!1);for(const[n,s]of Object.entries(r))i(n,s,!0);return t}function Xl(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}const Ae=BigInt(0),ge=BigInt(1),Gr=BigInt(2),lb=BigInt(3),Oa=BigInt(4),Ql=BigInt(5),eu=BigInt(8);function xe(t,e){const r=t%e;return r>=Ae?r:e+r}function ub(t,e,r){if(e<Ae)throw new Error("invalid exponent, negatives unsupported");if(r<=Ae)throw new Error("invalid modulus");if(r===ge)return Ae;let i=ge;for(;e>Ae;)e&ge&&(i=i*t%r),t=t*t%r,e>>=ge;return i}function Ft(t,e,r){let i=t;for(;e-- >Ae;)i*=i,i%=r;return i}function tu(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 r=xe(t,e),i=e,n=Ae,s=ge;for(;r!==Ae;){const o=i/r,a=i%r,c=n-s*o;i=r,r=a,n=s,s=c}if(i!==ge)throw new Error("invert: does not exist");return xe(n,e)}function hb(t){const e=(t-ge)/Gr;let r,i,n;for(r=t-ge,i=0;r%Gr===Ae;r/=Gr,i++);for(n=Gr;n<t&&ub(n,e,t)!==t-ge;n++)if(n>1e3)throw new Error("Cannot find square root: likely non-prime P");if(i===1){const o=(t+ge)/Oa;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=(r+ge)/Gr;return function(o,a){if(o.pow(a,e)===o.neg(o.ONE))throw new Error("Cannot find square root");let c=i,l=o.pow(o.mul(o.ONE,n),r),u=o.pow(a,s),h=o.pow(a,r);for(;!o.eql(h,o.ONE);){if(o.eql(h,o.ZERO))return o.ZERO;let f=1;for(let 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 fb(t){if(t%Oa===lb){const e=(t+ge)/Oa;return function(r,i){const n=r.pow(i,e);if(!r.eql(r.sqr(n),i))throw new Error("Cannot find square root");return n}}if(t%eu===Ql){const e=(t-Ql)/eu;return function(r,i){const n=r.mul(i,Gr),s=r.pow(n,e),o=r.mul(i,s),a=r.mul(r.mul(o,Gr),s),c=r.mul(o,r.sub(a,r.ONE));if(!r.eql(r.sqr(c),i))throw new Error("Cannot find square root");return c}}return hb(t)}const db=(t,e)=>(xe(t,e)&ge)===ge,pb=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function gb(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"},r=pb.reduce((i,n)=>(i[n]="function",i),e);return Pc(t,r)}function yb(t,e,r){if(r<Ae)throw new Error("invalid exponent, negatives unsupported");if(r===Ae)return t.ONE;if(r===ge)return e;let i=t.ONE,n=e;for(;r>Ae;)r&ge&&(i=t.mul(i,n)),n=t.sqr(n),r>>=ge;return i}function wb(t,e){const r=new Array(e.length),i=e.reduce((s,o,a)=>t.is0(o)?s:(r[a]=s,t.mul(s,o)),t.ONE),n=t.inv(i);return e.reduceRight((s,o,a)=>t.is0(o)?s:(r[a]=t.mul(s,r[a]),t.mul(s,o)),n),r}function jd(t,e){const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function Ld(t,e,r=!1,i={}){if(t<=Ae)throw new Error("invalid field: expected ORDER > 0, got "+t);const{nBitLength:n,nByteLength:s}=jd(t,e);if(s>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let o;const a=Object.freeze({ORDER:t,isLE:r,BITS:n,BYTES:s,MASK:ab(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)=>yb(a,c,l),div:(c,l)=>xe(c*tu(l,t),t),sqrN:c=>c*c,addN:(c,l)=>c+l,subN:(c,l)=>c-l,mulN:(c,l)=>c*l,inv:c=>tu(c,t),sqrt:i.sqrt||(c=>(o||(o=fb(t)),o(a,c))),invertBatch:c=>wb(a,c),cmov:(c,l,u)=>u?l:c,toBytes:c=>r?$a(c,s):kd(c,s),fromBytes:c=>{if(c.length!==s)throw new Error("Field.fromBytes: expected "+s+" bytes, got "+c.length);return r?us(c):nb(c)}});return Object.freeze(a)}const ru=BigInt(0),Vn=BigInt(1);function To(t,e){const r=e.negate();return t?r:e}function Md(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){Md(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1);return{windows:r,windowSize:i}}function mb(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function bb(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Fo=new WeakMap,qd=new WeakMap;function No(t){return qd.get(t)||1}function vb(t,e){return{constTimeNegate:To,hasPrecomputes(r){return No(r)!==1},unsafeLadder(r,i,n=t.ZERO){let s=r;for(;i>ru;)i&Vn&&(n=n.add(s)),s=s.double(),i>>=Vn;return n},precomputeWindow(r,i){const{windows:n,windowSize:s}=Ro(i,e),o=[];let a=r,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(r,i,n){const{windows:s,windowSize:o}=Ro(r,e);let a=t.ZERO,c=t.BASE;const l=BigInt(2**r-1),u=2**r,h=BigInt(r);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,I=f%2!==0,C=p<0;p===0?c=c.add(To(I,i[g])):a=a.add(To(C,i[w]))}return{p:a,f:c}},wNAFUnsafe(r,i,n,s=t.ZERO){const{windows:o,windowSize:a}=Ro(r,e),c=BigInt(2**r-1),l=2**r,u=BigInt(r);for(let h=0;h<o;h++){const f=h*a;if(n===ru)break;let d=Number(n&c);if(n>>=u,d>a&&(d-=l,n+=Vn),d===0)continue;let p=i[f+Math.abs(d)-1];d<0&&(p=p.negate()),s=s.add(p)}return s},getPrecomputes(r,i,n){let s=Fo.get(i);return s||(s=this.precomputeWindow(i,r),r!==1&&Fo.set(i,n(s))),s},wNAFCached(r,i,n){const s=No(r);return this.wNAF(s,this.getPrecomputes(s,r,n),i)},wNAFCachedUnsafe(r,i,n,s){const o=No(r);return o===1?this.unsafeLadder(r,i,s):this.wNAFUnsafe(o,this.getPrecomputes(o,r,n),i,s)},setWindowSize(r,i){Md(i,e),qd.set(r,i),Fo.delete(r)}}}function Eb(t,e,r,i){if(mb(r,t),bb(i,e),r.length!==i.length)throw new Error("arrays of points and scalars must have equal length");const n=t.ZERO,s=ob(BigInt(r.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<i.length;d++){const p=i[d],g=Number(p>>BigInt(h)&BigInt(a));c[g]=c[g].add(r[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 xb(t){return gb(t.Fp),Pc(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze({...jd(t.n,t.nBitLength),...t,p:t.Fp.ORDER})}const $t=BigInt(0),Ye=BigInt(1),Hn=BigInt(2),_b=BigInt(8),Ib={zip215:!0};function Sb(t){const e=xb(t);return Pc(t,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze({...e})}function $b(t){const e=Sb(t),{Fp:r,n:i,prehash:n,hash:s,randomBytes:o,nByteLength:a,h:c}=e,l=Hn<<BigInt(a*8)-Ye,u=r.create,h=Ld(e.n,e.nBitLength),f=e.uvRatio||((m,y)=>{try{return{isValid:!0,value:r.sqrt(m*r.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){Gi("coordinate "+m,y,$t,l)}function w(m){if(!(m instanceof b))throw new Error("ExtendedPoint expected")}const I=Xl((m,y)=>{const{ex:x,ey:$,ez:E}=m,S=m.is0();y==null&&(y=S?_b:r.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=Xl(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=r.invertBatch(y.map($=>$.ez));return y.map(($,E)=>$.toAffine(x[E])).map(b.fromAffine)}static msm(y,x){return Eb(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 ol=u((S-E)*(z+H)),al=u((S+E)*(z-H)),ho=u(al-ol);if(ho===$t)return this.double();const cl=u(F*Hn*K),ll=u(N*Hn*q),ul=ll+cl,hl=al+ol,fl=ll-cl,A0=u(ul*ho),P0=u(hl*fl),C0=u(ul*fl),B0=u(ho*hl);return new b(A0,P0,B0,C0)}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,Ie=Q+W,He=u(X-x*G),Gt=u(pe*ve),dr=u(Ie*He),O0=u(pe*He),D0=u(ve*Ie);return new b(Gt,dr,D0,O0)}subtract(y){return this.add(y.negate())}wNAF(y){return P.wNAFCached(this,y,b.normalizeZ)}multiply(y){const x=y;Gi("scalar",x,Ye,i);const{p:$,f:E}=this.wNAF(x);return b.normalizeZ([$,E])[0]}multiplyUnsafe(y,x=b.ZERO){const $=y;return Gi("scalar",$,$t,i),$===$t?D:this.is0()||$===Ye?this:P.wNAFCachedUnsafe(this,$,b.normalizeZ,x)}isSmallOrder(){return this.multiplyUnsafe(c).is0()}isTorsionFree(){return P.unsafeLadder(this,i).is0()}toAffine(y){return I(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=r.BYTES;y=Xt("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:r.ORDER;Gi("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(),$=$a(x,r.BYTES);return $[$.length-1]|=y&Ye?128:0,$}toHex(){return Ac(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:D}=b,P=vb(b,a*8);function T(m){return xe(m,i)}function R(m){return T(us(m))}function A(m){const y=r.BYTES;m=Xt("private key",m,y);const x=Xt("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=Jl(...y);return R(s(p(x,Xt("context",m),!!n)))}function B(m,y,x={}){m=Xt("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);Gi("signature.s",z,$t,i);const q=Jl(N,$a(z,r.BYTES));return Xt("result",q,r.BYTES*2)}const _=Ib;function O(m,y,x,$=_){const{context:E,zip215:S}=$,F=r.BYTES;m=Xt("signature",m,2*F),y=Xt("message",y),x=Xt("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:O,ExtendedPoint:b,utils:{getExtendedPublicKey:A,randomPrivateKey:()=>o(r.BYTES),precompute(m=8,y=b.BASE){return y._setWindowSize(m),y.multiply(BigInt(3)),y}}}}BigInt(0),BigInt(1);const Cc=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),iu=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);const Ob=BigInt(1),nu=BigInt(2);BigInt(3);const Db=BigInt(5),Ab=BigInt(8);function Pb(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),s=Cc,o=t*t%s*t%s,a=Ft(o,nu,s)*o%s,c=Ft(a,Ob,s)*t%s,l=Ft(c,Db,s)*c%s,u=Ft(l,e,s)*l%s,h=Ft(u,r,s)*u%s,f=Ft(h,i,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,nu,s)*t%s,b2:o}}function Cb(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}function Bb(t,e){const r=Cc,i=xe(e*e*e,r),n=xe(i*i*e,r),s=Pb(t*n).pow_p_5_8;let o=xe(t*i*s,r);const a=xe(e*o*o,r),c=o,l=xe(o*iu,r),u=a===t,h=a===xe(-t,r),f=a===xe(-t*iu,r);return u&&(o=c),(h||f)&&(o=l),db(o,r)&&(o=xe(-o,r)),{isValid:u||h,value:o}}const Tb=(()=>Ld(Cc,void 0,!0))(),Rb=(()=>({a:BigInt(-1),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:Tb,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:Ab,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:tb,randomBytes:Td,adjustScalarBytes:Cb,uvRatio:Bb}))(),zd=(()=>$b(Rb))(),Fb="EdDSA",Nb="JWT",Ss=".",Hs="base64url",Vd="utf8",Hd="utf8",Ub=":",kb="did",jb="key",su="base58btc",Lb="z",Mb="K36",qb=32;function Bc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function Kd(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Bc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function Wd(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const r=Kd(e);let i=0;for(const n of t)r.set(n,i),i+=n.length;return Bc(r)}function zb(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[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,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*u+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}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,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;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 Vb=zb,Hb=Vb;const Gd=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")},Kb=t=>new TextEncoder().encode(t),Wb=t=>new TextDecoder().decode(t);let Gb=class{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Yb=class{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yd(this,e)}},Zb=class{constructor(e){this.decoders=e}or(e){return Yd(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};const Yd=(t,e)=>new Zb({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});let Jb=class{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new Gb(e,r,i),this.decoder=new Yb(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}};const Ks=({name:t,prefix:e,encode:r,decode:i})=>new Jb(t,e,r,i),Pn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=Hb(r,e);return Ks({prefix:t,name:e,encode:i,decode:s=>Gd(n(s))})},Xb=(t,e,r,i)=>{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*r/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-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},Qb=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Fe=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Ks({prefix:e,name:t,encode(n){return Qb(n,i,r)},decode(n){return Xb(n,i,r,t)}}),ev=Ks({prefix:"\0",name:"identity",encode:t=>Wb(t),decode:t=>Kb(t)});var tv=Object.freeze({__proto__:null,identity:ev});const rv=Fe({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var iv=Object.freeze({__proto__:null,base2:rv});const nv=Fe({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var sv=Object.freeze({__proto__:null,base8:nv});const ov=Pn({prefix:"9",name:"base10",alphabet:"0123456789"});var av=Object.freeze({__proto__:null,base10:ov});const cv=Fe({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),lv=Fe({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var uv=Object.freeze({__proto__:null,base16:cv,base16upper:lv});const hv=Fe({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),fv=Fe({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),dv=Fe({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),pv=Fe({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),gv=Fe({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),yv=Fe({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),wv=Fe({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),mv=Fe({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),bv=Fe({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var vv=Object.freeze({__proto__:null,base32:hv,base32upper:fv,base32pad:dv,base32padupper:pv,base32hex:gv,base32hexupper:yv,base32hexpad:wv,base32hexpadupper:mv,base32z:bv});const Ev=Pn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),xv=Pn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var _v=Object.freeze({__proto__:null,base36:Ev,base36upper:xv});const Iv=Pn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Sv=Pn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var $v=Object.freeze({__proto__:null,base58btc:Iv,base58flickr:Sv});const Ov=Fe({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Dv=Fe({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Av=Fe({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Pv=Fe({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Cv=Object.freeze({__proto__:null,base64:Ov,base64pad:Dv,base64url:Av,base64urlpad:Pv});const Zd=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),Bv=Zd.reduce((t,e,r)=>(t[r]=e,t),[]),Tv=Zd.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Rv(t){return t.reduce((e,r)=>(e+=Bv[r],e),"")}function Fv(t){const e=[];for(const r of t){const i=Tv[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const Nv=Ks({prefix:"🚀",name:"base256emoji",encode:Rv,decode:Fv});var Uv=Object.freeze({__proto__:null,base256emoji:Nv}),kv=Jd,ou=128,jv=127,Lv=~jv,Mv=Math.pow(2,31);function Jd(t,e,r){e=e||[],r=r||0;for(var i=r;t>=Mv;)e[r++]=t&255|ou,t/=128;for(;t&Lv;)e[r++]=t&255|ou,t>>>=7;return e[r]=t|0,Jd.bytes=r-i+1,e}var qv=Da,zv=128,au=127;function Da(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Da.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&au)<<n:(o&au)*Math.pow(2,n),n+=7}while(o>=zv);return Da.bytes=s-i,r}var Vv=Math.pow(2,7),Hv=Math.pow(2,14),Kv=Math.pow(2,21),Wv=Math.pow(2,28),Gv=Math.pow(2,35),Yv=Math.pow(2,42),Zv=Math.pow(2,49),Jv=Math.pow(2,56),Xv=Math.pow(2,63),Qv=function(t){return t<Vv?1:t<Hv?2:t<Kv?3:t<Wv?4:t<Gv?5:t<Yv?6:t<Zv?7:t<Jv?8:t<Xv?9:10},e2={encode:kv,decode:qv,encodingLength:Qv},Xd=e2;const cu=(t,e,r=0)=>(Xd.encode(t,e,r),e),lu=t=>Xd.encodingLength(t),Aa=(t,e)=>{const r=e.byteLength,i=lu(t),n=i+lu(r),s=new Uint8Array(n+r);return cu(t,s,0),cu(r,s,i),s.set(e,n),new t2(t,r,e,s)};let t2=class{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}};const Qd=({name:t,code:e,encode:r})=>new r2(t,e,r);let r2=class{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?Aa(this.code,r):r.then(i=>Aa(this.code,i))}else throw Error("Unknown type, must be binary type")}};const ep=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),i2=Qd({name:"sha2-256",code:18,encode:ep("SHA-256")}),n2=Qd({name:"sha2-512",code:19,encode:ep("SHA-512")});var s2=Object.freeze({__proto__:null,sha256:i2,sha512:n2});const tp=0,o2="identity",rp=Gd,a2=t=>Aa(tp,rp(t)),c2={code:tp,name:o2,encode:rp,digest:a2};var l2=Object.freeze({__proto__:null,identity:c2});new TextEncoder,new TextDecoder;const uu={...tv,...iv,...sv,...av,...uv,...vv,..._v,...$v,...Cv,...Uv};({...s2,...l2});function ip(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const hu=ip("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),Uo=ip("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=Kd(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),np={utf8:hu,"utf-8":hu,hex:uu.base16,latin1:Uo,ascii:Uo,binary:Uo,...uu};function Ws(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}function Li(t,e="utf8"){const r=np[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Bc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function fu(t){return si(Ws(Li(t,Hs),Vd))}function $s(t){return Ws(Li(oi(t),Vd),Hs)}function sp(t){const e=Li(Mb,su),r=Lb+Ws(Wd([e,t]),su);return[kb,jb,r].join(Ub)}function u2(t){return Ws(t,Hs)}function h2(t){return Li(t,Hs)}function f2(t){return Li([$s(t.header),$s(t.payload)].join(Ss),Hd)}function d2(t){return[$s(t.header),$s(t.payload),u2(t.signature)].join(Ss)}function Pa(t){const e=t.split(Ss),r=fu(e[0]),i=fu(e[1]),n=h2(e[2]),s=Li(e.slice(0,2).join(Ss),Hd);return{header:r,payload:i,signature:n,data:s}}function du(t=Td(qb)){const e=zd.getPublicKey(t);return{secretKey:Wd([t,e]),publicKey:e}}async function p2(t,e,r,i,n=L.fromMiliseconds(Date.now())){const s={alg:Fb,typ:Nb},o=sp(i.publicKey),a=n+r,c={iss:o,sub:t,aud:e,iat:n,exp:a},l=f2({header:s,payload:c}),u=zd.sign(l,i.secretKey.slice(0,32));return d2({header:s,payload:c,signature:u})}function Tc(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function op(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?Tc(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function fn(t,e){e||(e=t.reduce((n,s)=>n+s.length,0));const r=op(e);let i=0;for(const n of t)r.set(n,i),i+=n.length;return Tc(r)}function g2(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[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,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*u+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}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,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;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 y2=g2,w2=y2;const m2=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")},b2=t=>new TextEncoder().encode(t),v2=t=>new TextDecoder().decode(t);class E2{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class x2{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return ap(this,e)}}class _2{constructor(e){this.decoders=e}or(e){return ap(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const ap=(t,e)=>new _2({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class I2{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new E2(e,r,i),this.decoder=new x2(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const Gs=({name:t,prefix:e,encode:r,decode:i})=>new I2(t,e,r,i),Cn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=w2(r,e);return Gs({prefix:t,name:e,encode:i,decode:s=>m2(n(s))})},S2=(t,e,r,i)=>{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*r/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-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},$2=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ne=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>Gs({prefix:e,name:t,encode(n){return $2(n,i,r)},decode(n){return S2(n,i,r,t)}}),O2=Gs({prefix:"\0",name:"identity",encode:t=>v2(t),decode:t=>b2(t)}),D2=Object.freeze(Object.defineProperty({__proto__:null,identity:O2},Symbol.toStringTag,{value:"Module"})),A2=Ne({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),P2=Object.freeze(Object.defineProperty({__proto__:null,base2:A2},Symbol.toStringTag,{value:"Module"})),C2=Ne({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),B2=Object.freeze(Object.defineProperty({__proto__:null,base8:C2},Symbol.toStringTag,{value:"Module"})),T2=Cn({prefix:"9",name:"base10",alphabet:"0123456789"}),R2=Object.freeze(Object.defineProperty({__proto__:null,base10:T2},Symbol.toStringTag,{value:"Module"})),F2=Ne({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),N2=Ne({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),U2=Object.freeze(Object.defineProperty({__proto__:null,base16:F2,base16upper:N2},Symbol.toStringTag,{value:"Module"})),k2=Ne({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),j2=Ne({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),L2=Ne({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),M2=Ne({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),q2=Ne({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),z2=Ne({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),V2=Ne({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),H2=Ne({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),K2=Ne({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),W2=Object.freeze(Object.defineProperty({__proto__:null,base32:k2,base32hex:q2,base32hexpad:V2,base32hexpadupper:H2,base32hexupper:z2,base32pad:L2,base32padupper:M2,base32upper:j2,base32z:K2},Symbol.toStringTag,{value:"Module"})),G2=Cn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Y2=Cn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),Z2=Object.freeze(Object.defineProperty({__proto__:null,base36:G2,base36upper:Y2},Symbol.toStringTag,{value:"Module"})),J2=Cn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),X2=Cn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),Q2=Object.freeze(Object.defineProperty({__proto__:null,base58btc:J2,base58flickr:X2},Symbol.toStringTag,{value:"Module"})),eE=Ne({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),tE=Ne({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),rE=Ne({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),iE=Ne({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),nE=Object.freeze(Object.defineProperty({__proto__:null,base64:eE,base64pad:tE,base64url:rE,base64urlpad:iE},Symbol.toStringTag,{value:"Module"})),cp=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),sE=cp.reduce((t,e,r)=>(t[r]=e,t),[]),oE=cp.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function aE(t){return t.reduce((e,r)=>(e+=sE[r],e),"")}function cE(t){const e=[];for(const r of t){const i=oE[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const lE=Gs({prefix:"🚀",name:"base256emoji",encode:aE,decode:cE}),uE=Object.freeze(Object.defineProperty({__proto__:null,base256emoji:lE},Symbol.toStringTag,{value:"Module"}));new TextEncoder;new TextDecoder;const pu={...D2,...P2,...B2,...R2,...U2,...W2,...Z2,...Q2,...nE,...uE};function lp(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const gu=lp("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ko=lp("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=op(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),up={utf8:gu,"utf-8":gu,hex:pu.base16,latin1:ko,ascii:ko,binary:ko,...pu};function Et(t,e="utf8"){const r=up[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?Tc(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}function nt(t,e="utf8"){const r=up[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?globalThis.Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8"):r.encoder.encode(t).substring(1)}const hE={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"}},fE="Input must be an string, Buffer or Uint8Array";function dE(t){let e;if(t instanceof Uint8Array)e=t;else if(typeof t=="string")e=new TextEncoder().encode(t);else throw new Error(fE);return e}function pE(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 gE(t,e,r){let i=`
|
|
16
|
+
`+t+" = ";for(let n=0;n<e.length;n+=2){if(r===32)i+=Kn(e[n]).toUpperCase(),i+=" ",i+=Kn(e[n+1]).toUpperCase();else if(r===64)i+=Kn(e[n+1]).toUpperCase(),i+=Kn(e[n]).toUpperCase();else throw new Error("Invalid size "+r);n%6===4?i+=`
|
|
17
|
+
`+new Array(t.length+4).join(" "):n<e.length-2&&(i+=" ")}console.log(i)}function yE(t,e,r){let i=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-i)+"ms"),i=s;for(let o=0;o<r;o++){const a=t(n),c=new Date().getTime(),l=c-i;i=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 hp={normalizeInput:dE,toHex:pE,debugPrint:gE,testSpeed:yE};const hs=hp;function Wn(t,e,r){const i=t[e]+t[r];let n=t[e+1]+t[r+1];i>=4294967296&&n++,t[e]=i,t[e+1]=n}function yu(t,e,r,i){let n=t[e]+r;r<0&&(n+=4294967296);let s=t[e+1]+i;n>=4294967296&&s++,t[e]=n,t[e+1]=s}function fp(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function mr(t,e,r,i,n,s){const o=an[n],a=an[n+1],c=an[s],l=an[s+1];Wn(Z,t,e),yu(Z,t,o,a);let u=Z[i]^Z[t],h=Z[i+1]^Z[t+1];Z[i]=h,Z[i+1]=u,Wn(Z,r,i),u=Z[e]^Z[r],h=Z[e+1]^Z[r+1],Z[e]=u>>>24^h<<8,Z[e+1]=h>>>24^u<<8,Wn(Z,t,e),yu(Z,t,c,l),u=Z[i]^Z[t],h=Z[i+1]^Z[t+1],Z[i]=u>>>16^h<<16,Z[i+1]=h>>>16^u<<16,Wn(Z,r,i),u=Z[e]^Z[r],h=Z[e+1]^Z[r+1],Z[e]=h>>>31^u<<1,Z[e+1]=u>>>31^h<<1}const dp=new Uint32Array([4089235720,1779033703,2227873595,3144134277,4271175723,1013904242,1595750129,2773480762,2917565137,1359893119,725511199,2600822924,4215389547,528734635,327033209,1541459225]),wE=[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(wE.map(function(t){return t*2})),Z=new Uint32Array(32),an=new Uint32Array(32);function pp(t,e){let r=0;for(r=0;r<16;r++)Z[r]=t.h[r],Z[r+16]=dp[r];for(Z[24]=Z[24]^t.t,Z[25]=Z[25]^t.t/4294967296,e&&(Z[28]=~Z[28],Z[29]=~Z[29]),r=0;r<32;r++)an[r]=fp(t.b,4*r);for(r=0;r<12;r++)mr(0,8,16,24,ke[r*16+0],ke[r*16+1]),mr(2,10,18,26,ke[r*16+2],ke[r*16+3]),mr(4,12,20,28,ke[r*16+4],ke[r*16+5]),mr(6,14,22,30,ke[r*16+6],ke[r*16+7]),mr(0,10,20,30,ke[r*16+8],ke[r*16+9]),mr(2,12,22,24,ke[r*16+10],ke[r*16+11]),mr(4,14,16,26,ke[r*16+12],ke[r*16+13]),mr(6,8,18,28,ke[r*16+14],ke[r*16+15]);for(r=0;r<16;r++)t.h[r]=t.h[r]^Z[r]^Z[r+16]}const br=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 gp(t,e,r,i){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(r&&r.length!==16)throw new Error("Illegal salt, expected Uint8Array with length is 16");if(i&&i.length!==16)throw new Error("Illegal personal, expected Uint8Array with length is 16");const n={b:new Uint8Array(128),h:new Uint32Array(16),t:0,c:0,outlen:t};br.fill(0),br[0]=t,e&&(br[1]=e.length),br[2]=1,br[3]=1,r&&br.set(r,32),i&&br.set(i,48);for(let s=0;s<16;s++)n.h[s]=dp[s]^fp(br,s*4);return e&&(Rc(n,e),n.c=128),n}function Rc(t,e){for(let r=0;r<e.length;r++)t.c===128&&(t.t+=t.c,pp(t,!1),t.c=0),t.b[t.c++]=e[r]}function yp(t){for(t.t+=t.c;t.c<128;)t.b[t.c++]=0;pp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3);return e}function wp(t,e,r,i,n){r=r||64,t=hs.normalizeInput(t),i&&(i=hs.normalizeInput(i)),n&&(n=hs.normalizeInput(n));const s=gp(r,e,i,n);return Rc(s,t),yp(s)}function mE(t,e,r,i,n){const s=wp(t,e,r,i,n);return hs.toHex(s)}var bE={blake2b:wp,blake2bHex:mE,blake2bInit:gp,blake2bUpdate:Rc,blake2bFinal:yp};const mp=hp;function vE(t,e){return t[e]^t[e+1]<<8^t[e+2]<<16^t[e+3]<<24}function vr(t,e,r,i,n,s){se[t]=se[t]+se[e]+n,se[i]=Gn(se[i]^se[t],16),se[r]=se[r]+se[i],se[e]=Gn(se[e]^se[r],12),se[t]=se[t]+se[e]+s,se[i]=Gn(se[i]^se[t],8),se[r]=se[r]+se[i],se[e]=Gn(se[e]^se[r],7)}function Gn(t,e){return t>>>e^t<<32-e}const bp=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 vp(t,e){let r=0;for(r=0;r<8;r++)se[r]=t.h[r],se[r+8]=bp[r];for(se[12]^=t.t,se[13]^=t.t/4294967296,e&&(se[14]=~se[14]),r=0;r<16;r++)Pe[r]=vE(t.b,4*r);for(r=0;r<10;r++)vr(0,4,8,12,Pe[je[r*16+0]],Pe[je[r*16+1]]),vr(1,5,9,13,Pe[je[r*16+2]],Pe[je[r*16+3]]),vr(2,6,10,14,Pe[je[r*16+4]],Pe[je[r*16+5]]),vr(3,7,11,15,Pe[je[r*16+6]],Pe[je[r*16+7]]),vr(0,5,10,15,Pe[je[r*16+8]],Pe[je[r*16+9]]),vr(1,6,11,12,Pe[je[r*16+10]],Pe[je[r*16+11]]),vr(2,7,8,13,Pe[je[r*16+12]],Pe[je[r*16+13]]),vr(3,4,9,14,Pe[je[r*16+14]],Pe[je[r*16+15]]);for(r=0;r<8;r++)t.h[r]^=se[r]^se[r+8]}function Ep(t,e){if(!(t>0&&t<=32))throw new Error("Incorrect output length, should be in [1, 32]");const r=e?e.length:0;if(e&&!(r>0&&r<=32))throw new Error("Incorrect key length, should be in [1, 32]");const i={h:new Uint32Array(bp),b:new Uint8Array(64),c:0,t:0,outlen:t};return i.h[0]^=16842752^r<<8^t,r>0&&(Fc(i,e),i.c=64),i}function Fc(t,e){for(let r=0;r<e.length;r++)t.c===64&&(t.t+=t.c,vp(t,!1),t.c=0),t.b[t.c++]=e[r]}function xp(t){for(t.t+=t.c;t.c<64;)t.b[t.c++]=0;vp(t,!0);const e=new Uint8Array(t.outlen);for(let r=0;r<t.outlen;r++)e[r]=t.h[r>>2]>>8*(r&3)&255;return e}function _p(t,e,r){r=r||32,t=mp.normalizeInput(t);const i=Ep(r,e);return Fc(i,t),xp(i)}function EE(t,e,r){const i=_p(t,e,r);return mp.toHex(i)}var xE={blake2s:_p,blake2sHex:EE,blake2sInit:Ep,blake2sUpdate:Fc,blake2sFinal:xp};const Yi=bE,Zi=xE;var _E={blake2b:Yi.blake2b,blake2bHex:Yi.blake2bHex,blake2bInit:Yi.blake2bInit,blake2bUpdate:Yi.blake2bUpdate,blake2bFinal:Yi.blake2bFinal,blake2s:Zi.blake2s,blake2sHex:Zi.blake2sHex,blake2sInit:Zi.blake2sInit,blake2sUpdate:Zi.blake2sUpdate,blake2sFinal:Zi.blake2sFinal},zt={exports:{}};function IE(t){try{return JSON.stringify(t)}catch{return'"[Circular]"'}}var SE=$E;function $E(t,e,r){var i=r&&r.stringify||IE,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]=i(t);for(var a=1;a<s;a++)o[a]=i(e[a]);return o.join(" ")}if(typeof t!="string")return t;var c=e.length;if(c===0)return t;for(var 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+=i(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 wu=SE;zt.exports=lr;const En=ME().console||{},OE={mapHttpRequest:Yn,mapHttpResponse:Yn,wrapRequestSerializer:jo,wrapResponseSerializer:jo,wrapErrorSerializer:jo,req:Yn,res:Yn,err:bu,errWithCause:bu};function Tr(t,e){return t==="silent"?1/0:e.levels.values[t]}const Nc=Symbol("pino.logFuncs"),Ca=Symbol("pino.hierarchy"),DE={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function mu(t,e){const r={logger:e,parent:t[Ca]};e[Ca]=r}function AE(t,e,r){const i={};e.forEach(n=>{i[n]=r[n]?r[n]:En[n]||En[DE[n]||"log"]||Pi}),t[Nc]=i}function PE(t,e){return Array.isArray(t)?t.filter(function(r){return r!=="!stdSerializers.err"}):t===!0?Object.keys(e):!1}function lr(t){t=t||{},t.browser=t.browser||{};const e=t.browser.transmit;if(e&&typeof e.send!="function")throw Error("pino: transmit option must have a send function");const r=t.browser.write||En;t.browser.write&&(t.browser.asObject=!0);const i=t.serializers||{},n=PE(t.browser.serialize,i);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 r=="function"&&a.forEach(function(g){r[g]=r}),(t.enabled===!1||t.browser.disabled)&&(t.level="silent");const c=t.level||"info",l=Object.create(r);l.log||(l.log=Pi),AE(l,a,r),mu({},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:kE(t),messageKey:t.messageKey||"msg",onChild:t.onChild||Pi};l.levels=CE(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=Pi,l.serializers=i,l._serialize=n,l._stdErrSerialize=s,l.child=function(...g){return p.call(this,u,...g)},e&&(l._logEvent=Ba());function h(){return Tr(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,qr(this,u,l,"error"),qr(this,u,l,"fatal"),qr(this,u,l,"warn"),qr(this,u,l,"info"),qr(this,u,l,"debug"),qr(this,u,l,"trace"),o.forEach(w=>{qr(this,u,l,w)})}function p(g,w,I){if(!w)throw new Error("missing bindings for child Pino");I=I||{},n&&w.serializers&&(I.serializers=w.serializers);const C=I.serializers;if(n&&C){var b=Object.assign({},i,C),v=t.browser.serialize===!0?Object.keys(b):n;delete w.serializers,Uc([w],v,b,this._stdErrSerialize)}function D(T){this._childLevel=(T._childLevel|0)+1,this.bindings=w,b&&(this.serializers=b,this._serialize=v),e&&(this._logEvent=Ba([].concat(T._logEvent.bindings,w)))}D.prototype=this;const P=new D(this);return mu(this,P),P.child=function(...T){return p.call(this,g,...T)},P.level=I.level||this.level,g.onChild(P),P}return l}function CE(t){const e=t.customLevels||{},r=Object.assign({},lr.levels.values,e),i=Object.assign({},lr.levels.labels,BE(e));return{values:r,labels:i}}function BE(t){const e={};return Object.keys(t).forEach(function(r){e[t[r]]=r}),e}lr.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"}},lr.stdSerializers=OE,lr.stdTimeFunctions=Object.assign({},{nullTime:Ip,epochTime:Sp,unixTime:jE,isoTime:LE});function TE(t){const e=[];t.bindings&&e.push(t.bindings);let r=t[Ca];for(;r.parent;)r=r.parent,r.logger.bindings&&e.push(r.logger.bindings);return e.reverse()}function qr(t,e,r,i){if(Object.defineProperty(t,i,{value:Tr(t.level,r)>Tr(i,r)?Pi:r[Nc][i],writable:!0,enumerable:!0,configurable:!0}),t[i]===Pi){if(!e.transmit)return;const s=e.transmit.level||t.level,o=Tr(s,r);if(Tr(i,r)<o)return}t[i]=FE(t,e,r,i);const n=TE(t);n.length!==0&&(t[i]=RE(n,t[i]))}function RE(t,e){return function(){return e.apply(this,[...t,...arguments])}}function FE(t,e,r,i){return function(n){return function(){const s=e.timestamp(),o=new Array(arguments.length),a=Object.getPrototypeOf&&Object.getPrototypeOf(this)===En?En:this;for(var c=0;c<o.length;c++)o[c]=arguments[c];var l=!1;if(e.serialize&&(Uc(o,this._serialize,this.serializers,this._stdErrSerialize),l=!0),e.asObject||e.formatters?n.call(a,...NE(this,i,o,s,e)):n.apply(a,o),e.transmit){const u=e.transmit.level||t._level,h=Tr(u,r),f=Tr(i,r);if(f<h)return;UE(this,{ts:s,methodLevel:i,methodValue:f,transmitLevel:u,transmitValue:r.levels.values[e.transmit.level||t._level],send:e.transmit.send,val:Tr(t._level,r)},o,l)}}}(t[Nc][i])}function NE(t,e,r,i,n){const{level:s,log:o=h=>h}=n.formatters||{},a=r.slice();let c=a[0];const l={};let u=(t._childLevel|0)+1;if(u<1&&(u=1),i&&(l.time=i),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?wu(a.shift(),a):void 0}else typeof c=="string"&&(c=wu(a.shift(),a));return c!==void 0&&(l[n.messageKey]=c),[o(l)]}}function Uc(t,e,r,i){for(const n in t)if(i&&t[n]instanceof Error)t[n]=lr.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 r&&(t[n][s]=r[s](t[n][s]))}function UE(t,e,r,i=!1){const n=e.send,s=e.ts,o=e.methodLevel,a=e.methodValue,c=e.val,l=t._logEvent.bindings;i||Uc(r,t._serialize||Object.keys(t.serializers),t.serializers,t._stdErrSerialize===void 0?!0:t._stdErrSerialize),t._logEvent.ts=s,t._logEvent.messages=r.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=Ba(l)}function Ba(t){return{ts:0,messages:[],bindings:t||[],level:{label:"",value:0}}}function bu(t){const e={type:t.constructor.name,msg:t.message,stack:t.stack};for(const r in t)e[r]===void 0&&(e[r]=t[r]);return e}function kE(t){return typeof t.timestamp=="function"?t.timestamp:t.timestamp===!1?Ip:Sp}function Yn(){return{}}function jo(t){return t}function Pi(){}function Ip(){return!1}function Sp(){return Date.now()}function jE(){return Math.round(Date.now()/1e3)}function LE(){return new Date(Date.now()).toISOString()}function ME(){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)||{}}}zt.exports.default=lr;zt.exports.pino=lr;const qE={level:"info"},Ys="custom_context",kc=1e3*1024;var zE=Object.defineProperty,VE=(t,e,r)=>e in t?zE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Pr=(t,e,r)=>VE(t,typeof e!="symbol"?e+"":e,r);let HE=class{constructor(e){Pr(this,"nodeValue"),Pr(this,"sizeInBytes"),Pr(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}},vu=class{constructor(e){Pr(this,"lengthInNodes"),Pr(this,"sizeInBytes"),Pr(this,"head"),Pr(this,"tail"),Pr(this,"maxSizeInBytes"),this.head=null,this.tail=null,this.lengthInNodes=0,this.maxSizeInBytes=e,this.sizeInBytes=0}append(e){const r=new HE(e);if(r.size>this.maxSizeInBytes)throw new Error(`[LinkedList] Value too big to insert into list: ${e} with size ${r.size}`);for(;this.size+r.size>this.maxSizeInBytes;)this.shift();this.head?(this.tail&&(this.tail.next=r),this.tail=r):(this.head=r,this.tail=r),this.lengthInNodes++,this.sizeInBytes+=r.size}shift(){if(!this.head)return;const e=this.head;this.head=this.head.next,this.head||(this.tail=null),this.lengthInNodes--,this.sizeInBytes-=e.size}toArray(){const e=[];let r=this.head;for(;r!==null;)e.push(r.value),r=r.next;return e}get length(){return this.lengthInNodes}get size(){return this.sizeInBytes}toOrderedArray(){return Array.from(this)}[Symbol.iterator](){let e=this.head;return{next:()=>{if(!e)return{done:!0,value:null};const r=e.value;return e=e.next,{done:!1,value:r}}}}};const KE=t=>JSON.stringify(t,(e,r)=>typeof r=="bigint"?r.toString()+"n":r);function Eu(t){return typeof t=="string"?t:KE(t)||""}var WE=Object.defineProperty,GE=(t,e,r)=>e in t?WE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zn=(t,e,r)=>GE(t,typeof e!="symbol"?e+"":e,r);let $p=class{constructor(e,r=kc){Zn(this,"logs"),Zn(this,"level"),Zn(this,"levelValue"),Zn(this,"MAX_LOG_SIZE_IN_BYTES"),this.level=e??"error",this.levelValue=zt.exports.levels.values[this.level],this.MAX_LOG_SIZE_IN_BYTES=r,this.logs=new vu(this.MAX_LOG_SIZE_IN_BYTES)}forwardToConsole(e,r){r===zt.exports.levels.values.error?console.error(e):r===zt.exports.levels.values.warn?console.warn(e):r===zt.exports.levels.values.debug?console.debug(e):r===zt.exports.levels.values.trace?console.trace(e):console.log(e)}appendToLogs(e){this.logs.append(Eu({timestamp:new Date().toISOString(),log:e}));const r=typeof e=="string"?JSON.parse(e).level:e.level;r>=this.levelValue&&this.forwardToConsole(e,r)}getLogs(){return this.logs}clearLogs(){this.logs=new vu(this.MAX_LOG_SIZE_IN_BYTES)}getLogArray(){return Array.from(this.logs)}logsToBlob(e){const r=this.getLogArray();return r.push(Eu({extraMetadata:e})),new Blob(r,{type:"application/json"})}};var YE=Object.defineProperty,ZE=(t,e,r)=>e in t?YE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,JE=(t,e,r)=>ZE(t,typeof e!="symbol"?e+"":e,r);let XE=class{constructor(e,r=kc){JE(this,"baseChunkLogger"),this.baseChunkLogger=new $p(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}downloadLogsBlobInBrowser(e){const r=URL.createObjectURL(this.logsToBlob(e)),i=document.createElement("a");i.href=r,i.download=`walletconnect-logs-${new Date().toISOString()}.txt`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}};var QE=Object.defineProperty,e3=(t,e,r)=>e in t?QE(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,t3=(t,e,r)=>e3(t,typeof e!="symbol"?e+"":e,r);let r3=class{constructor(e,r=kc){t3(this,"baseChunkLogger"),this.baseChunkLogger=new $p(e,r)}write(e){this.baseChunkLogger.appendToLogs(e)}getLogs(){return this.baseChunkLogger.getLogs()}clearLogs(){this.baseChunkLogger.clearLogs()}getLogArray(){return this.baseChunkLogger.getLogArray()}logsToBlob(e){return this.baseChunkLogger.logsToBlob(e)}};var i3=Object.defineProperty,n3=Object.defineProperties,s3=Object.getOwnPropertyDescriptors,xu=Object.getOwnPropertySymbols,o3=Object.prototype.hasOwnProperty,a3=Object.prototype.propertyIsEnumerable,_u=(t,e,r)=>e in t?i3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Os=(t,e)=>{for(var r in e||(e={}))o3.call(e,r)&&_u(t,r,e[r]);if(xu)for(var r of xu(e))a3.call(e,r)&&_u(t,r,e[r]);return t},Ds=(t,e)=>n3(t,s3(e));function c3(t){return Ds(Os({},t),{level:(t==null?void 0:t.level)||qE.level})}function l3(t,e,r=Ys){return t[r]=e,t}function st(t,e=Ys){return t[e]||""}function u3(t,e,r=Ys){const i=st(t,r);return i.trim()?`${i}/${e}`:e}function dt(t,e,r=Ys){const i=u3(t,e,r),n=t.child({context:i});return l3(n,i,r)}function h3(t){var e,r;const i=new XE((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:zt.exports(Ds(Os({},t.opts),{level:"trace",browser:Ds(Os({},(r=t.opts)==null?void 0:r.browser),{write:n=>i.write(n)})})),chunkLoggerController:i}}function f3(t){var e;const r=new r3((e=t.opts)==null?void 0:e.level,t.maxSizeInBytes);return{logger:zt.exports(Ds(Os({},t.opts),{level:"trace"}),r),chunkLoggerController:r}}function Op(t){return typeof t.loggerOverride<"u"&&typeof t.loggerOverride!="string"?{logger:t.loggerOverride,chunkLoggerController:null}:typeof window<"u"?h3(t):f3(t)}const d3=":";function ur(t){const[e,r]=t.split(d3);return{namespace:e,reference:r}}function Iu(t,e=[]){const r=[];return Object.keys(t).forEach(i=>{if(e.length&&!e.includes(i))return;const n=t[i];r.push(...n.accounts)}),r}function Dp(t,e){return t.includes(":")?[t]:e.chains||[]}var p3=Object.defineProperty,g3=Object.defineProperties,y3=Object.getOwnPropertyDescriptors,Su=Object.getOwnPropertySymbols,w3=Object.prototype.hasOwnProperty,m3=Object.prototype.propertyIsEnumerable,Ta=(t,e,r)=>e in t?p3(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$u=(t,e)=>{for(var r in e||(e={}))w3.call(e,r)&&Ta(t,r,e[r]);if(Su)for(var r of Su(e))m3.call(e,r)&&Ta(t,r,e[r]);return t},b3=(t,e)=>g3(t,y3(e)),Ou=(t,e,r)=>Ta(t,typeof e!="symbol"?e+"":e,r);const v3="ReactNative",ft={reactNative:"react-native",node:"node",browser:"browser",unknown:"unknown"},E3="js";function As(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}function kr(){return!ii()&&!!pc()&&navigator.product===v3}function x3(){return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="android"}function _3(){return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"&&(Y==null?void 0:Y.Platform.OS)==="ios"}function Mi(){return!As()&&!!pc()&&!!ii()}function Bn(){return kr()?ft.reactNative:As()?ft.node:Mi()?ft.browser:ft.unknown}function Du(){var t;try{return kr()&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Application)<"u"?(t=Y.Application)==null?void 0:t.applicationId:void 0}catch{return}}function I3(t,e){const r=new URLSearchParams(t);return Object.entries(e).sort(([i],[n])=>i.localeCompare(n)).forEach(([i,n])=>{n!=null&&r.set(i,String(n))}),r.toString()}function S3(t){var e,r;const i=Ap();try{return t!=null&&t.url&&i.url&&new URL(t.url).host!==new URL(i.url).host&&(console.warn(`The configured WalletConnect 'metadata.url':${t.url} differs from the actual page url:${i.url}. This is probably unintended and can lead to issues.`),t.url=i.url),(e=t==null?void 0:t.icons)!=null&&e.length&&t.icons.length>0&&(t.icons=t.icons.filter(n=>n!=="")),b3($u($u({},i),t),{url:(t==null?void 0:t.url)||i.url,name:(t==null?void 0:t.name)||i.name,description:(t==null?void 0:t.description)||i.description,icons:(r=t==null?void 0:t.icons)!=null&&r.length&&t.icons.length>0?t.icons:i.icons})}catch(n){return console.warn("Error populating app metadata",n),t||i}}function Ap(){return qf()||{name:"",description:"",url:"",icons:[""]}}function $3(){if(Bn()===ft.reactNative&&typeof Y<"u"&&typeof(Y==null?void 0:Y.Platform)<"u"){const{OS:r,Version:i}=Y.Platform;return[r,i].join("-")}const t=q0();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 O3(){var t;const e=Bn();return e===ft.browser?[e,((t=Mf())==null?void 0:t.host)||"unknown"].join(":"):e}function Pp(t,e,r){const i=$3(),n=O3();return[[t,e].join("-"),[E3,r].join("-"),i,n].join("/")}function D3({protocol:t,version:e,relayUrl:r,sdkVersion:i,auth:n,projectId:s,useOnCloseEvent:o,bundleId:a,packageName:c}){const l=r.split("?"),u=Pp(t,e,i),h={auth:n,ua:u,projectId:s,useOnCloseEvent:o||void 0,packageName:c||void 0,bundleId:a||void 0},f=I3(l[1]||"",h);return l[0]+"?"+f}function Xr(t,e){return t.filter(r=>e.includes(r)).length===t.length}function Ra(t){return Object.fromEntries(t.entries())}function Fa(t){return new Map(Object.entries(t))}function Kr(t=L.FIVE_MINUTES,e){const r=L.toMiliseconds(t||L.FIVE_MINUTES);let i,n,s,o;return{resolve:a=>{s&&i&&(clearTimeout(s),i(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)},r),i=a,n=c})}}function Vt(t,e,r){return new Promise(async(i,n)=>{const s=setTimeout(()=>n(new Error(r)),e);try{const o=await t;i(o)}catch(o){n(o)}clearTimeout(s)})}function Cp(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 A3(t){return Cp("topic",t)}function P3(t){return Cp("id",t)}function Bp(t){const[e,r]=t.split(":"),i={id:void 0,topic:void 0};if(e==="topic"&&typeof r=="string")i.topic=r;else if(e==="id"&&Number.isInteger(Number(r)))i.id=Number(r);else throw new Error(`Invalid target, expected id:number or topic:string, got ${e}:${r}`);return i}function 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 Ht(t=[],e=[]){return[...new Set([...t,...e])]}async function C3({id:t,topic:e,wcDeepLink:r}){var i;try{if(!r)return;const n=typeof r=="string"?JSON.parse(r):r,s=n==null?void 0:n.href;if(typeof s!="string")return;const o=B3(s,t,e),a=Bn();if(a===ft.browser){if(!((i=ii())!=null&&i.hasFocus())){console.warn("Document does not have focus, skipping deeplink.");return}T3(o)}else a===ft.reactNative&&typeof(Y==null?void 0:Y.Linking)<"u"&&await Y.Linking.openURL(o)}catch(n){console.error(n)}}function B3(t,e,r){const i=`requestId=${e}&sessionTopic=${r}`;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}${U3(i,!0)}`}else n=`${n}/wc?${i}`;return n}function T3(t){let e="_self";N3()?e="_top":(F3()||t.startsWith("https://")||t.startsWith("http://"))&&(e="_blank"),window.open(t,e,"noreferrer noopener")}async function R3(t,e){let r="";try{if(Mi()&&(r=localStorage.getItem(e),r))return r;r=await t.getItem(e)}catch(i){console.error(i)}return r}function Au(t,e){if(!t.includes(e))return null;const r=t.split(/([&,?,=])/),i=r.indexOf(e);return r[i+2]}function Pu(){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 jc(){return typeof xt<"u"&&{}.IS_VITEST==="true"}function F3(){return typeof window<"u"&&(!!window.TelegramWebviewProxy||!!window.Telegram||!!window.TelegramWebviewProxyProto)}function N3(){try{return window.self!==window.top}catch{return!1}}function U3(t,e=!1){const r=re.from(t).toString("base64");return e?r.replace(/[=]/g,""):r}function Tp(t){return re.from(t,"base64").toString("utf-8")}function k3(t){return new Promise(e=>setTimeout(e,t))}let j3=class{constructor({limit:e}){Ou(this,"limit"),Ou(this,"set"),this.limit=e,this.set=new Set}add(e){if(!this.set.has(e)){if(this.set.size>=this.limit){const r=this.set.values().next().value;r&&this.set.delete(r)}this.set.add(e)}}has(e){return this.set.has(e)}};const Jn=BigInt(2**32-1),Cu=BigInt(32);function Rp(t,e=!1){return e?{h:Number(t&Jn),l:Number(t>>Cu&Jn)}:{h:Number(t>>Cu&Jn)|0,l:Number(t&Jn)|0}}function Fp(t,e=!1){const r=t.length;let i=new Uint32Array(r),n=new Uint32Array(r);for(let s=0;s<r;s++){const{h:o,l:a}=Rp(t[s],e);[i[s],n[s]]=[o,a]}return[i,n]}const Bu=(t,e,r)=>t>>>r,Tu=(t,e,r)=>t<<32-r|e>>>r,Or=(t,e,r)=>t>>>r|e<<32-r,Dr=(t,e,r)=>t<<32-r|e>>>r,cn=(t,e,r)=>t<<64-r|e>>>r-32,ln=(t,e,r)=>t>>>r-32|e<<64-r,L3=(t,e)=>e,M3=(t,e)=>t,q3=(t,e,r)=>t<<r|e>>>32-r,z3=(t,e,r)=>e<<r|t>>>32-r,V3=(t,e,r)=>e<<r-32|t>>>64-r,H3=(t,e,r)=>t<<r-32|e>>>64-r;function Pt(t,e,r,i){const n=(e>>>0)+(i>>>0);return{h:t+r+(n/2**32|0)|0,l:n|0}}const Lc=(t,e,r)=>(t>>>0)+(e>>>0)+(r>>>0),Mc=(t,e,r,i)=>e+r+i+(t/2**32|0)|0,K3=(t,e,r,i)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0),W3=(t,e,r,i,n)=>e+r+i+n+(t/2**32|0)|0,G3=(t,e,r,i,n)=>(t>>>0)+(e>>>0)+(r>>>0)+(i>>>0)+(n>>>0),Y3=(t,e,r,i,n,s)=>e+r+i+n+s+(t/2**32|0)|0,bi=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 fr(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");fr(t.outputLen),fr(t.blockLen)}function Ur(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 qc(t,e){Tt(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function xn(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function It(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function Lo(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}function Nt(t,e){return t<<32-e|t>>>e}const Np=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Up(t){return t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255}const rr=Np?t=>t:t=>Up(t);function Z3(t){for(let e=0;e<t.length;e++)t[e]=Up(t[e]);return t}const Ar=Np?t=>t:Z3,kp=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",J3=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ci(t){if(Tt(t),kp)return t.toHex();let e="";for(let r=0;r<t.length;r++)e+=J3[t[r]];return e}const Qt={_0:48,_9:57,A:65,F:70,a:97,f:102};function Ru(t){if(t>=Qt._0&&t<=Qt._9)return t-Qt._0;if(t>=Qt.A&&t<=Qt.F)return t-(Qt.A-10);if(t>=Qt.a&&t<=Qt.f)return t-(Qt.a-10)}function Ps(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);if(kp)return Uint8Array.fromHex(t);const e=t.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const i=new Uint8Array(r);for(let n=0,s=0;n<r;n++,s+=2){const o=Ru(t.charCodeAt(s)),a=Ru(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)}i[n]=o*16+a}return i}function jp(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=jp(t)),Tt(t),t}function Cr(...t){let e=0;for(let i=0;i<t.length;i++){const n=t[i];Tt(n),e+=n.length}const r=new Uint8Array(e);for(let i=0,n=0;i<t.length;i++){const s=t[i];r.set(s,n),n+=s.length}return r}let Xs=class{};function Tn(t){const e=i=>t().update(Bt(i)).digest(),r=t();return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=()=>t(),e}function X3(t){const e=(i,n)=>t(n).update(Bt(i)).digest(),r=t({});return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}function ui(t=32){if(bi&&typeof bi.getRandomValues=="function")return bi.getRandomValues(new Uint8Array(t));if(bi&&typeof bi.randomBytes=="function")return Uint8Array.from(bi.randomBytes(t));throw new Error("crypto.getRandomValues must be defined")}const Q3=BigInt(0),Ji=BigInt(1),ex=BigInt(2),tx=BigInt(7),rx=BigInt(256),ix=BigInt(113),Lp=[],Mp=[],qp=[];for(let t=0,e=Ji,r=1,i=0;t<24;t++){[r,i]=[i,(2*r+3*i)%5],Lp.push(2*(5*i+r)),Mp.push((t+1)*(t+2)/2%64);let n=Q3;for(let s=0;s<7;s++)e=(e<<Ji^(e>>tx)*ix)%rx,e&ex&&(n^=Ji<<(Ji<<BigInt(s))-Ji);qp.push(n)}const zp=Fp(qp,!0),nx=zp[0],sx=zp[1],Fu=(t,e,r)=>r>32?V3(t,e,r):q3(t,e,r),Nu=(t,e,r)=>r>32?H3(t,e,r):z3(t,e,r);function ox(t,e=24){const r=new Uint32Array(10);for(let i=24-e;i<24;i++){for(let o=0;o<10;o++)r[o]=t[o]^t[o+10]^t[o+20]^t[o+30]^t[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],h=Fu(l,u,1)^r[a],f=Nu(l,u,1)^r[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=Mp[o],c=Fu(n,s,a),l=Nu(n,s,a),u=Lp[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++)r[a]=t[o+a];for(let a=0;a<10;a++)t[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}t[0]^=nx[i],t[1]^=sx[i]}It(r)}let ax=class Vp extends Xs{constructor(e,r,i,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=r,this.outputLen=i,this.enableXOF=n,this.rounds=s,fr(i),!(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(){Ar(this.state32),ox(this.state32,this.rounds),Ar(this.state32),this.posOut=0,this.pos=0}update(e){Ur(this),e=Bt(e),Tt(e);const{blockLen:r,state:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(r-this.pos,n-s);for(let a=0;a<o;a++)i[this.pos++]^=e[s++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:i,blockLen:n}=this;e[i]^=r,r&128&&i===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ur(this,!1),Tt(e),this.finish();const r=this.state,{blockLen:i}=this;for(let n=0,s=e.length;n<s;){this.posOut>=i&&this.keccak();const o=Math.min(i-this.posOut,s-n);e.set(r.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 fr(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(qc(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,It(this.state)}_cloneInto(e){const{blockLen:r,suffix:i,outputLen:n,rounds:s,enableXOF:o}=this;return e||(e=new Vp(r,i,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=i,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}};const cx=(t,e,r)=>Tn(()=>new ax(e,t,r)),lx=cx(1,136,256/8);function ux(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function hx(t,e,r){return t&e^~t&r}function fx(t,e,r){return t&e^t&r^e&r}let Hp=class extends Xs{constructor(e,r,i,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=r,this.padOffset=i,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Lo(this.buffer)}update(e){Ur(this),e=Bt(e),Tt(e);const{view:r,buffer:i,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}i.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ur(this),qc(e,this),this.finished=!0;const{buffer:r,view:i,blockLen:n,isLE:s}=this;let{pos:o}=this;r[o++]=128,It(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(i,0),o=0);for(let h=o;h<n;h++)r[h]=0;ux(i,n-8,BigInt(this.length*8),s),this.process(i,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:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:i,length:n,finished:s,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=s,e.length=n,e.pos=a,n%r&&e.buffer.set(i),e}clone(){return this._cloneInto()}};const Er=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]),dx=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]),xr=new Uint32Array(64);class px extends Hp{constructor(e=32){super(64,e,8,!1),this.A=Er[0]|0,this.B=Er[1]|0,this.C=Er[2]|0,this.D=Er[3]|0,this.E=Er[4]|0,this.F=Er[5]|0,this.G=Er[6]|0,this.H=Er[7]|0}get(){const{A:e,B:r,C:i,D:n,E:s,F:o,G:a,H:c}=this;return[e,r,i,n,s,o,a,c]}set(e,r,i,n,s,o,a,c){this.A=e|0,this.B=r|0,this.C=i|0,this.D=n|0,this.E=s|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let h=0;h<16;h++,r+=4)xr[h]=e.getUint32(r,!1);for(let h=16;h<64;h++){const f=xr[h-15],d=xr[h-2],p=Nt(f,7)^Nt(f,18)^f>>>3,g=Nt(d,17)^Nt(d,19)^d>>>10;xr[h]=g+xr[h-7]+p+xr[h-16]|0}let{A:i,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+hx(a,c,l)+dx[h]+xr[h]|0,p=(Nt(i,2)^Nt(i,13)^Nt(i,22))+fx(i,n,s)|0;u=l,l=c,c=a,a=o+d|0,o=s,s=n,n=i,i=d+p|0}i=i+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(i,n,s,o,a,c,l,u)}roundClean(){It(xr)}destroy(){this.set(0,0,0,0,0,0,0,0),It(this.buffer)}}const Kp=Fp(["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))),gx=Kp[0],yx=Kp[1],_r=new Uint32Array(80),Ir=new Uint32Array(80);let zc=class extends Hp{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:r,Bh:i,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,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w){this.Ah=e|0,this.Al=r|0,this.Bh=i|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,r){for(let b=0;b<16;b++,r+=4)_r[b]=e.getUint32(r),Ir[b]=e.getUint32(r+=4);for(let b=16;b<80;b++){const v=_r[b-15]|0,D=Ir[b-15]|0,P=Or(v,D,1)^Or(v,D,8)^Bu(v,D,7),T=Dr(v,D,1)^Dr(v,D,8)^Tu(v,D,7),R=_r[b-2]|0,A=Ir[b-2]|0,U=Or(R,A,19)^cn(R,A,61)^Bu(R,A,6),j=Dr(R,A,19)^ln(R,A,61)^Tu(R,A,6),B=K3(T,j,Ir[b-7],Ir[b-16]),_=W3(B,P,U,_r[b-7],_r[b-16]);_r[b]=_|0,Ir[b]=B|0}let{Ah:i,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:I,Hl:C}=this;for(let b=0;b<80;b++){const v=Or(h,f,14)^Or(h,f,18)^cn(h,f,41),D=Dr(h,f,14)^Dr(h,f,18)^ln(h,f,41),P=h&d^~h&g,T=f&p^~f&w,R=G3(C,D,T,yx[b],Ir[b]),A=Y3(R,I,v,P,gx[b],_r[b]),U=R|0,j=Or(i,n,28)^cn(i,n,34)^cn(i,n,39),B=Dr(i,n,28)^ln(i,n,34)^ln(i,n,39),_=i&s^i&a^s&a,O=n&o^n&c^o&c;I=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=i|0,o=n|0;const m=Lc(U,B,O);i=Mc(m,A,j,_),n=m|0}({h:i,l:n}=Pt(this.Ah|0,this.Al|0,i|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:I,l:C}=Pt(this.Hh|0,this.Hl|0,I|0,C|0),this.set(i,n,s,o,a,c,l,u,h,f,d,p,g,w,I,C)}roundClean(){It(_r,Ir)}destroy(){It(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}};class wx extends zc{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 mx extends zc{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 px),bx=Tn(()=>new zc),vx=Tn(()=>new wx),Ex=Tn(()=>new mx),xx=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 Sr(t,e,r,i,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*r],d=V[2*r+1],p=V[2*i],g=V[2*i+1],w=Lc(c,u,o);l=Mc(w,l,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:L3(g,p),Dl:M3(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:Or(h,u,24),Bl:Dr(h,u,24)},V[2*t]=c,V[2*t+1]=l,V[2*e]=u,V[2*e+1]=h,V[2*r]=f,V[2*r+1]=d,V[2*i]=p,V[2*i+1]=g}function $r(t,e,r,i,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*r],d=V[2*r+1],p=V[2*i],g=V[2*i+1],w=Lc(c,u,o);l=Mc(w,l,h,a),c=w|0,{Dh:g,Dl:p}={Dh:g^l,Dl:p^c},{Dh:g,Dl:p}={Dh:Or(g,p,16),Dl:Dr(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*r]=f,V[2*r+1]=d,V[2*i]=p,V[2*i+1]=g}function _x(t,e={},r,i,n){if(fr(r),t<0||t>r)throw new Error("outputLen bigger than keyLen");const{key:s,salt:o,personalization:a}=e;if(s!==void 0&&(s.length<1||s.length>r))throw new Error("key length must be undefined or 1.."+r);if(o!==void 0&&o.length!==i)throw new Error("salt must be undefined or "+i);if(a!==void 0&&a.length!==n)throw new Error("personalization must be undefined or "+n)}class Ix extends Xs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,this.length=0,this.pos=0,fr(e),fr(r),this.blockLen=e,this.outputLen=r,this.buffer=new Uint8Array(e),this.buffer32=xn(this.buffer)}update(e){Ur(this),e=Bt(e),Tt(e);const{blockLen:r,buffer:i,buffer32:n}=this,s=e.length,o=e.byteOffset,a=e.buffer;for(let c=0;c<s;){this.pos===r&&(Ar(n),this.compress(n,0,!1),Ar(n),this.pos=0);const l=Math.min(r-this.pos,s-c),u=o+c;if(l===r&&!(u%4)&&c+l<s){const h=new Uint32Array(a,u,Math.floor((s-c)/4));Ar(h);for(let f=0;c+r<s;f+=n.length,c+=r)this.length+=r,this.compress(h,f,!1);Ar(h);continue}i.set(e.subarray(c,c+l),this.pos),this.pos+=l,this.length+=l,c+=l}return this}digestInto(e){Ur(this),qc(e,this);const{pos:r,buffer32:i}=this;this.finished=!0,It(this.buffer.subarray(r)),Ar(i),this.compress(i,0,!0),Ar(i);const n=xn(e);this.get().forEach((s,o)=>n[o]=rr(s))}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}_cloneInto(e){const{buffer:r,length:i,finished:n,destroyed:s,outputLen:o,pos:a}=this;return e||(e=new this.constructor({dkLen:o})),e.set(...this.get()),e.buffer.set(r),e.destroyed=s,e.finished=n,e.length=i,e.pos=a,e.outputLen=o,e}clone(){return this._cloneInto()}}class Sx extends Ix{constructor(e={}){const r=e.dkLen===void 0?64:e.dkLen;super(128,r),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,_x(r,e,64,16,16);let{key:i,personalization:n,salt:s}=e,o=0;if(i!==void 0&&(i=Bt(i),o=i.length),this.v0l^=this.outputLen|o<<8|65536|1<<24,s!==void 0){s=Bt(s);const a=xn(s);this.v4l^=rr(a[0]),this.v4h^=rr(a[1]),this.v5l^=rr(a[2]),this.v5h^=rr(a[3])}if(n!==void 0){n=Bt(n);const a=xn(n);this.v6l^=rr(a[0]),this.v6h^=rr(a[1]),this.v7l^=rr(a[2]),this.v7h^=rr(a[3])}if(i!==void 0){const a=new Uint8Array(this.blockLen);a.set(i),this.update(a)}}get(){let{v0l:e,v0h:r,v1l:i,v1h: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,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w]}set(e,r,i,n,s,o,a,c,l,u,h,f,d,p,g,w){this.v0l=e|0,this.v0h=r|0,this.v1l=i|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,r,i){this.get().forEach((c,l)=>V[l]=c),V.set(Ee,16);let{h:n,l:s}=Rp(BigInt(this.length));V[24]=Ee[8]^s,V[25]=Ee[9]^n,i&&(V[28]=~V[28],V[29]=~V[29]);let o=0;const a=xx;for(let c=0;c<12;c++)Sr(0,4,8,12,e,r+2*a[o++]),$r(0,4,8,12,e,r+2*a[o++]),Sr(1,5,9,13,e,r+2*a[o++]),$r(1,5,9,13,e,r+2*a[o++]),Sr(2,6,10,14,e,r+2*a[o++]),$r(2,6,10,14,e,r+2*a[o++]),Sr(3,7,11,15,e,r+2*a[o++]),$r(3,7,11,15,e,r+2*a[o++]),Sr(0,5,10,15,e,r+2*a[o++]),$r(0,5,10,15,e,r+2*a[o++]),Sr(1,6,11,12,e,r+2*a[o++]),$r(1,6,11,12,e,r+2*a[o++]),Sr(2,7,8,13,e,r+2*a[o++]),$r(2,7,8,13,e,r+2*a[o++]),Sr(3,4,9,14,e,r+2*a[o++]),$r(3,4,9,14,e,r+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],It(V)}destroy(){this.destroyed=!0,It(this.buffer32),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}const $x=X3(t=>new Sx(t)),Ox="https://rpc.walletconnect.org/v1";function Wp(t){const e=`Ethereum Signed Message:
|
|
18
|
+
${t.length}`,r=new TextEncoder().encode(e+t);return"0x"+re.from(lx(r)).toString("hex")}async function Dx(t,e,r,i,n,s){switch(r.t){case"eip191":return await Ax(t,e,r.s);case"eip1271":return await Px(t,e,r.s,i,n,s);default:throw new Error(`verifySignature failed: Attempted to verify CacaoSignature with unknown type: ${r.t}`)}}function Ax(t,e,r){const i=_m(r);return Nm({payload:Wp(e),signature:i}).toLowerCase()===t.toLowerCase()}async function Px(t,e,r,i,n,s){const o=ur(i);if(!o.namespace||!o.reference)throw new Error(`isValidEip1271Signature failed: chainId must be in CAIP-2 format, received: ${i}`);try{const a="0x1626ba7e",c="0000000000000000000000000000000000000000000000000000000000000040",l=r.substring(2),u=(l.length/2).toString(16).padStart(64,"0"),h=(e.startsWith("0x")?e:Wp(e)).substring(2),f=a+h+c+u+l,d=await fetch(`${s||Ox}/?chainId=${i}&projectId=${n}`,{headers:{"Content-Type":"application/json"},method:"POST",body:JSON.stringify({id:Cx(),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 Cx(){return Date.now()+Math.floor(Math.random()*1e3)}function Bx(t){const e=atob(t),r=new Uint8Array(e.length);for(let o=0;o<e.length;o++)r[o]=e.charCodeAt(o);const i=r[0];if(i===0)throw new Error("No signatures found");const n=1+i*64;if(r.length<n)throw new Error("Transaction data too short for claimed signature count");if(r.length<100)throw new Error("Transaction too short");const s=re.from(t,"base64").slice(1,65);return An.encode(s)}function Tx(t){const e=new Uint8Array(re.from(t,"base64")),r=Array.from("TransactionData::").map(s=>s.charCodeAt(0)),i=new Uint8Array(r.length+e.length);i.set(r),i.set(e,r.length);const n=$x(i,{dkLen:32});return An.encode(n)}function Uu(t){const e=new Uint8Array(Qs(Rx(t)));return An.encode(e)}function Rx(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 ku(t){const e=re.from(t,"base64"),r=E1(e).txn;if(!r)throw new Error("Invalid signed transaction: missing 'txn' field");const i=f1(r),n=re.from("TX"),s=re.concat([n,re.from(i)]),o=Ex(s);return Fm.encode(o).replace(/=+$/,"")}function Mo(t){const e=[];let r=BigInt(t);for(;r>=BigInt(128);)e.push(Number(r&BigInt(127)|BigInt(128))),r>>=BigInt(7);return e.push(Number(r)),re.from(e)}function Fx(t){const e=re.from(t.signed.bodyBytes,"base64"),r=re.from(t.signed.authInfoBytes,"base64"),i=re.from(t.signature.signature,"base64"),n=[];n.push(re.from([10])),n.push(Mo(e.length)),n.push(e),n.push(re.from([18])),n.push(Mo(r.length)),n.push(r),n.push(re.from([26])),n.push(Mo(i.length)),n.push(i);const s=re.concat(n),o=Qs(s);return re.from(o).toString("hex").toUpperCase()}function Nx(t){var e,r;const i=[];try{if(typeof t=="string")return i.push(t),i;if(typeof t!="object")return i;t!=null&&t.id&&i.push(t.id);const n=(r=(e=t==null?void 0:t.capabilities)==null?void 0:e.caip345)==null?void 0:r.transactionHashes;n&&i.push(...n)}catch(n){console.warn("getWalletSendCallsHashes failed: ",n)}return i}var Ux=Object.defineProperty,kx=Object.defineProperties,jx=Object.getOwnPropertyDescriptors,ju=Object.getOwnPropertySymbols,Lx=Object.prototype.hasOwnProperty,Mx=Object.prototype.propertyIsEnumerable,Lu=(t,e,r)=>e in t?Ux(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,qx=(t,e)=>{for(var r in e||(e={}))Lx.call(e,r)&&Lu(t,r,e[r]);if(ju)for(var r of ju(e))Mx.call(e,r)&&Lu(t,r,e[r]);return t},zx=(t,e)=>kx(t,jx(e));const Gp="did:pkh:",Vx={eip155:"Ethereum",solana:"Solana",bip122:"Bitcoin"},Hx=t=>t?Vx[t]||t:"",eo=t=>t==null?void 0:t.split(":"),Kx=t=>{const e=t&&eo(t);if(e)return t.includes(Gp)?e[3]:e[1]},Wx=t=>{const e=t&&eo(t);if(e)return t.includes(Gp)?e[2]:e[0]},Na=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 Mu(t){const{cacao:e,projectId:r}=t,{s:i,p:n}=e,s=Yp(n,n.iss),o=Cs(n.iss);return await Dx(o,s,i,Na(n.iss),r)}const Yp=(t,e)=>{const r=Wx(e);if(!r)throw new Error("Invalid issuer: "+e);const i=`${t.domain} wants you to sign in with your ${Hx(r)} 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: ${Kx(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=_n(g);s=r_(s,w)}return[i,n,"",s,"",o,a,c,l,u,h,f,d,p].filter(w=>w!=null).join(`
|
|
20
|
+
`)};function Gx(t){return re.from(JSON.stringify(t)).toString("base64")}function Yx(t){return JSON.parse(re.from(t,"base64").toString("utf-8"))}function ai(t){if(!t)throw new Error("No recap provided, value is undefined");if(!t.att)throw new Error("No `att` property found");const e=Object.keys(t.att);if(!(e!=null&&e.length))throw new Error("No resources found in `att` property");e.forEach(r=>{const i=t.att[r];if(Array.isArray(i))throw new Error(`Resource must be an object: ${r}`);if(typeof i!="object")throw new Error(`Resource must be an object: ${r}`);if(!Object.keys(i).length)throw new Error(`Resource object is empty: ${r}`);Object.keys(i).forEach(n=>{const s=i[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 Zx(t,e,r,i={}){return r==null||r.sort((n,s)=>n.localeCompare(s)),{att:{[t]:Jx(e,r,i)}}}function Jx(t,e,r={}){e=e==null?void 0:e.sort((n,s)=>n.localeCompare(s));const i=e.map(n=>({[`${t}/${n}`]:[r]}));return Object.assign({},...i)}function Zp(t){return ai(t),`urn:recap:${Gx(t).replace(/=/g,"")}`}function _n(t){const e=Yx(t.replace("urn:recap:",""));return ai(e),e}function Xx(t,e,r){const i=Zx(t,e,r);return Zp(i)}function Qx(t){return t&&t.includes("urn:recap:")}function e_(t,e){const r=_n(t),i=_n(e),n=t_(r,i);return Zp(n)}function t_(t,e){ai(t),ai(e);const r=Object.keys(t.att).concat(Object.keys(e.att)).sort((n,s)=>n.localeCompare(s)),i={att:{}};return r.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;i.att[n]=zx(qx({},i.att[n]),{[a]:((c=t.att[n])==null?void 0:c[a])||((l=e.att[n])==null?void 0:l[a])})})}),i}function r_(t="",e){ai(e);const r="I further authorize the stated URI to perform the following actions on my behalf: ";if(t.includes(r))return t;const i=[];let 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}'.`));i.push(u.join(", ").replace(".,","."))});const s=i.join(" "),o=`${r}${s}`;return`${t?t+" ":""}${o}`}function qu(t){var e;const r=_n(t);ai(r);const i=(e=r.att)==null?void 0:e.eip155;return i?Object.keys(i).map(n=>n.split("/")[1]):[]}function zu(t){const e=_n(t);ai(e);const r=[];return Object.values(e.att).forEach(i=>{Object.values(i).forEach(n=>{var s;(s=n==null?void 0:n[0])!=null&&s.chains&&r.push(n[0].chains)})}),[...new Set(r.flat())]}function fs(t){if(!t)return;const e=t==null?void 0:t[t.length-1];return Qx(e)?e:void 0}/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */function Jp(t){return t instanceof Uint8Array||ArrayBuffer.isView(t)&&t.constructor.name==="Uint8Array"}function Ua(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(!Jp(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 Vu(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 i_(t,e){et(t);const r=e.outputLen;if(t.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function Fr(t){return new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4))}function Ui(...t){for(let e=0;e<t.length;e++)t[e].fill(0)}function n_(t){return new DataView(t.buffer,t.byteOffset,t.byteLength)}const s_=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function o_(t){if(typeof t!="string")throw new Error("string expected");return new Uint8Array(new TextEncoder().encode(t))}function ka(t){if(typeof t=="string")t=o_(t);else if(Jp(t))t=ja(t);else throw new Error("Uint8Array expected, got "+typeof t);return t}function a_(t,e){if(e==null||typeof e!="object")throw new Error("options must be defined");return Object.assign(t,e)}function c_(t,e){if(t.length!==e.length)return!1;let r=0;for(let i=0;i<t.length;i++)r|=t[i]^e[i];return r===0}const l_=(t,e)=>{function r(i,...n){if(et(i),!s_)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(i,...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(r,t),r};function Hu(t,e,r=!0){if(e===void 0)return new Uint8Array(t);if(e.length!==t)throw new Error("invalid output length, expected "+t+", got: "+e.length);if(r&&!h_(e))throw new Error("invalid output, must be aligned");return e}function Ku(t,e,r,i){if(typeof t.setBigUint64=="function")return t.setBigUint64(e,r,i);const n=BigInt(32),s=BigInt(4294967295),o=Number(r>>n&s),a=Number(r&s),c=i?4:0,l=i?0:4;t.setUint32(e+c,o,i),t.setUint32(e+l,a,i)}function u_(t,e,r){Ua(r);const i=new Uint8Array(16),n=n_(i);return Ku(n,0,BigInt(e),r),Ku(n,8,BigInt(t),r),i}function h_(t){return t.byteOffset%4===0}function ja(t){return Uint8Array.from(t)}const Xp=t=>Uint8Array.from(t.split("").map(e=>e.charCodeAt(0))),f_=Xp("expand 16-byte k"),d_=Xp("expand 32-byte k"),p_=Fr(f_),g_=Fr(d_);function ie(t,e){return t<<e|t>>>32-e}function La(t){return t.byteOffset%4===0}const Xn=64,y_=16,Qp=2**32-1,Wu=new Uint32Array;function w_(t,e,r,i,n,s,o,a){const c=n.length,l=new Uint8Array(Xn),u=Fr(l),h=La(n)&&La(s),f=h?Fr(n):Wu,d=h?Fr(s):Wu;for(let p=0;p<c;o++){if(t(e,r,i,u,o,a),o>=Qp)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 I=0,C;I<y_;I++)C=w+I,d[C]=f[C]^u[I];p+=Xn;continue}for(let w=0,I;w<g;w++)I=p+w,s[I]=n[I]^l[w];p+=g}}function m_(t,e){const{allowShortKeys:r,extendNonceFn:i,counterLength:n,counterRight:s,rounds:o}=a_({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),Ua(s),Ua(r),(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>=Qp)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=ja(a)),w=g_;else if(p===16&&r)g=new Uint8Array(32),g.set(a),g.set(a,16),w=p_,d.push(g);else throw new Error(`arx: invalid 32-byte key, got length=${p}`);La(c)||d.push(c=ja(c));const I=Fr(g);if(i){if(c.length!==24)throw new Error("arx: extended nonce must be 24 bytes");i(w,I,Fr(c.subarray(0,16)),I),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=Fr(c);return w_(t,w,I,b,l,u,h,o),Ui(...d),u}}const Ce=(t,e)=>t[e++]&255|(t[e++]&255)<<8;class b_{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=ka(e),et(e,32);const r=Ce(e,0),i=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]=r&8191,this.r[1]=(r>>>13|i<<3)&8191,this.r[2]=(i>>>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,r,i=!1){const n=i?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],I=Ce(e,r+0),C=Ce(e,r+2),b=Ce(e,r+4),v=Ce(e,r+6),D=Ce(e,r+8),P=Ce(e,r+10),T=Ce(e,r+12),R=Ce(e,r+14);let A=s[0]+(I&8191),U=s[1]+((I>>>13|C<<3)&8191),j=s[2]+((C>>>10|b<<6)&8191),B=s[3]+((b>>>7|v<<9)&8191),_=s[4]+((v>>>4|D<<12)&8191),O=s[5]+(D>>>1&8191),m=s[6]+((D>>>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)+_*(5*d);E=S>>>13,S&=8191,S+=O*(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)+_*(5*p);E=F>>>13,F&=8191,F+=O*(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)+_*(5*g);E=N>>>13,N&=8191,N+=O*(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+_*(5*w);E=H>>>13,H&=8191,H+=O*(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+_*a;E=z>>>13,z&=8191,z+=O*(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+_*c;E=q>>>13,q&=8191,q+=O*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+_*l;E=K>>>13,K&=8191,K+=O*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+_*u;E=G>>>13,G&=8191,G+=O*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+_*h;E=X>>>13,X&=8191,X+=O*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+_*f;E=W>>>13,W&=8191,W+=O*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:r}=this,i=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,i[0]=e[0]+5,n=i[0]>>>13,i[0]&=8191;for(let a=1;a<10;a++)i[a]=e[a]+n,n=i[a]>>>13,i[a]&=8191;i[9]-=8192;let s=(n^1)-1;for(let a=0;a<10;a++)i[a]&=s;s=~s;for(let a=0;a<10;a++)e[a]=e[a]&s|i[a];e[0]=(e[0]|e[1]<<13)&65535,e[1]=(e[1]>>>3|e[2]<<10)&65535,e[2]=(e[2]>>>6|e[3]<<7)&65535,e[3]=(e[3]>>>9|e[4]<<4)&65535,e[4]=(e[4]>>>12|e[5]<<1|e[6]<<14)&65535,e[5]=(e[6]>>>2|e[7]<<11)&65535,e[6]=(e[7]>>>5|e[8]<<8)&65535,e[7]=(e[8]>>>8|e[9]<<5)&65535;let o=e[0]+r[0];e[0]=o&65535;for(let a=1;a<8;a++)o=(e[a]+r[a]|0)+(o>>>16)|0,e[a]=o&65535;Ui(i)}update(e){Vu(this),e=ka(e),et(e);const{buffer:r,blockLen:i}=this,n=e.length;for(let s=0;s<n;){const o=Math.min(i-this.pos,n-s);if(o===i){for(;i<=n-s;s+=i)this.process(e,s);continue}r.set(e.subarray(s,s+o),this.pos),this.pos+=o,s+=o,this.pos===i&&(this.process(r,0,!1),this.pos=0)}return this}destroy(){Ui(this.h,this.r,this.buffer,this.pad)}digestInto(e){Vu(this),i_(e,this),this.finished=!0;const{buffer:r,h:i}=this;let{pos:n}=this;if(n){for(r[n++]=1;n<16;n++)r[n]=0;this.process(r,0,!0)}this.finalize();let s=0;for(let o=0;o<8;o++)e[s++]=i[o]>>>0,e[s++]=i[o]>>>8;return e}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const i=e.slice(0,r);return this.destroy(),i}}function v_(t){const e=(i,n)=>t(n).update(ka(i)).digest(),r=t(new Uint8Array(32));return e.outputLen=r.outputLen,e.blockLen=r.blockLen,e.create=i=>t(i),e}const E_=v_(t=>new b_(t));function x_(t,e,r,i,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],I=e[7],C=n,b=r[0],v=r[1],D=r[2],P=o,T=a,R=c,A=l,U=u,j=h,B=f,_=d,O=p,m=g,y=w,x=I,$=C,E=b,S=v,F=D;for(let H=0;H<s;H+=2)P=P+U|0,$=ie($^P,16),O=O+$|0,U=ie(U^O,12),P=P+U|0,$=ie($^P,8),O=O+$|0,U=ie(U^O,7),T=T+j|0,E=ie(E^T,16),m=m+E|0,j=ie(j^m,12),T=T+j|0,E=ie(E^T,8),m=m+E|0,j=ie(j^m,7),R=R+B|0,S=ie(S^R,16),y=y+S|0,B=ie(B^y,12),R=R+B|0,S=ie(S^R,8),y=y+S|0,B=ie(B^y,7),A=A+_|0,F=ie(F^A,16),x=x+F|0,_=ie(_^x,12),A=A+_|0,F=ie(F^A,8),x=x+F|0,_=ie(_^x,7),P=P+j|0,F=ie(F^P,16),y=y+F|0,j=ie(j^y,12),P=P+j|0,F=ie(F^P,8),y=y+F|0,j=ie(j^y,7),T=T+B|0,$=ie($^T,16),x=x+$|0,B=ie(B^x,12),T=T+B|0,$=ie($^T,8),x=x+$|0,B=ie(B^x,7),R=R+_|0,E=ie(E^R,16),O=O+E|0,_=ie(_^O,12),R=R+_|0,E=ie(E^R,8),O=O+E|0,_=ie(_^O,7),A=A+U|0,S=ie(S^A,16),m=m+S|0,U=ie(U^m,12),A=A+U|0,S=ie(S^A,8),m=m+S|0,U=ie(U^m,7);let N=0;i[N++]=o+P|0,i[N++]=a+T|0,i[N++]=c+R|0,i[N++]=l+A|0,i[N++]=u+U|0,i[N++]=h+j|0,i[N++]=f+B|0,i[N++]=d+_|0,i[N++]=p+O|0,i[N++]=g+m|0,i[N++]=w+y|0,i[N++]=I+x|0,i[N++]=C+$|0,i[N++]=b+E|0,i[N++]=v+S|0,i[N++]=D+F|0}const __=m_(x_,{counterRight:!1,counterLength:4,allowShortKeys:!1}),I_=new Uint8Array(16),Gu=(t,e)=>{t.update(e);const r=e.length%16;r&&t.update(I_.subarray(r))},S_=new Uint8Array(32);function Yu(t,e,r,i,n){const s=t(e,r,S_),o=E_.create(s);n&&Gu(o,n),Gu(o,i);const a=u_(i.length,n?n.length:0,!0);o.update(a);const c=o.digest();return Ui(s,a),c}const $_=t=>(e,r,i)=>({encrypt(n,s){const o=n.length;s=Hu(o+16,s,!1),s.set(n);const a=s.subarray(0,-16);t(e,r,a,a,1);const c=Yu(t,e,r,a,i);return s.set(c,o),Ui(c),s},decrypt(n,s){s=Hu(n.length-16,s,!1);const o=n.subarray(0,-16),a=n.subarray(-16),c=Yu(t,e,r,o,i);if(!c_(a,c))throw new Error("invalid tag");return s.set(n.subarray(0,-16)),t(e,r,s,s,1),Ui(c),s}}),eg=l_({blockSize:64,nonceLength:12,tagLength:16},$_(__));let tg=class extends Xs{constructor(e,r){super(),this.finished=!1,this.destroyed=!1,Js(e);const i=Bt(r);if(this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const n=this.blockLen,s=new Uint8Array(n);s.set(i.length>n?e.create().update(i).digest():i);for(let o=0;o<s.length;o++)s[o]^=54;this.iHash.update(s),this.oHash=e.create();for(let o=0;o<s.length;o++)s[o]^=106;this.oHash.update(s),It(s)}update(e){return Ur(this),this.iHash.update(e),this}digestInto(e){Ur(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:r,iHash:i,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=r._cloneInto(e.oHash),e.iHash=i._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}};const to=(t,e,r)=>new tg(t,e).update(r).digest();to.create=(t,e)=>new tg(t,e);function O_(t,e,r){return Js(t),r===void 0&&(r=new Uint8Array(t.outputLen)),to(t,Bt(r),Bt(e))}const zo=Uint8Array.from([0]),Zu=Uint8Array.of();function D_(t,e,r,i=32){Js(t),fr(i);const n=t.outputLen;if(i>255*n)throw new Error("Length should be <= 255*HashLen");const s=Math.ceil(i/n);r===void 0&&(r=Zu);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?Zu:l).update(r).update(zo).digestInto(l),o.set(l,n*u),a._cloneInto(c);return a.destroy(),c.destroy(),It(l,zo),o.slice(0,i)}const A_=(t,e,r,i,n)=>D_(t,O_(t,e,r),i,n),ro=Qs,Vc=BigInt(0),Ma=BigInt(1);function Bs(t,e=""){if(typeof t!="boolean"){const r=e&&`"${e}"`;throw new Error(r+"expected boolean, got type="+typeof t)}return t}function Qr(t,e,r=""){const i=Zs(t),n=t==null?void 0:t.length,s=e!==void 0;if(!i||s&&n!==e){const o=r&&`"${r}" `,a=s?` of length ${e}`:"",c=i?`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 rg(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);return t===""?Vc:BigInt("0x"+t)}function io(t){return rg(Ci(t))}function Ts(t){return Tt(t),rg(Ci(Uint8Array.from(t).reverse()))}function Hc(t,e){return Ps(t.toString(16).padStart(e*2,"0"))}function Kc(t,e){return Hc(t,e).reverse()}function Ve(t,e,r){let i;if(typeof e=="string")try{i=Ps(e)}catch(s){throw new Error(t+" must be hex string or Uint8Array, cause: "+s)}else if(Zs(e))i=Uint8Array.from(e);else throw new Error(t+" must be hex string or Uint8Array");const n=i.length;if(typeof r=="number"&&n!==r)throw new Error(t+" of length "+r+" expected, got "+n);return i}const Vo=t=>typeof t=="bigint"&&Vc<=t;function P_(t,e,r){return Vo(t)&&Vo(e)&&Vo(r)&&e<=t&&t<r}function qa(t,e,r,i){if(!P_(e,r,i))throw new Error("expected valid "+t+": "+r+" <= n < "+i+", got "+e)}function ig(t){let e;for(e=0;t>Vc;t>>=Ma,e+=1);return e}const Rn=t=>(Ma<<BigInt(t))-Ma;function C_(t,e,r){if(typeof t!="number"||t<2)throw new Error("hashLen must be a number");if(typeof e!="number"||e<2)throw new Error("qByteLen must be a number");if(typeof r!="function")throw new Error("hmacFn must be a function");const i=f=>new Uint8Array(f),n=f=>Uint8Array.of(f);let s=i(t),o=i(t),a=0;const c=()=>{s.fill(1),o.fill(0),a=0},l=(...f)=>r(o,s,...f),u=(f=i(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 Cr(...d)};return(f,d)=>{c(),u(f);let p;for(;!(p=d(h()));)u();return c(),p}}function no(t,e,r={}){if(!t||typeof t!="object")throw new Error("expected valid options object");function i(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])=>i(n,s,!1)),Object.entries(r).forEach(([n,s])=>i(n,s,!0))}function Ju(t){const e=new WeakMap;return(r,...i)=>{const n=e.get(r);if(n!==void 0)return n;const s=t(r,...i);return e.set(r,s),s}}const it=BigInt(0),We=BigInt(1),ei=BigInt(2),ng=BigInt(3),sg=BigInt(4),og=BigInt(5),B_=BigInt(7),ag=BigInt(8),T_=BigInt(9),cg=BigInt(16);function ht(t,e){const r=t%e;return r>=it?r:e+r}function At(t,e,r){let i=t;for(;e-- >it;)i*=i,i%=r;return i}function Xu(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 r=ht(t,e),i=e,n=it,s=We;for(;r!==it;){const o=i/r,a=i%r,c=n-s*o;i=r,r=a,n=s,s=c}if(i!==We)throw new Error("invert: does not exist");return ht(n,e)}function Wc(t,e,r){if(!t.eql(t.sqr(e),r))throw new Error("Cannot find square root")}function lg(t,e){const r=(t.ORDER+We)/sg,i=t.pow(e,r);return Wc(t,i,e),i}function R_(t,e){const r=(t.ORDER-og)/ag,i=t.mul(e,ei),n=t.pow(i,r),s=t.mul(e,n),o=t.mul(t.mul(s,ei),n),a=t.mul(s,t.sub(o,t.ONE));return Wc(t,a,e),a}function F_(t){const e=jr(t),r=ug(t),i=r(e,e.neg(e.ONE)),n=r(e,i),s=r(e,e.neg(i)),o=(t+B_)/cg;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,i);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 Wc(a,w,c),w}}function ug(t){if(t<ng)throw new Error("sqrt is not defined for small field");let e=t-We,r=0;for(;e%ei===it;)e/=ei,r++;let i=ei;const n=jr(t);for(;Qu(n,i)===1;)if(i++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return lg;let s=n.pow(i,e);const o=(e+We)/ei;return function(a,c){if(a.is0(c))return c;if(Qu(a,c)!==1)throw new Error("Cannot find square root");let l=r,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 N_(t){return t%sg===ng?lg:t%ag===og?R_:t%cg===T_?F_(t):ug(t)}const U_=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function k_(t){const e={ORDER:"bigint",MASK:"bigint",BYTES:"number",BITS:"number"},r=U_.reduce((i,n)=>(i[n]="function",i),e);return no(t,r),t}function j_(t,e,r){if(r<it)throw new Error("invalid exponent, negatives unsupported");if(r===it)return t.ONE;if(r===We)return e;let i=t.ONE,n=e;for(;r>it;)r&We&&(i=t.mul(i,n)),n=t.sqr(n),r>>=We;return i}function hg(t,e,r=!1){const i=new Array(e.length).fill(r?t.ZERO:void 0),n=e.reduce((o,a,c)=>t.is0(a)?o:(i[c]=o,t.mul(o,a)),t.ONE),s=t.inv(n);return e.reduceRight((o,a,c)=>t.is0(a)?o:(i[c]=t.mul(o,i[c]),t.mul(o,a)),s),i}function Qu(t,e){const r=(t.ORDER-We)/ei,i=t.pow(e,r),n=t.eql(i,t.ONE),s=t.eql(i,t.ZERO),o=t.eql(i,t.neg(t.ONE));if(!n&&!s&&!o)throw new Error("invalid Legendre symbol result");return n?1:s?0:-1}function fg(t,e){e!==void 0&&fr(e);const r=e!==void 0?e:t.toString(2).length,i=Math.ceil(r/8);return{nBitLength:r,nByteLength:i}}function jr(t,e,r=!1,i={}){if(t<=it)throw new Error("invalid field: expected ORDER > 0, got "+t);let n,s,o=!1,a;if(typeof e=="object"&&e!=null){if(i.sqrt||r)throw new Error("cannot specify opts in two arguments");const f=e;f.BITS&&(n=f.BITS),f.sqrt&&(s=f.sqrt),typeof f.isLE=="boolean"&&(r=f.isLE),typeof f.modFromBytes=="boolean"&&(o=f.modFromBytes),a=f.allowedLengths}else typeof e=="number"&&(n=e),i.sqrt&&(s=i.sqrt);const{nBitLength:c,nByteLength:l}=fg(t,n);if(l>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");let u;const h=Object.freeze({ORDER:t,isLE:r,BITS:c,BYTES:l,MASK:Rn(c),ZERO:it,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 it<=f&&f<t},is0:f=>f===it,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)=>j_(h,f,d),div:(f,d)=>ht(f*Xu(d,t),t),sqrN:f=>f*f,addN:(f,d)=>f+d,subN:(f,d)=>f-d,mulN:(f,d)=>f*d,inv:f=>Xu(f,t),sqrt:s||(f=>(u||(u=N_(t)),u(h,f))),toBytes:f=>r?Kc(f,l):Hc(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,r?0:g.length-f.length),f=g}if(f.length!==l)throw new Error("Field.fromBytes: expected "+l+" bytes, got "+f.length);let p=r?Ts(f):io(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=>hg(h,f),cmov:(f,d,p)=>p?d:f});return Object.freeze(h)}function dg(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 pg(t){const e=dg(t);return e+Math.ceil(e/2)}function L_(t,e,r=!1){const i=t.length,n=dg(e),s=pg(e);if(i<16||i<s||i>1024)throw new Error("expected "+s+"-1024 bytes of input, got "+i);const o=r?Ts(t):io(t),a=ht(o,e-We)+We;return r?Kc(a,n):Hc(a,n)}const ki=BigInt(0),ti=BigInt(1);function Rs(t,e){const r=e.negate();return t?r:e}function Ho(t,e){const r=hg(t.Fp,e.map(i=>i.Z));return e.map((i,n)=>t.fromAffine(i.toAffine(r[n])))}function gg(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){gg(t,e);const r=Math.ceil(e/t)+1,i=2**(t-1),n=2**t,s=Rn(t),o=BigInt(t);return{windows:r,windowSize:i,mask:s,maxNumber:n,shiftBy:o}}function eh(t,e,r){const{windowSize:i,mask:n,maxNumber:s,shiftBy:o}=r;let a=Number(t&n),c=t>>o;a>i&&(a-=s,c+=ti);const l=e*i,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 M_(t,e){if(!Array.isArray(t))throw new Error("array expected");t.forEach((r,i)=>{if(!(r instanceof e))throw new Error("invalid point at index "+i)})}function q_(t,e){if(!Array.isArray(t))throw new Error("array of scalars expected");t.forEach((r,i)=>{if(!e.isValid(r))throw new Error("invalid scalar at index "+i)})}const Wo=new WeakMap,yg=new WeakMap;function Go(t){return yg.get(t)||1}function th(t){if(t!==ki)throw new Error("invalid wNAF")}class z_{constructor(e,r){this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,i=this.ZERO){let n=e;for(;r>ki;)r&ti&&(i=i.add(n)),n=n.double(),r>>=ti;return i}precomputeWindow(e,r){const{windows:i,windowSize:n}=Ko(r,this.bits),s=[];let o=e,a=o;for(let c=0;c<i;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,r,i){if(!this.Fn.isValid(i))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}=eh(i,a,o);i=c,u?s=s.add(Rs(f,r[d])):n=n.add(Rs(h,r[l]))}return th(i),{p:n,f:s}}wNAFUnsafe(e,r,i,n=this.ZERO){const s=Ko(e,this.bits);for(let o=0;o<s.windows&&i!==ki;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=eh(i,o,s);if(i=a,!l){const h=r[c];n=n.add(u?h.negate():h)}}return th(i),n}getPrecomputes(e,r,i){let n=Wo.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof i=="function"&&(n=i(n)),Wo.set(r,n))),n}cached(e,r,i){const n=Go(e);return this.wNAF(n,this.getPrecomputes(n,e,i),r)}unsafe(e,r,i,n){const s=Go(e);return s===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(s,this.getPrecomputes(s,e,i),r,n)}createCache(e,r){gg(r,this.bits),yg.set(e,r),Wo.delete(e)}hasCache(e){return Go(e)!==1}}function V_(t,e,r,i){let n=e,s=t.ZERO,o=t.ZERO;for(;r>ki||i>ki;)r&ti&&(s=s.add(n)),i&ti&&(o=o.add(n)),n=n.double(),r>>=ti,i>>=ti;return{p1:s,p2:o}}function H_(t,e,r,i){M_(r,t),q_(i,e);const n=r.length,s=i.length;if(n!==s)throw new Error("arrays of points and scalars must have equal length");const o=t.ZERO,a=ig(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=i[g],I=Number(w>>BigInt(d)&l);u[I]=u[I].add(r[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 rh(t,e,r){if(e){if(e.ORDER!==t)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return k_(e),e}else return jr(t,{isLE:r})}function K_(t,e,r={},i){if(i===void 0&&(i=t==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${t} CURVE object`);for(const a of["p","n","h"]){const c=e[a];if(!(typeof c=="bigint"&&c>ki))throw new Error(`CURVE.${a} must be positive bigint`)}const n=rh(e.p,r.Fp,i),s=rh(e.n,r.Fn,i),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),jp("HashToScalar-");const Xi=BigInt(0),vi=BigInt(1),es=BigInt(2);function W_(t){return no(t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze({...t})}function G_(t){const e=W_(t),{P:r,type:i,adjustScalarBytes:n,powPminus2:s,randomBytes:o}=e,a=i==="x25519";if(!a&&i!=="x448")throw new Error("invalid type");const c=o||ui,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)-vi:BigInt(4)*es**BigInt(445)-vi,g=d+p+vi,w=B=>ht(B,r),I=C(h);function C(B){return Kc(w(B),u)}function b(B){const _=Ve("u coordinate",B,u);return a&&(_[31]&=127),w(Ts(_))}function v(B){return Ts(n(Ve("scalar",B,u)))}function D(B,_){const O=R(b(_),v(B));if(O===Xi)throw new Error("invalid private or public key received");return C(O)}function P(B){return D(B,I)}function T(B,_,O){const m=w(B*(_-O));return _=w(_-m),O=w(O+m),{x_2:_,x_3:O}}function R(B,_){qa("u",B,Xi,r),qa("scalar",_,d,g);const O=_,m=B;let y=vi,x=Xi,$=B,E=vi,S=Xi;for(let N=BigInt(l-1);N>=Xi;N--){const H=O>>N&vi;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),Ie=pe+ve,He=pe-ve;$=w(Ie*Ie),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 _=U(B);return{secretKey:_,publicKey:P(_)}}return{keygen:j,getSharedSecret:(B,_)=>D(B,_),getPublicKey:B=>P(B),scalarMult:D,scalarMultBase:P,utils:{randomSecretKey:U,randomPrivateKey:U},GuBytes:I.slice(),lengths:A}}const Y_=BigInt(1),ih=BigInt(2),Z_=BigInt(3),J_=BigInt(5),X_=BigInt(8),wg=BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffed"),Q_={p:wg,n:BigInt("0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3ed"),h:X_,a:BigInt("0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffec"),d:BigInt("0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3"),Gx:BigInt("0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a"),Gy:BigInt("0x6666666666666666666666666666666666666666666666666666666666666658")};function eI(t){const e=BigInt(10),r=BigInt(20),i=BigInt(40),n=BigInt(80),s=wg,o=t*t%s*t%s,a=At(o,ih,s)*o%s,c=At(a,Y_,s)*t%s,l=At(c,J_,s)*c%s,u=At(l,e,s)*l%s,h=At(u,r,s)*u%s,f=At(h,i,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,ih,s)*t%s,b2:o}}function tI(t){return t[0]&=248,t[31]&=127,t[31]|=64,t}const rI=jr(Q_.p,{isLE:!0}),za=(()=>{const t=rI.ORDER;return G_({P:t,type:"x25519",powPminus2:e=>{const{pow_p_5_8:r,b2:i}=eI(e);return ht(At(r,Z_,t)*i,t)},adjustScalarBytes:tI})})(),nh=(t,e)=>(t+(t>=0?e:-e)/mg)/e;function iI(t,e,r){const[[i,n],[s,o]]=e,a=nh(o*t,r),c=nh(-n*t,r);let l=t-a*i-c*s,u=-a*n-c*o;const h=l<cr,f=u<cr;h&&(l=-l),f&&(u=-u);const d=Rn(Math.ceil(ig(r)/2))+Bi;if(l<cr||l>=d||u<cr||u>=d)throw new Error("splitScalar (endomorphism): failed, k="+t);return{k1neg:h,k1:l,k2neg:f,k2:u}}function Va(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 r={};for(let i of Object.keys(e))r[i]=t[i]===void 0?e[i]:t[i];return Bs(r.lowS,"lowS"),Bs(r.prehash,"prehash"),r.format!==void 0&&Va(r.format),r}class nI extends Error{constructor(e=""){super(e)}}const or={Err:nI,_tlv:{encode:(t,e)=>{const{Err:r}=or;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const i=e.length/2,n=Qn(i);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const s=i>127?Qn(n.length/2|128):"";return Qn(t)+s+n+e},decode(t,e){const{Err:r}=or;let i=0;if(t<0||t>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[i++]!==t)throw new r("tlv.decode: wrong tlv");const n=e[i++],s=!!(n&128);let o=0;if(!s)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(i,i+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(i+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(i,i+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(i+o)}}},_int:{encode(t){const{Err:e}=or;if(t<cr)throw new e("integer: negative integers are not allowed");let r=Qn(t);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(t){const{Err:e}=or;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 io(t)}},toSig(t){const{Err:e,_int:r,_tlv:i}=or,n=Ve("signature",t),{v:s,l:o}=i.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=i.decode(2,s),{v:l,l:u}=i.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(t){const{_tlv:e,_int:r}=or,i=e.encode(2,r.encode(t.r)),n=e.encode(2,r.encode(t.s)),s=i+n;return e.encode(48,s)}},cr=BigInt(0),Bi=BigInt(1),mg=BigInt(2),ts=BigInt(3),sI=BigInt(4);function Si(t,e){const{BYTES:r}=t;let i;if(typeof e=="bigint")i=e;else{let n=Ve("private key",e);try{i=t.fromBytes(n)}catch{throw new Error(`invalid private key: expected ui8a of size ${r}, got ${typeof e}`)}}if(!t.isValidNot0(i))throw new Error("invalid private key: out of range [1..N-1]");return i}function oI(t,e={}){const r=K_("weierstrass",t,e),{Fp:i,Fn:n}=r;let s=r.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&&(!i.is0(s.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=vg(i,n);function u(){if(!i.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function h(B,_,O){const{x:m,y}=_.toAffine(),x=i.toBytes(m);if(Bs(O,"isCompressed"),O){u();const $=!i.isOdd(y);return Cr(bg($),x)}else return Cr(Uint8Array.of(4),x,i.toBytes(y))}function f(B){Qr(B,void 0,"Point");const{publicKey:_,publicKeyUncompressed:O}=l,m=B.length,y=B[0],x=B.subarray(1);if(m===_&&(y===2||y===3)){const $=i.fromBytes(x);if(!i.isValid($))throw new Error("bad point: is not on curve, wrong x");const E=g($);let S;try{S=i.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=i.isOdd(S);return(y&1)===1!==F&&(S=i.neg(S)),{x:$,y:S}}else if(m===O&&y===4){const $=i.BYTES,E=i.fromBytes(x.subarray(0,$)),S=i.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=${_} or uncompressed=${O}`)}const d=e.toBytes||h,p=e.fromBytes||f;function g(B){const _=i.sqr(B),O=i.mul(_,B);return i.add(i.add(O,i.mul(B,s.a)),s.b)}function w(B,_){const O=i.sqr(_),m=g(B);return i.eql(O,m)}if(!w(s.Gx,s.Gy))throw new Error("bad curve params: generator point");const I=i.mul(i.pow(s.a,ts),sI),C=i.mul(i.sqr(s.b),BigInt(27));if(i.is0(i.add(I,C)))throw new Error("bad curve params: a or b");function b(B,_,O=!1){if(!i.isValid(_)||O&&i.is0(_))throw new Error(`bad point coordinate ${B}`);return _}function v(B){if(!(B instanceof A))throw new Error("ProjectivePoint expected")}function D(B){if(!c||!c.basises)throw new Error("no endo");return iI(B,c.basises,n.ORDER)}const P=Ju((B,_)=>{const{X:O,Y:m,Z:y}=B;if(i.eql(y,i.ONE))return{x:O,y:m};const x=B.is0();_==null&&(_=x?i.ONE:i.inv(y));const $=i.mul(O,_),E=i.mul(m,_),S=i.mul(y,_);if(x)return{x:i.ZERO,y:i.ZERO};if(!i.eql(S,i.ONE))throw new Error("invZ was invalid");return{x:$,y:E}}),T=Ju(B=>{if(B.is0()){if(e.allowInfinityPoint&&!i.is0(B.Y))return;throw new Error("bad point: ZERO")}const{x:_,y:O}=B.toAffine();if(!i.isValid(_)||!i.isValid(O))throw new Error("bad point: x or y not field elements");if(!w(_,O))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,_,O,m,y){return O=new A(i.mul(O.X,B),O.Y,O.Z),_=Rs(m,_),O=Rs(y,O),_.add(O)}class A{constructor(_,O,m){this.X=b("x",_),this.Y=b("y",O,!0),this.Z=b("z",m),Object.freeze(this)}static CURVE(){return s}static fromAffine(_){const{x:O,y:m}=_||{};if(!_||!i.isValid(O)||!i.isValid(m))throw new Error("invalid affine point");if(_ instanceof A)throw new Error("projective point not allowed");return i.is0(O)&&i.is0(m)?A.ZERO:new A(O,m,i.ONE)}static fromBytes(_){const O=A.fromAffine(p(Qr(_,void 0,"point")));return O.assertValidity(),O}static fromHex(_){return A.fromBytes(Ve("pointHex",_))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(_=8,O=!0){return j.createCache(this,_),O||this.multiply(ts),this}assertValidity(){T(this)}hasEvenY(){const{y:_}=this.toAffine();if(!i.isOdd)throw new Error("Field doesn't support isOdd");return!i.isOdd(_)}equals(_){v(_);const{X:O,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=_,S=i.eql(i.mul(O,E),i.mul(x,y)),F=i.eql(i.mul(m,E),i.mul($,y));return S&&F}negate(){return new A(this.X,i.neg(this.Y),this.Z)}double(){const{a:_,b:O}=s,m=i.mul(O,ts),{X:y,Y:x,Z:$}=this;let E=i.ZERO,S=i.ZERO,F=i.ZERO,N=i.mul(y,y),H=i.mul(x,x),z=i.mul($,$),q=i.mul(y,x);return q=i.add(q,q),F=i.mul(y,$),F=i.add(F,F),E=i.mul(_,F),S=i.mul(m,z),S=i.add(E,S),E=i.sub(H,S),S=i.add(H,S),S=i.mul(E,S),E=i.mul(q,E),F=i.mul(m,F),z=i.mul(_,z),q=i.sub(N,z),q=i.mul(_,q),q=i.add(q,F),F=i.add(N,N),N=i.add(F,N),N=i.add(N,z),N=i.mul(N,q),S=i.add(S,N),z=i.mul(x,$),z=i.add(z,z),N=i.mul(z,q),E=i.sub(E,N),F=i.mul(z,H),F=i.add(F,F),F=i.add(F,F),new A(E,S,F)}add(_){v(_);const{X:O,Y:m,Z:y}=this,{X:x,Y:$,Z:E}=_;let S=i.ZERO,F=i.ZERO,N=i.ZERO;const H=s.a,z=i.mul(s.b,ts);let q=i.mul(O,x),K=i.mul(m,$),G=i.mul(y,E),X=i.add(O,m),W=i.add(x,$);X=i.mul(X,W),W=i.add(q,K),X=i.sub(X,W),W=i.add(O,y);let Q=i.add(x,E);return W=i.mul(W,Q),Q=i.add(q,G),W=i.sub(W,Q),Q=i.add(m,y),S=i.add($,E),Q=i.mul(Q,S),S=i.add(K,G),Q=i.sub(Q,S),N=i.mul(H,W),S=i.mul(z,G),N=i.add(S,N),S=i.sub(K,N),N=i.add(K,N),F=i.mul(S,N),K=i.add(q,q),K=i.add(K,q),G=i.mul(H,G),W=i.mul(z,W),K=i.add(K,G),G=i.sub(q,G),G=i.mul(H,G),W=i.add(W,G),q=i.mul(K,W),F=i.add(F,q),q=i.mul(Q,W),S=i.mul(X,S),S=i.sub(S,q),q=i.mul(X,K),N=i.mul(Q,N),N=i.add(N,q),new A(S,F,N)}subtract(_){return this.add(_.negate())}is0(){return this.equals(A.ZERO)}multiply(_){const{endo:O}=e;if(!n.isValidNot0(_))throw new Error("invalid scalar: out of range");let m,y;const x=$=>j.cached(this,$,E=>Ho(A,E));if(O){const{k1neg:$,k1:E,k2neg:S,k2:F}=D(_),{p:N,f:H}=x(E),{p:z,f:q}=x(F);y=H.add(q),m=R(O.beta,N,z,$,S)}else{const{p:$,f:E}=x(_);m=$,y=E}return Ho(A,[m,y])[0]}multiplyUnsafe(_){const{endo:O}=e,m=this;if(!n.isValid(_))throw new Error("invalid scalar: out of range");if(_===cr||m.is0())return A.ZERO;if(_===Bi)return m;if(j.hasCache(this))return this.multiply(_);if(O){const{k1neg:y,k1:x,k2neg:$,k2:E}=D(_),{p1:S,p2:F}=V_(A,m,x,E);return R(O.beta,S,F,y,$)}else return j.unsafe(m,_)}multiplyAndAddUnsafe(_,O,m){const y=this.multiplyUnsafe(O).add(_.multiplyUnsafe(m));return y.is0()?void 0:y}toAffine(_){return P(this,_)}isTorsionFree(){const{isTorsionFree:_}=e;return o===Bi?!0:_?_(A,this):j.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:_}=e;return o===Bi?this:_?_(A,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(_=!0){return Bs(_,"isCompressed"),this.assertValidity(),d(A,this,_)}toHex(_=!0){return Ci(this.toBytes(_))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}get px(){return this.X}get py(){return this.X}get pz(){return this.Z}toRawBytes(_=!0){return this.toBytes(_)}_setWindowSize(_){this.precompute(_)}static normalizeZ(_){return Ho(A,_)}static msm(_,O){return H_(A,n,_,O)}static fromPrivateKey(_){return A.BASE.multiply(Si(n,_))}}A.BASE=new A(s.Gx,s.Gy,i.ONE),A.ZERO=new A(i.ZERO,i.ONE,i.ZERO),A.Fp=i,A.Fn=n;const U=n.BITS,j=new z_(A,e.endo?Math.ceil(U/2):U);return A.BASE.precompute(8),A}function bg(t){return Uint8Array.of(t?2:3)}function vg(t,e){return{secretKey:e.BYTES,publicKey:1+t.BYTES,publicKeyUncompressed:1+2*t.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function aI(t,e={}){const{Fn:r}=t,i=e.randomBytes||ui,n=Object.assign(vg(t.Fp,r),{seed:pg(r.ORDER)});function s(f){try{return!!Si(r,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=i(n.seed)){return L_(Qr(f,n.seed,"seed"),r.ORDER)}function c(f,d=!0){return t.BASE.multiply(Si(r,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(r.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=Si(r,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=>Si(r,f),precompute(f=8,d=t.BASE){return d.precompute(f,!1)}},lengths:n})}function cI(t,e,r={}){Js(e),no(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"});const i=r.randomBytes||ui,n=r.hmac||((O,...m)=>to(e,O,Cr(...m))),{Fp:s,Fn:o}=t,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d}=aI(t,r),p={prehash:!1,lowS:typeof r.lowS=="boolean"?r.lowS:!1,format:void 0,extraEntropy:!1},g="compact";function w(O){const m=a>>Bi;return O>m}function I(O,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${O}: out of range 1..Point.Fn.ORDER`);return m}function C(O,m){Va(m);const y=d.signature,x=m==="compact"?y:m==="recovered"?y+1:void 0;return Qr(O,x,`${m} signature`)}class b{constructor(m,y,x){this.r=I("r",m),this.s=I("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}=or.toSig(Qr(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*mg<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(Cr(bg((E&1)===0),F)),H=o.inv(S),z=D(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(Va(m),m==="der")return Ps(or.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 Cr(Uint8Array.of(this.recovery),y,x)}return Cr(y,x)}toHex(m){return Ci(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 Ci(this.toBytes("der"))}toCompactRawBytes(){return this.toBytes("compact")}toCompactHex(){return Ci(this.toBytes("compact"))}}const v=r.bits2int||function(O){if(O.length>8192)throw new Error("input is too large");const m=io(O),y=O.length*8-c;return y>0?m>>BigInt(y):m},D=r.bits2int_modN||function(O){return o.create(v(O))},P=Rn(c);function T(O){return qa("num < 2^"+c,O,cr,P),o.toBytes(O)}function R(O,m){return Qr(O,void 0,"message"),m?Qr(e(O),void 0,"prehashed message"):O}function A(O,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);O=R(O,$);const S=D(O),F=Si(o,m),N=[T(F),T(S)];if(E!=null&&E!==!1){const K=E===!0?i(d.secretKey):E;N.push(Ve("extraEntropy",K))}const H=Cr(...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===cr)return;const pe=o.create(X*o.create(z+Q*F));if(pe===cr)return;let ve=(W.x===Q?0:2)|Number(W.y&Bi),Ie=pe;return x&&w(pe)&&(Ie=o.neg(pe),ve^=1),new b(Q,Ie,ve)}return{seed:H,k2sig:q}}function U(O,m,y={}){O=Ve("message",O);const{seed:x,k2sig:$}=A(O,m,y);return C_(e.outputLen,o.BYTES,n)(x,$)}function j(O){let m;const y=typeof O=="string"||Zs(O),x=!y&&O!==null&&typeof O=="object"&&typeof O.r=="bigint"&&typeof O.s=="bigint";if(!y&&!x)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");if(x)m=new b(O.r,O.s);else if(y){try{m=b.fromBytes(Ve("sig",O),"der")}catch($){if(!($ instanceof or.Err))throw $}if(!m)try{m=b.fromBytes(Ve("sig",O),"compact")}catch{return!1}}return m||!1}function B(O,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(O):b.fromBytes(Ve("sig",O),S);if(F===!1)return!1;try{const N=t.fromBytes(y);if($&&F.hasHighS())return!1;const{r:H,s:z}=F,q=D(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 _(O,m,y={}){const{prehash:x}=Yo(y,p);return m=R(m,x),b.fromBytes(O,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:h,utils:f,lengths:d,Point:t,sign:U,verify:B,recoverPublicKey:_,Signature:b,hash:e})}function lI(t){const e={a:t.a,b:t.b,p:t.Fp.ORDER,n:t.n,h:t.h,Gx:t.Gx,Gy:t.Gy},r=t.Fp;let i=t.allowedPrivateKeyLengths?Array.from(new Set(t.allowedPrivateKeyLengths.map(o=>Math.ceil(o/2)))):void 0;const n=jr(e.n,{BITS:t.nBitLength,allowedLengths:i,modFromBytes:t.wrapPrivateKey}),s={Fp:r,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 uI(t){const{CURVE:e,curveOpts:r}=lI(t),i={hmac:t.hmac,randomBytes:t.randomBytes,lowS:t.lowS,bits2int:t.bits2int,bits2int_modN:t.bits2int_modN};return{CURVE:e,curveOpts:r,hash:t.hash,ecdsaOpts:i}}function hI(t,e){const r=e.Point;return Object.assign({},e,{ProjectivePoint:r,CURVE:Object.assign({},t,fg(r.Fn.ORDER,r.Fn.BITS))})}function fI(t){const{CURVE:e,curveOpts:r,hash:i,ecdsaOpts:n}=uI(t),s=oI(e,r),o=cI(s,i,n);return hI(t,o)}function Ha(t,e){const r=i=>fI({...t,hash:i});return{...r(e),create:r}}const Eg={p:BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff"),n:BigInt("0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551"),h:BigInt(1),a:BigInt("0xffffffff00000001000000000000000000000000fffffffffffffffffffffffc"),b:BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b"),Gx:BigInt("0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296"),Gy:BigInt("0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5")},xg={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000ffffffff"),n:BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffc7634d81f4372ddf581a0db248b0a77aecec196accc52973"),h:BigInt(1),a:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffeffffffff0000000000000000fffffffc"),b:BigInt("0xb3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef"),Gx:BigInt("0xaa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7"),Gy:BigInt("0x3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f")},_g={p:BigInt("0x1ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"),n:BigInt("0x01fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa51868783bf2f966b7fcc0148f709a5d03bb5c9b8899c47aebb6fb71e91386409"),h:BigInt(1),a:BigInt("0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc"),b:BigInt("0x0051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00"),Gx:BigInt("0x00c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66"),Gy:BigInt("0x011839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650")},dI=jr(Eg.p),pI=jr(xg.p),gI=jr(_g.p),yI=Ha({...Eg,Fp:dI,lowS:!1},Qs);Ha({...xg,Fp:pI,lowS:!1},vx),Ha({..._g,Fp:gI,lowS:!1,allowedPrivateKeyLengths:[130,131,132]},bx);const wI=yI,Ig="base10",Ge="base16",tt="base64pad",Br="base64url",Fn="utf8",Sg=0,hr=1,Nn=2,mI=0,sh=1,dn=12,Gc=32;function bI(){const t=za.utils.randomPrivateKey(),e=za.getPublicKey(t);return{privateKey:nt(t,Ge),publicKey:nt(e,Ge)}}function Ka(){const t=ui(Gc);return nt(t,Ge)}function vI(t,e){const r=za.getSharedSecret(Et(t,Ge),Et(e,Ge)),i=A_(ro,r,void 0,void 0,Gc);return nt(i,Ge)}function ds(t){const e=ro(Et(t,Ge));return nt(e,Ge)}function bt(t){const e=ro(Et(t,Fn));return nt(e,Ge)}function $g(t){return Et(`${t}`,Ig)}function ci(t){return Number(nt(t,Ig))}function Og(t){return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Dg(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),r=(4-e.length%4)%4;return e+"=".repeat(r)}function EI(t){const e=$g(typeof t.type<"u"?t.type:Sg);if(ci(e)===hr&&typeof t.senderPublicKey>"u")throw new Error("Missing sender public key for type 1 envelope");const r=typeof t.senderPublicKey<"u"?Et(t.senderPublicKey,Ge):void 0,i=typeof t.iv<"u"?Et(t.iv,Ge):ui(dn),n=Et(t.symKey,Ge),s=eg(n,i).encrypt(Et(t.message,Fn)),o=Ag({type:e,sealed:s,iv:i,senderPublicKey:r});return t.encoding===Br?Og(o):o}function xI(t){const e=Et(t.symKey,Ge),{sealed:r,iv:i}=In({encoded:t.encoded,encoding:t.encoding}),n=eg(e,i).decrypt(r);if(n===null)throw new Error("Failed to decrypt");return nt(n,Fn)}function _I(t,e){const r=$g(Nn),i=ui(dn),n=Et(t,Fn),s=Ag({type:r,sealed:n,iv:i});return e===Br?Og(s):s}function II(t,e){const{sealed:r}=In({encoded:t,encoding:e});return nt(r,Fn)}function Ag(t){if(ci(t.type)===Nn)return nt(fn([t.type,t.sealed]),tt);if(ci(t.type)===hr){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 In(t){const e=(t.encoding||tt)===Br?Dg(t.encoded):t.encoded,r=Et(e,tt),i=r.slice(mI,sh),n=sh;if(ci(i)===hr){const c=n+Gc,l=c+dn,u=r.slice(n,c),h=r.slice(c,l),f=r.slice(l);return{type:i,sealed:f,iv:h,senderPublicKey:u}}if(ci(i)===Nn){const c=r.slice(n),l=ui(dn);return{type:i,sealed:c,iv:l}}const s=n+dn,o=r.slice(n,s),a=r.slice(s);return{type:i,sealed:a,iv:o}}function SI(t,e){const r=In({encoded:t,encoding:e==null?void 0:e.encoding});return Pg({type:ci(r.type),senderPublicKey:typeof r.senderPublicKey<"u"?nt(r.senderPublicKey,Ge):void 0,receiverPublicKey:e==null?void 0:e.receiverPublicKey})}function Pg(t){const e=(t==null?void 0:t.type)||Sg;if(e===hr){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 oh(t){return t.type===hr&&typeof t.senderPublicKey=="string"&&typeof t.receiverPublicKey=="string"}function ah(t){return t.type===Nn}function $I(t){const e=re.from(t.x,"base64"),r=re.from(t.y,"base64");return fn([new Uint8Array([4]),e,r])}function OI(t,e){const[r,i,n]=t.split("."),s=re.from(Dg(n),"base64");if(s.length!==64)throw new Error("Invalid signature length");const o=s.slice(0,32),a=s.slice(32,64),c=`${r}.${i}`,l=ro(c),u=$I(e);if(!wI.verify(fn([o,a]),l,u))throw new Error("Invalid signature");return Pa(t).payload}const DI="irn";function Fs(t){return(t==null?void 0:t.relay)||{protocol:DI}}function $i(t){const e=hE[t];if(typeof e>"u")throw new Error(`Relay Protocol not supported: ${t}`);return e}var AI=Object.defineProperty,PI=Object.defineProperties,CI=Object.getOwnPropertyDescriptors,ch=Object.getOwnPropertySymbols,BI=Object.prototype.hasOwnProperty,TI=Object.prototype.propertyIsEnumerable,lh=(t,e,r)=>e in t?AI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Zo=(t,e)=>{for(var r in e||(e={}))BI.call(e,r)&&lh(t,r,e[r]);if(ch)for(var r of ch(e))TI.call(e,r)&&lh(t,r,e[r]);return t},RI=(t,e)=>PI(t,CI(e));function FI(t,e="-"){const r={},i="relay"+e;return Object.keys(t).forEach(n=>{if(n.startsWith(i)){const s=n.replace(i,""),o=t[n];r[s]=o}}),r}function uh(t){if(!t.includes("wc:")){const l=Tp(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(":"),r=t.indexOf("?")!==-1?t.indexOf("?"):void 0,i=t.substring(0,e),n=t.substring(e+1,r).split("@"),s=typeof r<"u"?t.substring(r):"",o=new URLSearchParams(s),a=Object.fromEntries(o.entries()),c=typeof a.methods=="string"?a.methods.split(","):void 0;return{protocol:i,topic:NI(n[0]),version:parseInt(n[1],10),symKey:a.symKey,relay:FI(a),methods:c,expiryTimestamp:a.expiryTimestamp?parseInt(a.expiryTimestamp,10):void 0}}function NI(t){return t.startsWith("//")?t.substring(2):t}function UI(t,e="-"){const r="relay",i={};return Object.keys(t).forEach(n=>{const s=n,o=r+e+s;t[s]&&(i[o]=t[s])}),i}function hh(t){const e=new URLSearchParams,r=Zo(Zo(RI(Zo({},UI(t.relay)),{symKey:t.symKey}),t.expiryTimestamp&&{expiryTimestamp:t.expiryTimestamp.toString()}),t.methods&&{methods:t.methods.join(",")});return Object.entries(r).sort(([i],[n])=>i.localeCompare(n)).forEach(([i,n])=>{n!==void 0&&e.append(i,String(n))}),`${t.protocol}:${t.topic}@${t.version}?${e}`}function rs(t,e,r){return`${t}?wc_ev=${r}&topic=${e}`}var kI=Object.defineProperty,jI=Object.defineProperties,LI=Object.getOwnPropertyDescriptors,fh=Object.getOwnPropertySymbols,MI=Object.prototype.hasOwnProperty,qI=Object.prototype.propertyIsEnumerable,dh=(t,e,r)=>e in t?kI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zI=(t,e)=>{for(var r in e||(e={}))MI.call(e,r)&&dh(t,r,e[r]);if(fh)for(var r of fh(e))qI.call(e,r)&&dh(t,r,e[r]);return t},VI=(t,e)=>jI(t,LI(e));function qi(t){const e=[];return t.forEach(r=>{const[i,n]=r.split(":");e.push(`${i}:${n}`)}),e}function Cg(t){const e=[];return Object.values(t).forEach(r=>{e.push(...qi(r.accounts))}),[...new Set(e)]}function HI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.methods)}),[...new Set(e)]}function KI(t){const e=[];return Object.values(t).forEach(r=>{e.push(...r.events)}),[...new Set(e)]}function WI(t,e){const r=[];return Object.values(t).forEach(i=>{qi(i.accounts).includes(e)&&r.push(...i.methods)}),r}function GI(t,e){const r=[];return Object.values(t).forEach(i=>{qi(i.accounts).includes(e)&&r.push(...i.events)}),r}function so(t){return t.includes(":")}function Oi(t){return so(t)?t.split(":")[0]:t}function ph(t){var e,r,i;const n={};if(!Kt(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=Oi(s);n[u]=VI(zI({},n[u]),{chains:Ht(a,(e=n[u])==null?void 0:e.chains),methods:Ht(c,(r=n[u])==null?void 0:r.methods),events:Ht(l,(i=n[u])==null?void 0:i.events)})}return n}function YI(t){const e={};return t==null||t.forEach(r=>{var i;const[n,s]=r.split(":");e[n]||(e[n]={accounts:[],chains:[],events:[],methods:[]}),e[n].accounts.push(r),(i=e[n].chains)==null||i.push(`${n}:${s}`)}),e}function gh(t,e){e=e.map(i=>i.replace("did:pkh:",""));const r=YI(e);for(const[i,n]of Object.entries(r))n.methods?n.methods=Ht(n.methods,t):n.methods=t,n.events=["chainChanged","accountsChanged"];return r}function ZI(t,e){var r,i,n,s,o,a;const c=ph(t),l=ph(e),u={},h=Object.keys(c).concat(Object.keys(l));for(const f of h)u[f]={chains:Ht((r=c[f])==null?void 0:r.chains,(i=l[f])==null?void 0:i.chains),methods:Ht((n=c[f])==null?void 0:n.methods,(s=l[f])==null?void 0:s.methods),events:Ht((o=c[f])==null?void 0:o.events,(a=l[f])==null?void 0:a.events)};return u}const JI={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}},XI={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:r,code:i}=XI[t];return{message:e?`${r} ${e}`:r,code:i}}function fe(t,e){const{message:r,code:i}=JI[t];return{message:e?`${r} ${e}`:r,code:i}}function _t(t,e){return Array.isArray(t)?typeof e<"u"&&t.length?t.every(e):!0:!1}function Kt(t){return Object.getPrototypeOf(t)===Object.prototype&&Object.keys(t).length}function _e(t){return typeof t>"u"}function be(t,e){return e&&_e(t)?!0:typeof t=="string"&&!!t.trim().length}function Yc(t,e){return e&&_e(t)?!0:typeof t=="number"&&!isNaN(t)}function QI(t,e){const{requiredNamespaces:r}=e,i=Object.keys(t.namespaces),n=Object.keys(r);let s=!0;return Xr(n,i)?(i.forEach(o=>{const{accounts:a,methods:c,events:l}=t.namespaces[o],u=qi(a),h=r[o];(!Xr(Dp(o,h),u)||!Xr(h.methods,c)||!Xr(h.events,l))&&(s=!1)}),s):!1}function Ns(t){return be(t,!1)&&t.includes(":")?t.split(":").length===2:!1}function e8(t){if(be(t,!1)&&t.includes(":")){const e=t.split(":");if(e.length===3){const r=e[0]+":"+e[1];return!!e[2]&&Ns(r)}}return!1}function t8(t){function e(r){try{return typeof new URL(r)<"u"}catch{return!1}}try{if(be(t,!1)){if(e(t))return!0;const r=Tp(t);return e(r)}}catch{}return!1}function r8(t){var e;return(e=t==null?void 0:t.proposer)==null?void 0:e.publicKey}function i8(t){return t==null?void 0:t.topic}function n8(t,e){let r=null;return be(t==null?void 0:t.publicKey,!1)||(r=M("MISSING_OR_INVALID",`${e} controller public key should be a string`)),r}function yh(t){let e=!0;return _t(t)?t.length&&(e=t.every(r=>be(r,!1))):e=!1,e}function s8(t,e,r){let i=null;return _t(e)&&e.length?e.forEach(n=>{i||Ns(n)||(i=fe("UNSUPPORTED_CHAINS",`${r}, chain ${n} should be a string and conform to "namespace:chainId" format`))}):Ns(t)||(i=fe("UNSUPPORTED_CHAINS",`${r}, chains must be defined as "namespace:chainId" e.g. "eip155:1": {...} in the namespace key OR as an array of CAIP-2 chainIds e.g. eip155: { chains: ["eip155:1", "eip155:5"] }`)),i}function o8(t,e,r){let i=null;return Object.entries(t).forEach(([n,s])=>{if(i)return;const o=s8(n,Dp(n,s),`${e} ${r}`);o&&(i=o)}),i}function a8(t,e){let r=null;return _t(t)?t.forEach(i=>{r||e8(i)||(r=fe("UNSUPPORTED_ACCOUNTS",`${e}, account ${i} should be a string and conform to "namespace:chainId:address" format`))}):r=fe("UNSUPPORTED_ACCOUNTS",`${e}, accounts should be an array of strings conforming to "namespace:chainId:address" format`),r}function c8(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=a8(i==null?void 0:i.accounts,`${e} namespace`);n&&(r=n)}),r}function l8(t,e){let r=null;return yh(t==null?void 0:t.methods)?yh(t==null?void 0:t.events)||(r=fe("UNSUPPORTED_EVENTS",`${e}, events should be an array of strings or empty array for no events`)):r=fe("UNSUPPORTED_METHODS",`${e}, methods should be an array of strings or empty array for no methods`),r}function Bg(t,e){let r=null;return Object.values(t).forEach(i=>{if(r)return;const n=l8(i,`${e}, namespace`);n&&(r=n)}),r}function u8(t,e,r){let i=null;if(t&&Kt(t)){const n=Bg(t,e);n&&(i=n);const s=o8(t,e,r);s&&(i=s)}else i=M("MISSING_OR_INVALID",`${e}, ${r} should be an object with data`);return i}function Jo(t,e){let r=null;if(t&&Kt(t)){const i=Bg(t,e);i&&(r=i);const n=c8(t,e);n&&(r=n)}else r=M("MISSING_OR_INVALID",`${e}, namespaces should be an object with data`);return r}function Tg(t){return be(t.protocol,!0)}function h8(t,e){let r=!1;return e&&!t?r=!0:t&&_t(t)&&t.length&&t.forEach(i=>{r=Tg(i)}),r}function f8(t){return typeof t=="number"}function Xe(t){return typeof t<"u"&&typeof t!==null}function d8(t){return!(!t||typeof t!="object"||!t.code||!Yc(t.code,!1)||!t.message||!be(t.message,!1))}function p8(t){return!(_e(t)||!be(t.method,!1))}function g8(t){return!(_e(t)||_e(t.result)&&_e(t.error)||!Yc(t.id,!1)||!be(t.jsonrpc,!1))}function y8(t){return!(_e(t)||!be(t.name,!1))}function wh(t,e){return!(!Ns(e)||!Cg(t).includes(e))}function w8(t,e,r){return be(r,!1)?WI(t,e).includes(r):!1}function m8(t,e,r){return be(r,!1)?GI(t,e).includes(r):!1}function mh(t,e,r){let i=null;const n=b8(t),s=v8(e),o=Object.keys(n),a=Object.keys(s),c=bh(Object.keys(t)),l=bh(Object.keys(e)),u=c.filter(h=>!l.includes(h));return u.length&&(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces keys don't satisfy requiredNamespaces.
|
|
21
|
+
Required: ${u.toString()}
|
|
22
|
+
Received: ${Object.keys(e).toString()}`)),Xr(o,a)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces chains don't satisfy required namespaces.
|
|
23
|
+
Required: ${o.toString()}
|
|
24
|
+
Approved: ${a.toString()}`)),Object.keys(e).forEach(h=>{if(!h.includes(":")||i)return;const f=qi(e[h].accounts);f.includes(h)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces accounts don't satisfy namespace accounts for ${h}
|
|
25
|
+
Required: ${h}
|
|
26
|
+
Approved: ${f.toString()}`))}),o.forEach(h=>{i||(Xr(n[h].methods,s[h].methods)?Xr(n[h].events,s[h].events)||(i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces events don't satisfy namespace events for ${h}`)):i=M("NON_CONFORMING_NAMESPACES",`${r} namespaces methods don't satisfy namespace methods for ${h}`))}),i}function b8(t){const e={};return Object.keys(t).forEach(r=>{var i;r.includes(":")?e[r]=t[r]:(i=t[r].chains)==null||i.forEach(n=>{e[n]={methods:t[r].methods,events:t[r].events}})}),e}function bh(t){return[...new Set(t.map(e=>e.includes(":")?e.split(":")[0]:e))]}function v8(t){const e={};return Object.keys(t).forEach(r=>{if(r.includes(":"))e[r]=t[r];else{const i=qi(t[r].accounts);i==null||i.forEach(n=>{e[n]={accounts:t[r].accounts.filter(s=>s.includes(`${n}:`)),methods:t[r].methods,events:t[r].events}})}}),e}function E8(t,e){return Yc(t,!1)&&t<=e.max&&t>=e.min}function vh(){const t=Bn();return new Promise(e=>{switch(t){case ft.browser:e(x8());break;case ft.reactNative:e(_8());break;case ft.node:e(I8());break;default:e(!0)}})}function x8(){return Mi()&&(navigator==null?void 0:navigator.onLine)}async function _8(){if(kr()&&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 I8(){return!0}function S8(t){switch(Bn()){case ft.browser:$8(t);break;case ft.reactNative:O8(t);break}}function $8(t){!kr()&&Mi()&&(window.addEventListener("online",()=>t(!0)),window.addEventListener("offline",()=>t(!1)))}function O8(t){var e;kr()&&typeof Y<"u"&&Y!=null&&Y.NetInfo&&((e=Y)==null||e.NetInfo.addEventListener(r=>t(r==null?void 0:r.isConnected)))}function D8(){var t;return Mi()&&ii()?((t=ii())==null?void 0:t.visibilityState)==="visible":!0}const Xo={};class Qi{static get(e){return Xo[e]}static set(e,r){Xo[e]=r}static delete(e){delete Xo[e]}}function A8(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 P8({publicKey:t,signature:e,payload:r}){var i;const n=Wa(r.method),s=128|parseInt(((i=r.version)==null?void 0:i.toString())||"4"),o=T8(r.address),a=r.era==="00"?new Uint8Array([0]):Wa(r.era);if(a.length!==1&&a.length!==2)throw new Error("Invalid era length");const c=parseInt(r.nonce,16),l=new Uint8Array([c&255,c>>8&255]),u=BigInt(`0x${B8(r.tip)}`),h=F8(u),f=new Uint8Array([0,...t,o,...e,...a,...l,...h,...n]),d=R8(f.length+1);return new Uint8Array([...d,s,...f])}function C8(t){const e=Wa(t),r=_E.blake2b(e,void 0,32);return"0x"+re.from(r).toString("hex")}function Wa(t){return new Uint8Array(t.replace(/^0x/,"").match(/.{1,2}/g).map(e=>parseInt(e,16)))}function B8(t){return t.startsWith("0x")?t.slice(2):t}function T8(t){const e=An.decode(t)[0];return e===42?0:e===60?2:1}function R8(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 F8(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 N8(t){const e=Uint8Array.from(re.from(t.signature,"hex")),r=A8(t.transaction.address),i=P8({publicKey:r,signature:e,payload:t.transaction}),n=re.from(i).toString("hex");return C8(n)}function Zc({logger:t,name:e}){const r=typeof t=="string"?Op({opts:{level:t,name:e}}).logger:t;return r.level=typeof t=="string"?t:t.level,r}class hi{}let U8=class extends hi{constructor(e){super()}};const Eh=L.FIVE_SECONDS,fi={pulse:"heartbeat_pulse"};let k8=class Rg extends U8{constructor(e){super(e),this.events=new St.EventEmitter,this.interval=Eh,this.interval=(e==null?void 0:e.interval)||Eh}static async init(e){const r=new Rg(e);return await r.init(),r}async init(){await this.initialize()}stop(){clearInterval(this.intervalRef)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async initialize(){this.intervalRef=setInterval(()=>this.pulse(),L.toMiliseconds(this.interval))}pulse(){this.events.emit(fi.pulse)}};const j8=/"(?:_|\\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*:/,L8=/"(?: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*:/,M8=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;function q8(t,e){if(t==="__proto__"||t==="constructor"&&e&&typeof e=="object"&&"prototype"in e){z8(t);return}return e}function z8(t){console.warn(`[destr] Dropping "${t}" key to prevent prototype pollution.`)}function is(t,e={}){if(typeof t!="string")return t;if(t[0]==='"'&&t[t.length-1]==='"'&&t.indexOf("\\")===-1)return t.slice(1,-1);const r=t.trim();if(r.length<=9)switch(r.toLowerCase()){case"true":return!0;case"false":return!1;case"undefined":return;case"null":return null;case"nan":return Number.NaN;case"infinity":return Number.POSITIVE_INFINITY;case"-infinity":return Number.NEGATIVE_INFINITY}if(!M8.test(t)){if(e.strict)throw new SyntaxError("[destr] Invalid JSON");return t}try{if(j8.test(t)||L8.test(t)){if(e.strict)throw new Error("[destr] Possible prototype pollution");return JSON.parse(t,q8)}return JSON.parse(t)}catch(i){if(e.strict)throw i;return t}}function V8(t){return!t||typeof t.then!="function"?Promise.resolve(t):t}function Oe(t,...e){try{return V8(t(...e))}catch(r){return Promise.reject(r)}}function H8(t){const e=typeof t;return t===null||e!=="object"&&e!=="function"}function K8(t){const e=Object.getPrototypeOf(t);return!e||e.isPrototypeOf(Object)}function ps(t){if(H8(t))return String(t);if(K8(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 Ga="base64:";function W8(t){return typeof t=="string"?t:Ga+Z8(t)}function G8(t){return typeof t!="string"||!t.startsWith(Ga)?t:Y8(t.slice(Ga.length))}function Y8(t){return globalThis.Buffer?Buffer.from(t,"base64"):Uint8Array.from(globalThis.atob(t),e=>e.codePointAt(0))}function Z8(t){return globalThis.Buffer?Buffer.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 J8(...t){return Je(t.join(":"))}function ns(t){return t=Je(t),t?t+":":""}function X8(t,e){if(e===void 0)return!0;let r=0,i=t.indexOf(":");for(;i>-1;)r++,i=t.indexOf(":",i+1);return r<=e}function Q8(t,e){return e?t.startsWith(e)&&t[t.length-1]!=="$":t[t.length-1]!=="$"}const eS="memory",tS=()=>{const t=new Map;return{name:eS,getInstance:()=>t,hasItem(e){return t.has(e)},getItem(e){return t.get(e)??null},getItemRaw(e){return t.get(e)??null},setItem(e,r){t.set(e,r)},setItemRaw(e,r){t.set(e,r)},removeItem(e){t.delete(e)},getKeys(){return[...t.keys()]},clear(){t.clear()},dispose(){t.clear()}}};function rS(t={}){const e={mounts:{"":t.driver||tS()},mountpoints:[""],watching:!1,watchListeners:[],unwatch:{}},r=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[""]}},i=(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 xh(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),I=g?void 0:p.value,C=g||!p.options?u:{...u,...p.options},b=r(w);d(b).items.push({key:w,value:I,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}=r(l);return Oe(f.hasItem,h,u)},getItem(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=r(l);return Oe(f.getItem,h,u).then(d=>is(d))},getItems(l,u={}){return a(l,u,h=>h.driver.getItems?Oe(h.driver.getItems,h.items.map(f=>({key:f.relativeKey,options:f.options})),u).then(f=>f.map(d=>({key:J8(h.base,d.key),value:is(d.value)}))):Promise.all(h.items.map(f=>Oe(h.driver.getItem,f.relativeKey,f.options).then(d=>({key:f.key,value:is(d)})))))},getItemRaw(l,u={}){l=Je(l);const{relativeKey:h,driver:f}=r(l);return f.getItemRaw?Oe(f.getItemRaw,h,u):Oe(f.getItem,h,u).then(d=>G8(d))},async setItem(l,u,h={}){if(u===void 0)return c.removeItem(l);l=Je(l);const{relativeKey:f,driver:d}=r(l);d.setItem&&(await Oe(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 Oe(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=>Oe(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}=r(l);if(d.setItemRaw)await Oe(d.setItemRaw,f,u,h);else if(d.setItem)await Oe(d.setItem,f,W8(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}=r(l);f.removeItem&&(await Oe(f.removeItem,h,u),(u.removeMeta||u.removeMata)&&await Oe(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}=r(l),d=Object.create(null);if(f.getMeta&&Object.assign(d,await Oe(f.getMeta,h,u)),!u.nativeOnly){const p=await Oe(f.getItem,h+"$",u).then(g=>is(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=i(l,!0);let f=[];const d=[];let p=!0;for(const I of h){(w=I.driver.flags)!=null&&w.maxDepth||(p=!1);const C=await Oe(I.driver.getKeys,I.relativeBase,u);for(const b of C){const v=I.mountpoint+Je(b);f.some(D=>v.startsWith(D))||d.push(v)}f=[I.mountpoint,...f.filter(b=>!b.startsWith(I.mountpoint))]}const g=u.maxDepth!==void 0&&!p;return d.filter(I=>(!g||X8(I,u.maxDepth))&&Q8(I,l))},async clear(l,u={}){l=ns(l),await Promise.all(i(l,!1).map(async h=>{if(h.driver.clear)return Oe(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=>_h(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(xh(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 _h(e.mounts[l]),e.mountpoints=e.mountpoints.filter(d=>d!==l),delete e.mounts[l])},getMount(l=""){l=Je(l)+":";const u=r(l);return{driver:u.driver,base:u.base}},getMounts(l="",u={}){return l=Je(l),i(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 xh(t,e,r){return t.watch?t.watch((i,n)=>e(i,r+n)):()=>{}}async function _h(t){typeof t.dispose=="function"&&await Oe(t.dispose)}function di(t){return new Promise((e,r)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>r(t.error)})}function Fg(t,e){let r;const i=()=>{if(r)return r;const n=indexedDB.open(t);return n.onupgradeneeded=()=>n.result.createObjectStore(e),r=di(n),r.then(s=>{s.onclose=()=>r=void 0},()=>{}),r};return(n,s)=>i().then(o=>s(o.transaction(e,n).objectStore(e)))}let Qo;function Un(){return Qo||(Qo=Fg("keyval-store","keyval")),Qo}function Ih(t,e=Un()){return e("readonly",r=>di(r.get(t)))}function iS(t,e,r=Un()){return r("readwrite",i=>(i.put(e,t),di(i.transaction)))}function nS(t,e=Un()){return e("readwrite",r=>(r.delete(t),di(r.transaction)))}function sS(t=Un()){return t("readwrite",e=>(e.clear(),di(e.transaction)))}function oS(t,e){return t.openCursor().onsuccess=function(){this.result&&(e(this.result),this.result.continue())},di(t.transaction)}function aS(t=Un()){return t("readonly",e=>{if(e.getAllKeys)return di(e.getAllKeys());const r=[];return oS(e,i=>r.push(i.key)).then(()=>r)})}const cS="idb-keyval";var lS=(t={})=>{const e=t.base&&t.base.length>0?`${t.base}:`:"",r=n=>e+n;let i;return t.dbName&&t.storeName&&(i=Fg(t.dbName,t.storeName)),{name:cS,options:t,async hasItem(n){return!(typeof await Ih(r(n),i)>"u")},async getItem(n){return await Ih(r(n),i)??null},setItem(n,s){return iS(r(n),s,i)},removeItem(n){return nS(r(n),i)},getKeys(){return aS(i)},clear(){return sS(i)}}};const uS="WALLET_CONNECT_V2_INDEXED_DB",hS="keyvaluestorage";let fS=class{constructor(){this.indexedDb=rS({driver:lS({dbName:uS,storeName:hS})})}async getKeys(){return this.indexedDb.getKeys()}async getEntries(){return(await this.indexedDb.getItems(await this.indexedDb.getKeys())).map(e=>[e.key,e.value])}async getItem(e){const r=await this.indexedDb.getItem(e);if(r!==null)return r}async setItem(e,r){await this.indexedDb.setItem(e,oi(r))}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(r){return this.hasOwnProperty(r)?String(this[r]):null},t.prototype.setItem=function(r,i){this[r]=String(i)},t.prototype.removeItem=function(r){delete this[r]},t.prototype.clear=function(){const r=this;Object.keys(r).forEach(function(i){r[i]=void 0,delete r[i]})},t.prototype.key=function(r){return r=r||0,Object.keys(this)[r]},t.prototype.__defineGetter__("length",function(){return Object.keys(this).length}),typeof ea<"u"&&ea.localStorage?gs.exports=ea.localStorage:typeof window<"u"&&window.localStorage?gs.exports=window.localStorage:gs.exports=new e})();function dS(t){var e;return[t[0],si((e=t[1])!=null?e:"")]}let pS=class{constructor(){this.localStorage=gs.exports}async getKeys(){return Object.keys(this.localStorage)}async getEntries(){return Object.entries(this.localStorage).map(dS)}async getItem(e){const r=this.localStorage.getItem(e);if(r!==null)return si(r)}async setItem(e,r){this.localStorage.setItem(e,oi(r))}async removeItem(e){this.localStorage.removeItem(e)}};const gS="wc_storage_version",Sh=1,yS=async(t,e,r)=>{const i=gS,n=await e.getItem(i);if(n&&n>=Sh){r(e);return}const s=await t.getKeys();if(!s.length){r(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(i,Sh),r(e),wS(t,o)},wS=async(t,e)=>{e.length&&e.forEach(async r=>{await t.removeItem(r)})};let mS=class{constructor(){this.initialized=!1,this.setInitialized=r=>{this.storage=r,this.initialized=!0};const e=new pS;this.storage=e;try{const r=new fS;yS(e,r,this.setInitialized)}catch{this.initialized=!0}}async getKeys(){return await this.initialize(),this.storage.getKeys()}async getEntries(){return await this.initialize(),this.storage.getEntries()}async getItem(e){return await this.initialize(),this.storage.getItem(e)}async setItem(e,r){return await this.initialize(),this.storage.setItem(e,r)}async removeItem(e){return await this.initialize(),this.storage.removeItem(e)}async initialize(){this.initialized||await new Promise(e=>{const r=setInterval(()=>{this.initialized&&(clearInterval(r),e())},20)})}};var bS=Object.defineProperty,vS=(t,e,r)=>e in t?bS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,$h=(t,e,r)=>vS(t,typeof e!="symbol"?e+"":e,r);let ES=class extends hi{constructor(e){super(),this.opts=e,$h(this,"protocol","wc"),$h(this,"version",2)}};var xS=Object.defineProperty,_S=(t,e,r)=>e in t?xS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,IS=(t,e,r)=>_S(t,typeof e!="symbol"?e+"":e,r);let SS=class extends hi{constructor(e,r){super(),this.core=e,this.logger=r,IS(this,"records",new Map)}},$S=class{constructor(e,r){this.logger=e,this.core=r}},OS=class extends hi{constructor(e,r){super(),this.relayer=e,this.logger=r}},DS=class extends hi{constructor(e){super()}},AS=class{constructor(e,r,i,n){this.core=e,this.logger=r,this.name=i}},PS=class extends hi{constructor(e,r){super(),this.relayer=e,this.logger=r}},CS=class extends hi{constructor(e,r){super(),this.core=e,this.logger=r}},BS=class{constructor(e,r,i){this.core=e,this.logger=r,this.store=i}},TS=class{constructor(e,r){this.projectId=e,this.logger=r}},RS=class{constructor(e,r,i){this.core=e,this.logger=r,this.telemetryEnabled=i}};var FS=Object.defineProperty,NS=(t,e,r)=>e in t?FS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Oh=(t,e,r)=>NS(t,typeof e!="symbol"?e+"":e,r);let US=class{constructor(e){this.opts=e,Oh(this,"protocol","wc"),Oh(this,"version",2)}},kS=class{constructor(e){this.client=e}};const jS="PARSE_ERROR",LS="INVALID_REQUEST",MS="METHOD_NOT_FOUND",qS="INVALID_PARAMS",Ng="INTERNAL_ERROR",Jc="SERVER_ERROR",zS=[-32700,-32600,-32601,-32602,-32603],pn={[jS]:{code:-32700,message:"Parse error"},[LS]:{code:-32600,message:"Invalid Request"},[MS]:{code:-32601,message:"Method not found"},[qS]:{code:-32602,message:"Invalid params"},[Ng]:{code:-32603,message:"Internal error"},[Jc]:{code:-32e3,message:"Server error"}},Ug=Jc;function VS(t){return zS.includes(t)}function Dh(t){return Object.keys(pn).includes(t)?pn[t]:pn[Ug]}function HS(t){const e=Object.values(pn).find(r=>r.code===t);return e||pn[Ug]}function kg(t,e,r){return t.message.includes("getaddrinfo ENOTFOUND")||t.message.includes("connect ECONNREFUSED")?new Error(`Unavailable ${r} RPC url at ${e}`):t}var jg={};/*! *****************************************************************************
|
|
27
|
+
Copyright (c) Microsoft Corporation.
|
|
28
|
+
|
|
29
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
30
|
+
purpose with or without fee is hereby granted.
|
|
31
|
+
|
|
32
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
33
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
34
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
35
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
36
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
37
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
38
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
39
|
+
***************************************************************************** */var Ya=function(t,e){return Ya=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(r,i){r.__proto__=i}||function(r,i){for(var n in i)i.hasOwnProperty(n)&&(r[n]=i[n])},Ya(t,e)};function KS(t,e){Ya(t,e);function r(){this.constructor=t}t.prototype=e===null?Object.create(e):(r.prototype=e.prototype,new r)}var Za=function(){return Za=Object.assign||function(e){for(var r,i=1,n=arguments.length;i<n;i++){r=arguments[i];for(var s in r)Object.prototype.hasOwnProperty.call(r,s)&&(e[s]=r[s])}return e},Za.apply(this,arguments)};function WS(t,e){var r={};for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&e.indexOf(i)<0&&(r[i]=t[i]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,i=Object.getOwnPropertySymbols(t);n<i.length;n++)e.indexOf(i[n])<0&&Object.prototype.propertyIsEnumerable.call(t,i[n])&&(r[i[n]]=t[i[n]]);return r}function GS(t,e,r,i){var n=arguments.length,s=n<3?e:i===null?i=Object.getOwnPropertyDescriptor(e,r):i,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(t,e,r,i);else for(var a=t.length-1;a>=0;a--)(o=t[a])&&(s=(n<3?o(s):n>3?o(e,r,s):o(e,r))||s);return n>3&&s&&Object.defineProperty(e,r,s),s}function YS(t,e){return function(r,i){e(r,i,t)}}function ZS(t,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(t,e)}function JS(t,e,r,i){function n(s){return s instanceof r?s:new r(function(o){o(s)})}return new(r||(r=Promise))(function(s,o){function a(u){try{l(i.next(u))}catch(h){o(h)}}function c(u){try{l(i.throw(u))}catch(h){o(h)}}function l(u){u.done?s(u.value):n(u.value).then(a,c)}l((i=i.apply(t,e||[])).next())})}function XS(t,e){var r={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},i,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(i)throw new TypeError("Generator is already executing.");for(;r;)try{if(i=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 r.label++,{value:l[1],done:!1};case 5:r.label++,n=l[1],l=[0];continue;case 7:l=r.ops.pop(),r.trys.pop();continue;default:if(s=r.trys,!(s=s.length>0&&s[s.length-1])&&(l[0]===6||l[0]===2)){r=0;continue}if(l[0]===3&&(!s||l[1]>s[0]&&l[1]<s[3])){r.label=l[1];break}if(l[0]===6&&r.label<s[1]){r.label=s[1],s=l;break}if(s&&r.label<s[2]){r.label=s[2],r.ops.push(l);break}s[2]&&r.ops.pop(),r.trys.pop();continue}l=e.call(t,r)}catch(u){l=[6,u],n=0}finally{i=s=0}if(l[0]&5)throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}function QS(t,e,r,i){i===void 0&&(i=r),t[i]=e[r]}function e$(t,e){for(var r in t)r!=="default"&&!e.hasOwnProperty(r)&&(e[r]=t[r])}function Ja(t){var e=typeof Symbol=="function"&&Symbol.iterator,r=e&&t[e],i=0;if(r)return r.call(t);if(t&&typeof t.length=="number")return{next:function(){return t&&i>=t.length&&(t=void 0),{value:t&&t[i++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function Lg(t,e){var r=typeof Symbol=="function"&&t[Symbol.iterator];if(!r)return t;var i=r.call(t),n,s=[],o;try{for(;(e===void 0||e-- >0)&&!(n=i.next()).done;)s.push(n.value)}catch(a){o={error:a}}finally{try{n&&!n.done&&(r=i.return)&&r.call(i)}finally{if(o)throw o.error}}return s}function t$(){for(var t=[],e=0;e<arguments.length;e++)t=t.concat(Lg(arguments[e]));return t}function r$(){for(var t=0,e=0,r=arguments.length;e<r;e++)t+=arguments[e].length;for(var i=Array(t),n=0,e=0;e<r;e++)for(var s=arguments[e],o=0,a=s.length;o<a;o++,n++)i[n]=s[o];return i}function Sn(t){return this instanceof Sn?(this.v=t,this):new Sn(t)}function i$(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=r.apply(t,e||[]),n,s=[];return n={},o("next"),o("throw"),o("return"),n[Symbol.asyncIterator]=function(){return this},n;function o(f){i[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(i[f](d))}catch(p){h(s[0][3],p)}}function c(f){f.value instanceof Sn?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 n$(t){var e,r;return e={},i("next"),i("throw",function(n){throw n}),i("return"),e[Symbol.iterator]=function(){return this},e;function i(n,s){e[n]=t[n]?function(o){return(r=!r)?{value:Sn(t[n](o)),done:n==="return"}:s?s(o):o}:s}}function s$(t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=t[Symbol.asyncIterator],r;return e?e.call(t):(t=typeof Ja=="function"?Ja(t):t[Symbol.iterator](),r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r);function i(s){r[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 o$(t,e){return Object.defineProperty?Object.defineProperty(t,"raw",{value:e}):t.raw=e,t}function a$(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function c$(t){return t&&t.__esModule?t:{default:t}}function l$(t,e){if(!e.has(t))throw new TypeError("attempted to get private field on non-instance");return e.get(t)}function u$(t,e,r){if(!e.has(t))throw new TypeError("attempted to set private field on non-instance");return e.set(t,r),r}const h$=Object.freeze(Object.defineProperty({__proto__:null,get __assign(){return Za},__asyncDelegator:n$,__asyncGenerator:i$,__asyncValues:s$,__await:Sn,__awaiter:JS,__classPrivateFieldGet:l$,__classPrivateFieldSet:u$,__createBinding:QS,__decorate:GS,__exportStar:e$,__extends:KS,__generator:XS,__importDefault:c$,__importStar:a$,__makeTemplateObject:o$,__metadata:ZS,__param:YS,__read:Lg,__rest:WS,__spread:t$,__spreadArrays:r$,__values:Ja},Symbol.toStringTag,{value:"Module"})),f$=kf(h$);var er={},Ah;function d$(){if(Ah)return er;Ah=1,Object.defineProperty(er,"__esModule",{value:!0}),er.isBrowserCryptoAvailable=er.getSubtleCrypto=er.getBrowerCrypto=void 0;function t(){return(gi===null||gi===void 0?void 0:gi.crypto)||(gi===null||gi===void 0?void 0:gi.msCrypto)||{}}er.getBrowerCrypto=t;function e(){const i=t();return i.subtle||i.webkitSubtle}er.getSubtleCrypto=e;function r(){return!!t()&&!!e()}return er.isBrowserCryptoAvailable=r,er}var tr={},Ph;function p$(){if(Ph)return tr;Ph=1,Object.defineProperty(tr,"__esModule",{value:!0}),tr.isBrowser=tr.isNode=tr.isReactNative=void 0;function t(){return typeof document>"u"&&typeof navigator<"u"&&navigator.product==="ReactNative"}tr.isReactNative=t;function e(){return typeof xt<"u"&&typeof xt.versions<"u"&&typeof xt.versions.node<"u"}tr.isNode=e;function r(){return!t()&&!e()}return tr.isBrowser=r,tr}(function(t){Object.defineProperty(t,"__esModule",{value:!0});const e=f$;e.__exportStar(d$(),t),e.__exportStar(p$(),t)})(jg);function Lt(t=3){const e=Date.now()*Math.pow(10,t),r=Math.floor(Math.random()*Math.pow(10,t));return e+r}function Rr(t=6){return BigInt(Lt(t))}function Ct(t,e,r){return{id:r||Lt(),jsonrpc:"2.0",method:t,params:e}}function $n(t,e){return{id:t,jsonrpc:"2.0",result:e}}function oo(t,e,r){return{id:t,jsonrpc:"2.0",error:g$(e,r)}}function g$(t,e){return typeof t>"u"?Dh(Ng):(typeof t=="string"&&(t=Object.assign(Object.assign({},Dh(Jc)),{message:t})),typeof e<"u"&&(t.data=e),VS(t.code)&&(t=HS(t.code)),t)}class y${}class w$ extends y${constructor(){super()}}class m$ extends w${constructor(e){super()}}const b$="^https?:",v$="^wss?:";function E$(t){const e=t.match(new RegExp(/^\w+:/,"gi"));if(!(!e||!e.length))return e[0]}function Mg(t,e){const r=E$(t);return typeof r>"u"?!1:new RegExp(e).test(r)}function Ch(t){return Mg(t,b$)}function Bh(t){return Mg(t,v$)}function x$(t){return new RegExp("wss?://localhost(:d{2,5})?").test(t)}function qg(t){return typeof t=="object"&&"id"in t&&"jsonrpc"in t&&t.jsonrpc==="2.0"}function Xc(t){return qg(t)&&"method"in t}function ao(t){return qg(t)&&(Mt(t)||vt(t))}function Mt(t){return"result"in t}function vt(t){return"error"in t}class Qc extends m${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,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async request(e,r){return this.requestStrict(Ct(e.method,e.params||[],e.id||Rr().toString()),r)}async requestStrict(e,r){return new Promise(async(i,n)=>{if(!this.connection.connected)try{await this.open()}catch(s){n(s)}this.events.on(`${e.id}`,s=>{vt(s)?n(s.error):i(s.result)});try{await this.connection.send(e,r)}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)}}var ta,Th;function _$(){return Th||(Th=1,ta=function(){throw new Error("ws does not work in the browser. Browser clients must use the native WebSocket object")}),ta}const I$=()=>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:_$(),S$=()=>typeof WebSocket<"u"||typeof Y<"u"&&typeof Y.WebSocket<"u"||typeof window<"u"&&typeof window.WebSocket<"u"||typeof self<"u"&&typeof self.WebSocket<"u",Rh=t=>t.split("?")[0],Fh=10,$$=I$();let O$=class{constructor(e){if(this.url=e,this.events=new St.EventEmitter,this.registering=!1,!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);this.url=e}get connected(){return typeof this.socket<"u"}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){return new Promise((e,r)=>{if(typeof this.socket>"u"){r(new Error("Connection already closed"));return}this.socket.onclose=i=>{this.onClose(i),e()},this.socket.close()})}async send(e){typeof this.socket>"u"&&(this.socket=await this.register());try{this.socket.send(oi(e))}catch(r){this.onError(e.id,r)}}register(e=this.url){if(!Bh(e))throw new Error(`Provided URL is not compatible with WebSocket connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i(this.socket)})})}return this.url=e,this.registering=!0,new Promise((r,i)=>{const n=jg.isReactNative()?void 0:{rejectUnauthorized:!x$(e)},s=new $$(e,[],n);S$()?s.onerror=o=>{const a=o;i(this.emitError(a.error))}:s.on("error",o=>{i(this.emitError(o))}),s.onopen=()=>{this.onOpen(s),r(s)}})}onOpen(e){e.onmessage=r=>this.onPayload(r),e.onclose=r=>this.onClose(r),this.socket=e,this.registering=!1,this.events.emit("open")}onClose(e){this.socket=void 0,this.registering=!1,this.events.emit("close",e)}onPayload(e){if(typeof e.data>"u")return;const r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,Rh(r),"WS")}resetMaxListeners(){this.events.getMaxListeners()>Fh&&this.events.setMaxListeners(Fh)}emitError(e){const r=this.parseError(new Error((e==null?void 0:e.message)||`WebSocket connection failed for host: ${Rh(this.url)}`));return this.events.emit("register_error",r),r}};const zg="wc",Vg=2,Us="core",Wt=`${zg}@2:${Us}:`,D$={name:Us,logger:"error"},A$={database:":memory:"},P$="crypto",Nh="client_ed25519_seed",C$=L.ONE_DAY,B$="keychain",T$="0.3",R$="messages",F$="0.3",N$=L.SIX_HOURS,U$="publisher",Hg="irn",k$="error",Kg="wss://relay.walletconnect.org",j$="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"},L$="_subscription",gt={payload:"payload",connect:"connect",disconnect:"disconnect",error:"error"},M$=.1,Xa="2.23.1",he={link_mode:"link_mode",relay:"relay"},ys={inbound:"inbound",outbound:"outbound"},q$="0.3",z$="WALLETCONNECT_CLIENT_ID",Uh="WALLETCONNECT_LINK_MODE_APPS",lt={created:"subscription_created",deleted:"subscription_deleted",expired:"subscription_expired",disabled:"subscription_disabled",sync:"subscription_sync",resubscribed:"subscription_resubscribed"},V$="subscription",H$="0.3",K$="pairing",W$="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}}},Yr={create:"pairing_create",expire:"pairing_expire",delete:"pairing_delete",ping:"pairing_ping"},Ot={created:"history_created",updated:"history_updated",deleted:"history_deleted",sync:"history_sync"},G$="history",Y$="0.3",Z$="expirer",wt={created:"expirer_created",deleted:"expirer_deleted",expired:"expirer_expired",sync:"expirer_sync"},J$="0.3",X$="verify-api",Q$="https://verify.walletconnect.com",Wg="https://verify.walletconnect.org",gn=Wg,e6=`${gn}/v3`,t6=[Q$,Wg],r6="echo",i6="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"},ir={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"},Dt={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"},zr={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"},Vr={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"},n6=.1,s6="event-client",o6=86400,a6="https://pulse.walletconnect.org/batch";function c6(t,e){if(t.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),i=0;i<r.length;i++)r[i]=255;for(var n=0;n<t.length;n++){var s=t.charAt(n),o=s.charCodeAt(0);if(r[o]!==255)throw new TypeError(s+" is ambiguous");r[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,I=0,C=p.length;I!==C&&p[I]===0;)I++,g++;for(var b=(C-I)*u+1>>>0,v=new Uint8Array(b);I!==C;){for(var D=p[I],P=0,T=b-1;(D!==0||P<w)&&T!==-1;T--,P++)D+=256*v[T]>>>0,v[T]=D%a>>>0,D=D/a>>>0;if(D!==0)throw new Error("Non-zero carry");w=P,I++}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,I=0;p[g]===c;)w++,g++;for(var C=(p.length-g)*l+1>>>0,b=new Uint8Array(C);p[g];){var v=r[p.charCodeAt(g)];if(v===255)return;for(var D=0,P=C-1;(v!==0||D<I)&&P!==-1;P--,D++)v+=a*b[P]>>>0,b[P]=v%256>>>0,v=v/256>>>0;if(v!==0)throw new Error("Non-zero carry");I=D,g++}if(p[g]!==" "){for(var T=C-I;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 l6=c6,u6=l6;const Gg=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")},h6=t=>new TextEncoder().encode(t),f6=t=>new TextDecoder().decode(t);class d6{constructor(e,r,i){this.name=e,this.prefix=r,this.baseEncode=i}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}}class p6{constructor(e,r,i){if(this.name=e,this.prefix=r,r.codePointAt(0)===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=r.codePointAt(0),this.baseDecode=i}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Yg(this,e)}}class g6{constructor(e){this.decoders=e}or(e){return Yg(this,e)}decode(e){const r=e[0],i=this.decoders[r];if(i)return i.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}}const Yg=(t,e)=>new g6({...t.decoders||{[t.prefix]:t},...e.decoders||{[e.prefix]:e}});class y6{constructor(e,r,i,n){this.name=e,this.prefix=r,this.baseEncode=i,this.baseDecode=n,this.encoder=new d6(e,r,i),this.decoder=new p6(e,r,n)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}const co=({name:t,prefix:e,encode:r,decode:i})=>new y6(t,e,r,i),kn=({prefix:t,name:e,alphabet:r})=>{const{encode:i,decode:n}=u6(r,e);return co({prefix:t,name:e,encode:i,decode:s=>Gg(n(s))})},w6=(t,e,r,i)=>{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*r/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-${i} character`);c=c<<r|h,a+=r,a>=8&&(a-=8,o[l++]=255&c>>a)}if(a>=r||255&c<<8-a)throw new SyntaxError("Unexpected end of data");return o},m6=(t,e,r)=>{const i=e[e.length-1]==="=",n=(1<<r)-1;let s="",o=0,a=0;for(let c=0;c<t.length;++c)for(a=a<<8|t[c],o+=8;o>r;)o-=r,s+=e[n&a>>o];if(o&&(s+=e[n&a<<r-o]),i)for(;s.length*r&7;)s+="=";return s},Ue=({name:t,prefix:e,bitsPerChar:r,alphabet:i})=>co({prefix:e,name:t,encode(n){return m6(n,i,r)},decode(n){return w6(n,i,r,t)}}),b6=co({prefix:"\0",name:"identity",encode:t=>f6(t),decode:t=>h6(t)});var v6=Object.freeze({__proto__:null,identity:b6});const E6=Ue({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1});var x6=Object.freeze({__proto__:null,base2:E6});const _6=Ue({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3});var I6=Object.freeze({__proto__:null,base8:_6});const S6=kn({prefix:"9",name:"base10",alphabet:"0123456789"});var $6=Object.freeze({__proto__:null,base10:S6});const O6=Ue({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),D6=Ue({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4});var A6=Object.freeze({__proto__:null,base16:O6,base16upper:D6});const P6=Ue({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),C6=Ue({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),B6=Ue({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),T6=Ue({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),R6=Ue({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),F6=Ue({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),N6=Ue({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),U6=Ue({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),k6=Ue({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5});var j6=Object.freeze({__proto__:null,base32:P6,base32upper:C6,base32pad:B6,base32padupper:T6,base32hex:R6,base32hexupper:F6,base32hexpad:N6,base32hexpadupper:U6,base32z:k6});const L6=kn({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),M6=kn({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"});var q6=Object.freeze({__proto__:null,base36:L6,base36upper:M6});const z6=kn({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),V6=kn({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"});var H6=Object.freeze({__proto__:null,base58btc:z6,base58flickr:V6});const K6=Ue({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),W6=Ue({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),G6=Ue({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Y6=Ue({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6});var Z6=Object.freeze({__proto__:null,base64:K6,base64pad:W6,base64url:G6,base64urlpad:Y6});const Zg=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),J6=Zg.reduce((t,e,r)=>(t[r]=e,t),[]),X6=Zg.reduce((t,e,r)=>(t[e.codePointAt(0)]=r,t),[]);function Q6(t){return t.reduce((e,r)=>(e+=J6[r],e),"")}function eO(t){const e=[];for(const r of t){const i=X6[r.codePointAt(0)];if(i===void 0)throw new Error(`Non-base256emoji character: ${r}`);e.push(i)}return new Uint8Array(e)}const tO=co({prefix:"🚀",name:"base256emoji",encode:Q6,decode:eO});var rO=Object.freeze({__proto__:null,base256emoji:tO}),iO=Jg,kh=128,nO=127,sO=~nO,oO=Math.pow(2,31);function Jg(t,e,r){e=e||[],r=r||0;for(var i=r;t>=oO;)e[r++]=t&255|kh,t/=128;for(;t&sO;)e[r++]=t&255|kh,t>>>=7;return e[r]=t|0,Jg.bytes=r-i+1,e}var aO=Qa,cO=128,jh=127;function Qa(t,i){var r=0,i=i||0,n=0,s=i,o,a=t.length;do{if(s>=a)throw Qa.bytes=0,new RangeError("Could not decode varint");o=t[s++],r+=n<28?(o&jh)<<n:(o&jh)*Math.pow(2,n),n+=7}while(o>=cO);return Qa.bytes=s-i,r}var lO=Math.pow(2,7),uO=Math.pow(2,14),hO=Math.pow(2,21),fO=Math.pow(2,28),dO=Math.pow(2,35),pO=Math.pow(2,42),gO=Math.pow(2,49),yO=Math.pow(2,56),wO=Math.pow(2,63),mO=function(t){return t<lO?1:t<uO?2:t<hO?3:t<fO?4:t<dO?5:t<pO?6:t<gO?7:t<yO?8:t<wO?9:10},bO={encode:iO,decode:aO,encodingLength:mO},Xg=bO;const Lh=(t,e,r=0)=>(Xg.encode(t,e,r),e),Mh=t=>Xg.encodingLength(t),ec=(t,e)=>{const r=e.byteLength,i=Mh(t),n=i+Mh(r),s=new Uint8Array(n+r);return Lh(t,s,0),Lh(r,s,i),s.set(e,n),new vO(t,r,e,s)};class vO{constructor(e,r,i,n){this.code=e,this.size=r,this.digest=i,this.bytes=n}}const Qg=({name:t,code:e,encode:r})=>new EO(t,e,r);class EO{constructor(e,r,i){this.name=e,this.code=r,this.encode=i}digest(e){if(e instanceof Uint8Array){const r=this.encode(e);return r instanceof Uint8Array?ec(this.code,r):r.then(i=>ec(this.code,i))}else throw Error("Unknown type, must be binary type")}}const e0=t=>async e=>new Uint8Array(await crypto.subtle.digest(t,e)),xO=Qg({name:"sha2-256",code:18,encode:e0("SHA-256")}),_O=Qg({name:"sha2-512",code:19,encode:e0("SHA-512")});var IO=Object.freeze({__proto__:null,sha256:xO,sha512:_O});const t0=0,SO="identity",r0=Gg,$O=t=>ec(t0,r0(t)),OO={code:t0,name:SO,encode:r0,digest:$O};var DO=Object.freeze({__proto__:null,identity:OO});new TextEncoder,new TextDecoder;const qh={...v6,...x6,...I6,...$6,...A6,...j6,...q6,...H6,...Z6,...rO};({...IO,...DO});function i0(t){return globalThis.Buffer!=null?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function AO(t=0){return globalThis.Buffer!=null&&globalThis.Buffer.allocUnsafe!=null?i0(globalThis.Buffer.allocUnsafe(t)):new Uint8Array(t)}function n0(t,e,r,i){return{name:t,prefix:e,encoder:{name:t,prefix:e,encode:r},decoder:{decode:i}}}const zh=n0("utf8","u",t=>"u"+new TextDecoder("utf8").decode(t),t=>new TextEncoder().encode(t.substring(1))),ra=n0("ascii","a",t=>{let e="a";for(let r=0;r<t.length;r++)e+=String.fromCharCode(t[r]);return e},t=>{t=t.substring(1);const e=AO(t.length);for(let r=0;r<t.length;r++)e[r]=t.charCodeAt(r);return e}),PO={utf8:zh,"utf-8":zh,hex:qh.base16,latin1:ra,ascii:ra,binary:ra,...qh};function CO(t,e="utf8"){const r=PO[e];if(!r)throw new Error(`Unsupported encoding "${e}"`);return(e==="utf8"||e==="utf-8")&&globalThis.Buffer!=null&&globalThis.Buffer.from!=null?i0(globalThis.Buffer.from(t,"utf-8")):r.decoder.decode(`${r.prefix}${t}`)}var BO=Object.defineProperty,TO=(t,e,r)=>e in t?BO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ut=(t,e,r)=>TO(t,typeof e!="symbol"?e+"":e,r);class RO{constructor(e,r){this.core=e,this.logger=r,Ut(this,"keychain",new Map),Ut(this,"name",B$),Ut(this,"version",T$),Ut(this,"initialized",!1),Ut(this,"storagePrefix",Wt),Ut(this,"init",async()=>{if(!this.initialized){const i=await this.getKeyChain();typeof i<"u"&&(this.keychain=i),this.initialized=!0}}),Ut(this,"has",i=>(this.isInitialized(),this.keychain.has(i))),Ut(this,"set",async(i,n)=>{this.isInitialized(),this.keychain.set(i,n),await this.persist()}),Ut(this,"get",i=>{this.isInitialized();const n=this.keychain.get(i);if(typeof n>"u"){const{message:s}=M("NO_MATCHING_KEY",`${this.name}: ${i}`);throw new Error(s)}return n}),Ut(this,"del",async i=>{this.isInitialized(),this.keychain.delete(i),await this.persist()}),this.core=e,this.logger=dt(r,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,Ra(e))}async getKeyChain(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(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 FO=Object.defineProperty,NO=(t,e,r)=>e in t?FO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Se=(t,e,r)=>NO(t,typeof e!="symbol"?e+"":e,r);class UO{constructor(e,r,i){this.core=e,this.logger=r,Se(this,"name",P$),Se(this,"keychain"),Se(this,"randomSessionIdentifier",Ka()),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=du(n),o=sp(s.publicKey);return this.clientId=o,o}),Se(this,"generateKeyPair",()=>{this.isInitialized();const n=bI();return this.setPrivateKey(n.publicKey,n.privateKey)}),Se(this,"signJWT",async n=>{this.isInitialized();const s=await this.getClientSeed(),o=du(s),a=this.randomSessionIdentifier;return await p2(a,n,C$,o)}),Se(this,"generateSharedKey",(n,s,o)=>{this.isInitialized();const a=this.getPrivateKey(n),c=vI(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=Pg(o),c=oi(s);if(ah(a))return _I(c,o==null?void 0:o.encoding);if(oh(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 EI({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=SI(s,o);if(ah(a)){const c=II(s,o==null?void 0:o.encoding);return si(c)}if(oh(a)){const c=a.receiverPublicKey,l=a.senderPublicKey;n=await this.generateSharedKey(c,l)}try{const c=this.getSymKey(n),l=xI({symKey:c,encoded:s,encoding:o==null?void 0:o.encoding});return si(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=In({encoded:n,encoding:s});return ci(o.type)}),Se(this,"getPayloadSenderPublicKey",(n,s=tt)=>{const o=In({encoded:n,encoding:s});return o.senderPublicKey?nt(o.senderPublicKey,Ge):void 0}),this.core=e,this.logger=dt(r,this.name),this.keychain=i||new RO(this.core,this.logger)}get context(){return st(this.logger)}async setPrivateKey(e,r){return await this.keychain.set(e,r),e}getPrivateKey(e){return this.keychain.get(e)}async getClientSeed(){let e="";try{e=this.keychain.get(Nh)}catch{e=Ka(),await this.keychain.set(Nh,e)}return CO(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 kO=Object.defineProperty,jO=Object.defineProperties,LO=Object.getOwnPropertyDescriptors,Vh=Object.getOwnPropertySymbols,MO=Object.prototype.hasOwnProperty,qO=Object.prototype.propertyIsEnumerable,tc=(t,e,r)=>e in t?kO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zO=(t,e)=>{for(var r in e||(e={}))MO.call(e,r)&&tc(t,r,e[r]);if(Vh)for(var r of Vh(e))qO.call(e,r)&&tc(t,r,e[r]);return t},VO=(t,e)=>jO(t,LO(e)),ot=(t,e,r)=>tc(t,typeof e!="symbol"?e+"":e,r);class HO extends $S{constructor(e,r){super(e,r),this.logger=e,this.core=r,ot(this,"messages",new Map),ot(this,"messagesWithoutClientAck",new Map),ot(this,"name",R$),ot(this,"version",F$),ot(this,"initialized",!1),ot(this,"storagePrefix",Wt),ot(this,"init",async()=>{if(!this.initialized){this.logger.trace("Initialized");try{const i=await this.getRelayerMessages();typeof i<"u"&&(this.messages=i);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(i){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(i)}finally{this.initialized=!0}}}),ot(this,"set",async(i,n,s)=>{this.isInitialized();const o=bt(n);let a=this.messages.get(i);if(typeof a>"u"&&(a={}),typeof a[o]<"u")return o;if(a[o]=n,this.messages.set(i,a),s===ys.inbound){const c=this.messagesWithoutClientAck.get(i)||{};this.messagesWithoutClientAck.set(i,VO(zO({},c),{[o]:n}))}return await this.persist(),o}),ot(this,"get",i=>{this.isInitialized();let n=this.messages.get(i);return typeof n>"u"&&(n={}),n}),ot(this,"getWithoutAck",i=>{this.isInitialized();const n={};for(const s of i){const o=this.messagesWithoutClientAck.get(s)||{};n[s]=Object.values(o)}return n}),ot(this,"has",(i,n)=>{this.isInitialized();const s=this.get(i),o=bt(n);return typeof s[o]<"u"}),ot(this,"ack",async(i,n)=>{this.isInitialized();const s=this.messagesWithoutClientAck.get(i);if(typeof s>"u")return;const o=bt(n);delete s[o],Object.keys(s).length===0?this.messagesWithoutClientAck.delete(i):this.messagesWithoutClientAck.set(i,s),await this.persist()}),ot(this,"del",async i=>{this.isInitialized(),this.messages.delete(i),this.messagesWithoutClientAck.delete(i),await this.persist()}),this.logger=dt(e,this.name),this.core=r}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,Ra(e))}async setRelayerMessagesWithoutClientAck(e){await this.core.storage.setItem(this.storageKeyWithoutClientAck,Ra(e))}async getRelayerMessages(){const e=await this.core.storage.getItem(this.storageKey);return typeof e<"u"?Fa(e):void 0}async getRelayerMessagesWithoutClientAck(){const e=await this.core.storage.getItem(this.storageKeyWithoutClientAck);return typeof e<"u"?Fa(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 KO=Object.defineProperty,WO=Object.defineProperties,GO=Object.getOwnPropertyDescriptors,Hh=Object.getOwnPropertySymbols,YO=Object.prototype.hasOwnProperty,ZO=Object.prototype.propertyIsEnumerable,rc=(t,e,r)=>e in t?KO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ei=(t,e)=>{for(var r in e||(e={}))YO.call(e,r)&&rc(t,r,e[r]);if(Hh)for(var r of Hh(e))ZO.call(e,r)&&rc(t,r,e[r]);return t},Kh=(t,e)=>WO(t,GO(e)),yt=(t,e,r)=>rc(t,typeof e!="symbol"?e+"":e,r);class JO extends OS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,yt(this,"events",new St.EventEmitter),yt(this,"name",U$),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(i,n,s)=>{var o,a,c,l,u;this.logger.debug("Publishing Payload"),this.logger.trace({type:"method",method:"publish",params:{topic:i,message:n,opts:s}});const h=(s==null?void 0:s.ttl)||N$,f=(s==null?void 0:s.prompt)||!1,d=(s==null?void 0:s.tag)||0,p=(s==null?void 0:s.id)||Rr().toString(),g=$i(Fs().protocol),w={id:p,method:(s==null?void 0:s.publishMethod)||g.publish,params:Ei({topic:i,message:n,ttl:h,prompt:f,tag:d,attestation:s==null?void 0:s.attestation},s==null?void 0:s.tvf)},I=`Failed to publish payload, please try again. id:${p} tag:${d}`;try{_e((o=w.params)==null?void 0:o.prompt)&&((a=w.params)==null||delete a.prompt),_e((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 D=Vt(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 D,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:i,message:n,opts:s}}),await Vt(C,this.publishTimeout,I)}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 i=>{var n,s,o,a,c;this.logger.debug("Publishing custom payload"),this.logger.trace({type:"method",method:"publishCustom",params:i});const{payload:l,opts:u={}}=i,{attestation:h,tvf:f,publishMethod:d,prompt:p,tag:g,ttl:w=L.FIVE_MINUTES}=u,I=u.id||Rr().toString(),C=$i(Fs().protocol),b=d||C.publish,v={id:I,method:b,params:Ei(Kh(Ei({},l),{ttl:w,prompt:p,tag:g,attestation:h}),f)},D=`Failed to publish custom payload, please try again. id:${I} tag:${g}`;try{_e((n=v.params)==null?void 0:n.prompt)&&((s=v.params)==null||delete s.prompt),_e((o=v.params)==null?void 0:o.tag)&&((a=v.params)==null||delete a.tag);const 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=Vt(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:${I} tag:${g}`);try{await A,this.events.removeListener(me.publish,R)}catch(U){this.queue.set(I,{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:I,payload:l,opts:u}}),await Vt(P,this.publishTimeout,D)}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(I)}}),yt(this,"on",(i,n)=>{this.events.on(i,n)}),yt(this,"once",(i,n)=>{this.events.once(i,n)}),yt(this,"off",(i,n)=>{this.events.off(i,n)}),yt(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.relayer=e,this.logger=dt(r,this.name),this.registerEventListeners()}get context(){return st(this.logger)}async rpcPublish(e,r){this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"message",direction:"outgoing",request:e});const i=await this.relayer.request(e);return this.relayer.events.emit(me.publish,Ei(Ei({},e),r)),this.logger.debug("Successfully Published Payload"),i}removeRequestFromQueue(e){this.queue.delete(e)}checkQueue(){this.queue.forEach(async(e,r)=>{var i;const n=e.attempt+1;this.queue.set(r,Kh(Ei({},e),{attempt:n})),this.logger.warn({},`Publisher: queue->publishing: ${e.request.id}, tag: ${(i=e.request.params)==null?void 0:i.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(fi.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 XO=Object.defineProperty,QO=(t,e,r)=>e in t?XO(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,xi=(t,e,r)=>QO(t,typeof e!="symbol"?e+"":e,r);class eD{constructor(){xi(this,"map",new Map),xi(this,"set",(e,r)=>{const i=this.get(e);this.exists(e,r)||this.map.set(e,[...i,r])}),xi(this,"get",e=>this.map.get(e)||[]),xi(this,"exists",(e,r)=>this.get(e).includes(r)),xi(this,"delete",(e,r)=>{if(typeof r>"u"){this.map.delete(e);return}if(!this.map.has(e))return;const i=this.get(e);if(!this.exists(e,r))return;const n=i.filter(s=>s!==r);if(!n.length){this.map.delete(e);return}this.map.set(e,n)}),xi(this,"clear",()=>{this.map.clear()})}get topics(){return Array.from(this.map.keys())}}var tD=Object.defineProperty,rD=Object.defineProperties,iD=Object.getOwnPropertyDescriptors,Wh=Object.getOwnPropertySymbols,nD=Object.prototype.hasOwnProperty,sD=Object.prototype.propertyIsEnumerable,ic=(t,e,r)=>e in t?tD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rn=(t,e)=>{for(var r in e||(e={}))nD.call(e,r)&&ic(t,r,e[r]);if(Wh)for(var r of Wh(e))sD.call(e,r)&&ic(t,r,e[r]);return t},ia=(t,e)=>rD(t,iD(e)),ce=(t,e,r)=>ic(t,typeof e!="symbol"?e+"":e,r);class oD extends PS{constructor(e,r){super(e,r),this.relayer=e,this.logger=r,ce(this,"subscriptions",new Map),ce(this,"topicMap",new eD),ce(this,"events",new St.EventEmitter),ce(this,"name",V$),ce(this,"version",H$),ce(this,"pending",new Map),ce(this,"cached",[]),ce(this,"initialized",!1),ce(this,"storagePrefix",Wt),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(i,n)=>{var s;this.isInitialized(),this.logger.debug("Subscribing Topic"),this.logger.trace({type:"method",method:"subscribe",params:{topic:i,opts:n}});try{const o=Fs(n),a={topic:i,relay:o,transportType:n==null?void 0:n.transportType};(s=n==null?void 0:n.internal)!=null&&s.skipSubscribe||this.pending.set(i,a);const c=await this.rpcSubscribe(i,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:i,opts:n}})),c}catch(o){throw this.logger.debug("Failed to Subscribe Topic"),this.logger.error(o),o}}),ce(this,"unsubscribe",async(i,n)=>{this.isInitialized(),typeof(n==null?void 0:n.id)<"u"?await this.unsubscribeById(i,n.id,n):await this.unsubscribeByTopic(i,n)}),ce(this,"isSubscribed",i=>new Promise(n=>{n(this.topicMap.topics.includes(i))})),ce(this,"isKnownTopic",i=>new Promise(n=>{n(this.topicMap.topics.includes(i)||this.pending.has(i)||this.cached.some(s=>s.topic===i))})),ce(this,"on",(i,n)=>{this.events.on(i,n)}),ce(this,"once",(i,n)=>{this.events.once(i,n)}),ce(this,"off",(i,n)=>{this.events.off(i,n)}),ce(this,"removeListener",(i,n)=>{this.events.removeListener(i,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 i=[];this.pending.forEach(n=>{i.push(n)}),await this.batchSubscribe(i)}),ce(this,"registerEventListeners",()=>{this.relayer.core.heartbeat.on(fi.pulse,async()=>{await this.checkPending()}),this.events.on(lt.created,async i=>{const n=lt.created;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()}),this.events.on(lt.deleted,async i=>{const n=lt.deleted;this.logger.info(`Emitting ${n}`),this.logger.debug({type:"event",event:n,data:i}),await this.persist()})}),this.relayer=e,this.logger=dt(r,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,r){let i=!1;try{i=this.getSubscription(e).topic===r}catch{}return i}reset(){this.cached=[],this.initialized=!0}onDisable(){this.values.length>0&&(this.cached=this.values),this.subscriptions.clear(),this.topicMap.clear()}async unsubscribeByTopic(e,r){const i=this.topicMap.get(e);await Promise.all(i.map(async n=>await this.unsubscribeById(e,n,r)))}async unsubscribeById(e,r,i){this.logger.debug("Unsubscribing Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}});try{const n=Fs(i);await this.restartToComplete({topic:e,id:r,relay:n}),await this.rpcUnsubscribe(e,r,n);const s=fe("USER_DISCONNECTED",`${this.name}, ${e}`);await this.onUnsubscribe(e,r,s),this.logger.debug("Successfully Unsubscribed Topic"),this.logger.trace({type:"method",method:"unsubscribe",params:{topic:e,id:r,opts:i}})}catch(n){throw this.logger.debug("Failed to Unsubscribe Topic"),this.logger.error(n),n}}async rpcSubscribe(e,r,i){var n,s;const o=await this.getSubscriptionId(e);if((n=i==null?void 0:i.internal)!=null&&n.skipSubscribe)return o;(!i||(i==null?void 0:i.transportType)===he.relay)&&await this.restartToComplete({topic:e,id:e,relay:r});const a={method:$i(r.protocol).subscribe,params:{topic:e}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:a});const c=(s=i==null?void 0:i.internal)==null?void 0:s.throwOnFailedPublish;try{if((i==null?void 0:i.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 Vt(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 Vt(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 r=e[0].relay,i={method:$i(r.protocol).batchSubscribe,params:{topics:e.map(n=>n.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});try{await await Vt(new Promise(n=>{this.relayer.request(i).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 r=e[0].relay,i={method:$i(r.protocol).batchFetchMessages,params:{topics:e.map(s=>s.topic)}};this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:i});let n;try{n=await await Vt(new Promise((s,o)=>{this.relayer.request(i).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,r,i){const n={method:$i(i.protocol).unsubscribe,params:{topic:e,id:r}};return this.logger.debug("Outgoing Relay Payload"),this.logger.trace({type:"payload",direction:"outgoing",request:n}),this.relayer.request(n)}onSubscribe(e,r){this.setSubscription(e,ia(rn({},r),{id:e})),this.pending.delete(r.topic)}onBatchSubscribe(e){e.length&&e.forEach(r=>{this.setSubscription(r.id,rn({},r)),this.pending.delete(r.topic)})}async onUnsubscribe(e,r,i){this.events.removeAllListeners(r),this.hasSubscription(r,e)&&this.deleteSubscription(r,i),await this.relayer.messages.del(e)}async setRelayerSubscriptions(e){await this.relayer.core.storage.setItem(this.storageKey,e)}async getRelayerSubscriptions(){return await this.relayer.core.storage.getItem(this.storageKey)}setSubscription(e,r){this.logger.debug("Setting subscription"),this.logger.trace({type:"method",method:"setSubscription",id:e,subscription:r}),this.addSubscription(e,r)}addSubscription(e,r){this.subscriptions.set(e,rn({},r)),this.topicMap.set(r.topic,e),this.events.emit(lt.created,r)}getSubscription(e){this.logger.debug("Getting subscription"),this.logger.trace({type:"method",method:"getSubscription",id:e});const r=this.subscriptions.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}deleteSubscription(e,r){this.logger.debug("Deleting subscription"),this.logger.trace({type:"method",method:"deleteSubscription",id:e,reason:r});const i=this.getSubscription(e);this.subscriptions.delete(e),this.topicMap.delete(i.topic,e),this.events.emit(lt.deleted,ia(rn({},i),{reason:r}))}async persist(){await this.setRelayerSubscriptions(this.values),this.events.emit(lt.sync)}async onRestart(){if(this.cached.length){const e=[...this.cached],r=Math.ceil(this.cached.length/this.batchSubscribeTopicsLimit);for(let i=0;i<r;i++){const 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(r=>{var i;return r.topic===((i=this.subscriptions.get(r.id))==null?void 0:i.topic)})){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),this.logger.error(`${this.name}: ${JSON.stringify(this.values)}`),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored subscriptions for ${this.name}`),this.logger.trace({type:"method",method:"restore",subscriptions:this.values})}catch(e){this.logger.debug(`Failed to Restore subscriptions for ${this.name}`),this.logger.error(e)}}async batchSubscribe(e){e.length&&(await this.rpcBatchSubscribe(e),this.onBatchSubscribe(await Promise.all(e.map(async r=>ia(rn({},r),{id:await this.getSubscriptionId(r.topic)})))))}async batchFetchMessages(e){if(!e.length)return;this.logger.trace(`Fetching batch messages for ${e.length} subscriptions`);const r=await this.rpcBatchFetchMessages(e);r&&r.messages&&(await k3(L.toMiliseconds(L.ONE_SECOND)),await this.relayer.handleBatchMessageEvents(r.messages))}async onConnect(){await this.restart(),this.reset()}onDisconnect(){this.onDisable()}isInitialized(){if(!this.initialized){const{message:e}=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 aD=Object.defineProperty,Gh=Object.getOwnPropertySymbols,cD=Object.prototype.hasOwnProperty,lD=Object.prototype.propertyIsEnumerable,nc=(t,e,r)=>e in t?aD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Yh=(t,e)=>{for(var r in e||(e={}))cD.call(e,r)&&nc(t,r,e[r]);if(Gh)for(var r of Gh(e))lD.call(e,r)&&nc(t,r,e[r]);return t},ne=(t,e,r)=>nc(t,typeof e!="symbol"?e+"":e,r);class uD extends DS{constructor(e){var r;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",j$),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 i=>{var n,s;this.logger.debug("Publishing Request Payload");const o=i.id||Rr().toString();await this.toEstablishConnection();try{this.logger.trace({id:o,method:i.method,topic:(n=i.params)==null?void 0:n.topic},"relayer.request - publishing...");const a=`${o}:${((s=i.params)==null?void 0:s.tag)||""}`;this.requestsInFlight.push(a);const c=await this.provider.request(i);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 i,n,s,o;try{this.logger.debug({},"pingTimeout: Connection stalled, terminating..."),(o=(s=(n=(i=this.provider)==null?void 0:i.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",i=>{this.onProviderPayload(i),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",i=>{this.logger.fatal(`Fatal socket error: ${i.message}`),this.events.emit(me.error,i),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=Zc({logger:(r=e.logger)!=null?r:k$,name:this.name}),this.messages=new HO(this.logger,e.core),this.subscriber=new oD(this,this.logger),this.publisher=new JO(this,this.logger),this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Kg,x3()?this.packageName=Du():_3()&&(this.bundleId=Du()),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,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===1||!1}get connecting(){var e,r,i;return((i=(r=(e=this.provider)==null?void 0:e.connection)==null?void 0:r.socket)==null?void 0:i.readyState)===0||this.connectPromise!==void 0||!1}async publish(e,r,i){this.isInitialized(),await this.publisher.publish(e,r,i),await this.recordMessageEvent({topic:e,message:r,publishedAt:Date.now(),transportType:he.relay},ys.outbound)}async publishCustom(e){this.isInitialized(),await this.publisher.publishCustom(e)}async subscribe(e,r){var i,n,s;this.isInitialized(),(!(r!=null&&r.transportType)||(r==null?void 0:r.transportType)==="relay")&&await this.toEstablishConnection();const o=typeof((i=r==null?void 0:r.internal)==null?void 0:i.throwOnFailedPublish)>"u"?!0:(n=r==null?void 0:r.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,Yh({internal:{throwOnFailedPublish:o}},r)).catch(f=>{o&&h(f)})||a,u()})]),a}async unsubscribe(e,r){this.isInitialized(),await this.subscriber.unsubscribe(e,r)}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async transportDisconnect(){this.provider.disconnect&&(this.hasExperiencedNetworkDisruption||this.connected)?await Vt(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(r,i)=>{await this.connect(e).then(r).catch(i).finally(()=>{this.connectPromise=void 0})}),await this.connectPromise),!this.connected)throw new Error(`Couldn't establish socket connection to the relay server: ${this.relayUrl}`)}async restartTransport(e){this.logger.debug({},"Restarting transport..."),!this.connectionAttemptInProgress&&(this.relayUrl=e||this.relayUrl,await this.confirmOnlineStateOrThrow(),await this.transportClose(),await this.transportOpen())}async confirmOnlineStateOrThrow(){if(!await vh())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 r=e.sort((i,n)=>i.publishedAt-n.publishedAt);this.logger.debug(`Batch of ${r.length} message events sorted`);for(const i of r)try{await this.onMessageEvent(i)}catch(n){this.logger.warn(n,"Error while processing batch message event: "+(n==null?void 0:n.message))}this.logger.trace(`Batch of ${r.length} message events processed`)}async onLinkMessageEvent(e,r){const{topic:i}=e;if(!r.sessionExists){const n=we(L.FIVE_MINUTES),s={topic:i,expiry:n,relay:{protocol:"irn"},active:!1};await this.core.pairing.pairings.set(i,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 r=1;for(;r<6;){try{if(this.transportExplicitlyClosed)break;this.logger.debug({},`Connecting to ${this.relayUrl}, attempt: ${r}...`),await this.createProvider(),await new Promise(async(i,n)=>{const s=()=>{n(new Error("Connection interrupted while trying to connect"))};this.provider.once(gt.disconnect,s),await Vt(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,i()})}catch(i){await this.subscriber.stop();const n=i;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: ${r}`);break}await new Promise(i=>setTimeout(i,L.toMiliseconds(r*1))),r++}}startPingTimeout(){var e,r,i,n,s;if(As())try{(r=(e=this.provider)==null?void 0:e.connection)!=null&&r.socket&&((s=(n=(i=this.provider)==null?void 0:i.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 Qc(new O$(D3({sdkVersion:Xa,protocol:this.protocol,version:this.version,relayUrl:this.relayUrl,projectId:this.projectId,auth:e,useOnCloseEvent:!0,bundleId:this.bundleId,packageName:this.packageName}))),this.registerProviderListeners()}async recordMessageEvent(e,r){const{topic:i,message:n}=e;await this.messages.set(i,n,r)}async shouldIgnoreMessageEvent(e){const{topic:r,message:i}=e;if(!i||i.length===0)return this.logger.warn(`Ignoring invalid/empty message: ${i}`),!0;if(!await this.subscriber.isKnownTopic(r))return this.logger.warn(`Ignoring message for unknown topic ${r}`),!0;const n=this.messages.has(r,i);return n&&this.logger.warn(`Ignoring duplicate message: ${i}`),n}async onProviderPayload(e){if(this.logger.debug("Incoming Relay Payload"),this.logger.trace({type:"payload",direction:"incoming",payload:e}),Xc(e)){if(!e.method.endsWith(L$))return;const r=e.params,{topic:i,message:n,publishedAt:s,attestation:o}=r.data,a={topic:i,message:n,publishedAt:s,transportType:he.relay,attestation:o};this.logger.debug("Emitting Relayer Payload"),this.logger.trace(Yh({type:"event",event:r.id},a)),this.events.emit(r.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 r=$n(e.id,!0);await this.provider.connection.send(r)}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 vh();S8(async r=>{e!==r&&(e=r,r?await this.transportOpen().catch(i=>this.logger.error(i,i==null?void 0:i.message)):(this.hasExperiencedNetworkDisruption=!0,await this.transportDisconnect(),this.transportExplicitlyClosed=!1))}),this.core.heartbeat.on(fi.pulse,async()=>{if(!this.transportExplicitlyClosed&&!this.connected&&D8())try{await this.confirmOnlineStateOrThrow(),await this.transportOpen()}catch(r){this.logger.warn(r,r==null?void 0:r.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(M$)))))}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 hD(t,e){return t===e||Number.isNaN(t)&&Number.isNaN(e)}function Zh(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function Jh(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const fD="[object RegExp]",dD="[object String]",pD="[object Number]",gD="[object Boolean]",Xh="[object Arguments]",yD="[object Symbol]",wD="[object Date]",mD="[object Map]",bD="[object Set]",vD="[object Array]",ED="[object Function]",xD="[object ArrayBuffer]",na="[object Object]",_D="[object Error]",ID="[object DataView]",SD="[object Uint8Array]",$D="[object Uint8ClampedArray]",OD="[object Uint16Array]",DD="[object Uint32Array]",AD="[object BigUint64Array]",PD="[object Int8Array]",CD="[object Int16Array]",BD="[object Int32Array]",TD="[object BigInt64Array]",RD="[object Float32Array]",FD="[object Float64Array]";function ND(){}function Qh(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 UD(t,e,r){return un(t,e,void 0,void 0,void 0,void 0,r)}function un(t,e,r,i,n,s,o){const a=o(t,e,r,i,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,r,i){if(Object.is(t,e))return!0;let n=Jh(t),s=Jh(e);if(n===Xh&&(n=na),s===Xh&&(s=na),n!==s)return!1;switch(n){case dD:return t.toString()===e.toString();case pD:{const c=t.valueOf(),l=e.valueOf();return hD(c,l)}case gD:case wD:case yD:return Object.is(t.valueOf(),e.valueOf());case fD:return t.source===e.source&&t.flags===e.flags;case ED:return t===e}r=r??new Map;const o=r.get(t),a=r.get(e);if(o!=null&&a!=null)return o===e;r.set(t,e),r.set(e,t);try{switch(n){case mD:{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,r,i))return!1;return!0}case bD:{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,r,i));if(f===-1)return!1;l.splice(f,1)}return!0}case vD:case SD:case $D:case OD:case DD:case AD:case PD:case CD:case BD:case TD:case RD:case FD:{if(typeof re<"u"&&re.isBuffer(t)!==re.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,r,i))return!1;return!0}case xD:return t.byteLength!==e.byteLength?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case ID:return t.byteLength!==e.byteLength||t.byteOffset!==e.byteOffset?!1:yn(new Uint8Array(t),new Uint8Array(e),r,i);case _D:return t.name===e.name&&t.message===e.message;case na:{if(!(yn(t.constructor,e.constructor,r,i)||Qh(t)&&Qh(e)))return!1;const c=[...Object.keys(t),...Zh(t)],l=[...Object.keys(e),...Zh(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,r,i))return!1}return!0}default:return!1}}finally{r.delete(t),r.delete(e)}}function kD(t,e){return UD(t,e,ND)}var jD=Object.defineProperty,ef=Object.getOwnPropertySymbols,LD=Object.prototype.hasOwnProperty,MD=Object.prototype.propertyIsEnumerable,sc=(t,e,r)=>e in t?jD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,tf=(t,e)=>{for(var r in e||(e={}))LD.call(e,r)&&sc(t,r,e[r]);if(ef)for(var r of ef(e))MD.call(e,r)&&sc(t,r,e[r]);return t},Ze=(t,e,r)=>sc(t,typeof e!="symbol"?e+"":e,r);class pi extends AS{constructor(e,r,i,n=Wt,s=void 0){super(e,r,i,n),this.core=e,this.logger=r,this.name=i,Ze(this,"map",new Map),Ze(this,"version",q$),Ze(this,"cached",[]),Ze(this,"initialized",!1),Ze(this,"getKey"),Ze(this,"storagePrefix",Wt),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&&!_e(o)?this.map.set(this.getKey(o),o):r8(o)?this.map.set(o.id,o):i8(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=>kD(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=tf(tf({},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(r,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 r=this.map.get(e);if(!r){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:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.error(i),new Error(i)}return r}async persist(){await this.setDataStore(this.values)}async restore(){try{const e=await this.getDataStore();if(typeof e>"u"||!e.length)return;if(this.map.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored value for ${this.name}`),this.logger.trace({type:"method",method:"restore",value:this.values})}catch(e){this.logger.debug(`Failed to Restore value for ${this.name}`),this.logger.error(e)}}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var qD=Object.defineProperty,zD=(t,e,r)=>e in t?qD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ee=(t,e,r)=>zD(t,typeof e!="symbol"?e+"":e,r);class VD{constructor(e,r){this.core=e,this.logger=r,ee(this,"name",K$),ee(this,"version",W$),ee(this,"events",new dc),ee(this,"pairings"),ee(this,"initialized",!1),ee(this,"storagePrefix",Wt),ee(this,"ignoredPayloadTypes",[hr]),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:i})=>{this.isInitialized(),this.registeredMethods=[...new Set([...this.registeredMethods,...i])]}),ee(this,"create",async i=>{this.isInitialized();const n=Ka(),s=await this.core.crypto.setSymKey(n),o=we(L.FIVE_MINUTES),a={protocol:Hg},c={topic:s,expiry:o,relay:a,active:!1,methods:i==null?void 0:i.methods},l=hh({protocol:this.core.protocol,version:this.core.version,topic:s,symKey:n,relay:a,expiryTimestamp:o,methods:i==null?void 0:i.methods});return this.events.emit(Yr.create,c),this.core.expirer.set(s,o),await this.pairings.set(s,c),await this.core.relayer.subscribe(s,{transportType:i==null?void 0:i.transportType,internal:i==null?void 0:i.internal}),{topic:s,uri:l}}),ee(this,"pair",async i=>{this.isInitialized();const n=this.core.eventClient.createEvent({properties:{topic:i==null?void 0:i.uri,trace:[jt.pairing_started]}});this.isValidPair(i,n);const{topic:s,symKey:o,relay:a,expiryTimestamp:c,methods:l}=uh(i.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(ir.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),i.activatePairing&&await this.activate({topic:s}),this.events.emit(Yr.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(ir.no_internet_connection)}try{await this.core.relayer.subscribe(s,{relay:a})}catch(d){throw n.setError(ir.subscribe_pairing_topic_failure),d}return n.addTrace(jt.subscribe_pairing_topic_success),f}),ee(this,"activate",async({topic:i})=>{this.isInitialized();const n=we(L.FIVE_MINUTES);this.core.expirer.set(i,n),await this.pairings.update(i,{active:!0,expiry:n})}),ee(this,"ping",async i=>{this.isInitialized(),await this.isValidPing(i),this.logger.warn("ping() is deprecated and will be removed in the next major release.");const{topic:n}=i;if(this.pairings.keys.includes(n)){const s=await this.sendRequest(n,"wc_pairingPing",{}),{done:o,resolve:a,reject:c}=Kr();this.events.once(ae("pairing_ping",s),({error:l})=>{l?c(l):a()}),await o()}}),ee(this,"updateExpiry",async({topic:i,expiry:n})=>{this.isInitialized(),await this.pairings.update(i,{expiry:n})}),ee(this,"updateMetadata",async({topic:i,metadata:n})=>{this.isInitialized(),await this.pairings.update(i,{peerMetadata:n})}),ee(this,"getPairings",()=>(this.isInitialized(),this.pairings.values)),ee(this,"disconnect",async i=>{this.isInitialized(),await this.isValidDisconnect(i);const{topic:n}=i;this.pairings.keys.includes(n)&&(await this.sendRequest(n,"wc_pairingDelete",fe("USER_DISCONNECTED")),await this.deletePairing(n))}),ee(this,"formatUriFromPairing",i=>{this.isInitialized();const{topic:n,relay:s,expiry:o,methods:a}=i,c=this.core.crypto.keychain.get(n);return hh({protocol:this.core.protocol,version:this.core.version,topic:n,symKey:c,relay:s,expiryTimestamp:o,methods:a})}),ee(this,"sendRequest",async(i,n,s)=>{const o=Ct(n,s),a=await this.core.crypto.encode(i,o),c=en[n].req;return this.core.history.set(i,o),this.core.relayer.publish(i,a,c),o.id}),ee(this,"sendResult",async(i,n,s)=>{const o=$n(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).request.method,l=en[c].res;await this.core.relayer.publish(n,a,l),await this.core.history.resolve(o)}),ee(this,"sendError",async(i,n,s)=>{const o=oo(i,s),a=await this.core.crypto.encode(n,o),c=(await this.core.history.get(n,i)).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(i,n)=>{await this.core.relayer.unsubscribe(i),await Promise.all([this.pairings.delete(i,fe("USER_DISCONNECTED")),this.core.crypto.deleteSymKey(i),n?Promise.resolve():this.core.expirer.del(i)])}),ee(this,"cleanup",async()=>{const i=this.pairings.getAll().filter(n=>qt(n.expiry));await Promise.all(i.map(n=>this.deletePairing(n.topic)))}),ee(this,"onRelayEventRequest",async i=>{const{topic:n,payload:s}=i;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 i=>{const{topic:n,payload:s}=i,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(i,n)=>{const{id:s}=n;try{this.isValidPing({topic:i}),await this.sendResult(s,i,!0),this.events.emit(Yr.ping,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onPairingPingResponse",(i,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(i,n)=>{const{id:s}=n;try{this.isValidDisconnect({topic:i}),await this.deletePairing(i),this.events.emit(Yr.delete,{id:s,topic:i})}catch(o){await this.sendError(s,i,o),this.logger.error(o)}}),ee(this,"onUnknownRpcMethodRequest",async(i,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,i,a),this.logger.error(a)}catch(a){await this.sendError(s,i,a),this.logger.error(a)}}),ee(this,"onUnknownRpcMethodResponse",i=>{this.registeredMethods.includes(i)||this.logger.error(fe("WC_METHOD_UNSUPPORTED",i))}),ee(this,"isValidPair",(i,n)=>{var s;if(!Xe(i)){const{message:a}=M("MISSING_OR_INVALID",`pair() params: ${i}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(!t8(i.uri)){const{message:a}=M("MISSING_OR_INVALID",`pair() uri: ${i.uri}`);throw n.setError(ir.malformed_pairing_uri),new Error(a)}const o=uh(i==null?void 0:i.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(ir.malformed_pairing_uri),new Error(a)}if(!(o!=null&&o.symKey)){const{message:a}=M("MISSING_OR_INVALID","pair() uri#symKey");throw n.setError(ir.malformed_pairing_uri),new Error(a)}if(o!=null&&o.expiryTimestamp&&L.toMiliseconds(o==null?void 0:o.expiryTimestamp)<Date.now()){n.setError(ir.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 i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`ping() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidDisconnect",async i=>{if(!Xe(i)){const{message:s}=M("MISSING_OR_INVALID",`disconnect() params: ${i}`);throw new Error(s)}const{topic:n}=i;await this.isValidPairingTopic(n)}),ee(this,"isValidPairingTopic",async i=>{if(!be(i,!1)){const{message:n}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${i}`);throw new Error(n)}if(!this.pairings.keys.includes(i)){const{message:n}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${i}`);throw new Error(n)}if(qt(this.pairings.get(i).expiry)){await this.deletePairing(i);const{message:n}=M("EXPIRED",`pairing topic: ${i}`);throw new Error(n)}}),this.core=e,this.logger=dt(r,this.name),this.pairings=new pi(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:r,message:i,transportType:n}=e;if(this.pairings.keys.includes(r)&&n!==he.link_mode&&!this.ignoredPayloadTypes.includes(this.core.crypto.getPayloadType(i)))try{const s=await this.core.crypto.decode(r,i);Xc(s)?(this.core.history.set(r,s),await this.onRelayEventRequest({topic:r,payload:s})):ao(s)&&(await this.core.history.resolve(s),await this.onRelayEventResponse({topic:r,payload:s}),this.core.history.delete(r,s.id)),await this.core.relayer.messages.ack(r,i)}catch(s){this.logger.error(s)}})}registerExpirerEvents(){this.core.expirer.on(wt.expired,async e=>{const{topic:r}=Bp(e.target);r&&this.pairings.keys.includes(r)&&(await this.deletePairing(r,!0),this.events.emit(Yr.expire,{topic:r}))})}}var HD=Object.defineProperty,KD=(t,e,r)=>e in t?HD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Be=(t,e,r)=>KD(t,typeof e!="symbol"?e+"":e,r);class WD extends SS{constructor(e,r){super(e,r),this.core=e,this.logger=r,Be(this,"records",new Map),Be(this,"events",new St.EventEmitter),Be(this,"name",G$),Be(this,"version",Y$),Be(this,"cached",[]),Be(this,"initialized",!1),Be(this,"storagePrefix",Wt),Be(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.records.set(i.id,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),Be(this,"set",(i,n,s)=>{if(this.isInitialized(),this.logger.debug("Setting JSON-RPC request history record"),this.logger.trace({type:"method",method:"set",topic:i,request:n,chainId:s}),this.records.has(n.id))return;const o={id:n.id,topic:i,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(Ot.created,o)}),Be(this,"resolve",async i=>{if(this.isInitialized(),this.logger.debug("Updating JSON-RPC response history record"),this.logger.trace({type:"method",method:"update",response:i}),!this.records.has(i.id))return;const n=await this.getRecord(i.id);typeof n.response>"u"&&(n.response=vt(i)?{error:i.error}:{result:i.result},this.records.set(n.id,n),this.persist(),this.events.emit(Ot.updated,n))}),Be(this,"get",async(i,n)=>(this.isInitialized(),this.logger.debug("Getting record"),this.logger.trace({type:"method",method:"get",topic:i,id:n}),await this.getRecord(n))),Be(this,"delete",(i,n)=>{this.isInitialized(),this.logger.debug("Deleting record"),this.logger.trace({type:"method",method:"delete",id:n}),this.values.forEach(s=>{if(s.topic===i){if(typeof n<"u"&&s.id!==n)return;this.records.delete(s.id),this.events.emit(Ot.deleted,s)}}),this.persist()}),Be(this,"exists",async(i,n)=>(this.isInitialized(),this.records.has(n)?(await this.getRecord(n)).topic===i:!1)),Be(this,"on",(i,n)=>{this.events.on(i,n)}),Be(this,"once",(i,n)=>{this.events.once(i,n)}),Be(this,"off",(i,n)=>{this.events.off(i,n)}),Be(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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(r=>{if(typeof r.response<"u")return;const i={topic:r.topic,request:Ct(r.request.method,r.request.params,r.id),chainId:r.chainId};return e.push(i)}),e}async setJsonRpcRecords(e){await this.core.storage.setItem(this.storageKey,e)}async getJsonRpcRecords(){return await this.core.storage.getItem(this.storageKey)}getRecord(e){this.isInitialized();const r=this.records.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw new Error(i)}return r}async persist(){await this.setJsonRpcRecords(this.values),this.events.emit(Ot.sync)}async restore(){try{const e=await this.getJsonRpcRecords();if(typeof e>"u"||!e.length)return;if(this.records.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored records for ${this.name}`),this.logger.trace({type:"method",method:"restore",records:this.values})}catch(e){this.logger.debug(`Failed to Restore records for ${this.name}`),this.logger.error(e)}}registerEventListeners(){this.events.on(Ot.created,e=>{const r=Ot.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.updated,e=>{const r=Ot.updated;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.events.on(Ot.deleted,e=>{const r=Ot.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,record:e})}),this.core.heartbeat.on(fi.pulse,()=>{this.cleanup()})}cleanup(){try{this.isInitialized();let e=!1;this.records.forEach(r=>{L.toMiliseconds(r.expiry||0)-Date.now()<=0&&(this.logger.info(`Deleting expired history log: ${r.id}`),this.records.delete(r.id),this.events.emit(Ot.deleted,r,!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 GD=Object.defineProperty,YD=(t,e,r)=>e in t?GD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ze=(t,e,r)=>YD(t,typeof e!="symbol"?e+"":e,r);class ZD extends CS{constructor(e,r){super(e,r),this.core=e,this.logger=r,ze(this,"expirations",new Map),ze(this,"events",new St.EventEmitter),ze(this,"name",Z$),ze(this,"version",J$),ze(this,"cached",[]),ze(this,"initialized",!1),ze(this,"storagePrefix",Wt),ze(this,"init",async()=>{this.initialized||(this.logger.trace("Initialized"),await this.restore(),this.cached.forEach(i=>this.expirations.set(i.target,i)),this.cached=[],this.registerEventListeners(),this.initialized=!0)}),ze(this,"has",i=>{try{const n=this.formatTarget(i);return typeof this.getExpiration(n)<"u"}catch{return!1}}),ze(this,"set",(i,n)=>{this.isInitialized();const s=this.formatTarget(i),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",i=>{this.isInitialized();const n=this.formatTarget(i);return this.getExpiration(n)}),ze(this,"del",i=>{if(this.isInitialized(),this.has(i)){const n=this.formatTarget(i),s=this.getExpiration(n);this.expirations.delete(n),this.events.emit(wt.deleted,{target:n,expiration:s})}}),ze(this,"on",(i,n)=>{this.events.on(i,n)}),ze(this,"once",(i,n)=>{this.events.once(i,n)}),ze(this,"off",(i,n)=>{this.events.off(i,n)}),ze(this,"removeListener",(i,n)=>{this.events.removeListener(i,n)}),this.logger=dt(r,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 A3(e);if(typeof e=="number")return P3(e);const{message:r}=M("UNKNOWN_TYPE",`Target type: ${typeof e}`);throw new Error(r)}async setExpirations(e){await this.core.storage.setItem(this.storageKey,e)}async getExpirations(){return await this.core.storage.getItem(this.storageKey)}async persist(){await this.setExpirations(this.values),this.events.emit(wt.sync)}async restore(){try{const e=await this.getExpirations();if(typeof e>"u"||!e.length)return;if(this.expirations.size){const{message:r}=M("RESTORE_WILL_OVERRIDE",this.name);throw this.logger.error(r),new Error(r)}this.cached=e,this.logger.debug(`Successfully Restored expirations for ${this.name}`),this.logger.trace({type:"method",method:"restore",expirations:this.values})}catch(e){this.logger.debug(`Failed to Restore expirations for ${this.name}`),this.logger.error(e)}}getExpiration(e){const r=this.expirations.get(e);if(!r){const{message:i}=M("NO_MATCHING_KEY",`${this.name}: ${e}`);throw this.logger.warn(i),new Error(i)}return r}checkExpiry(e,r){const{expiry:i}=r;L.toMiliseconds(i)-Date.now()<=0&&this.expire(e,r)}expire(e,r){this.expirations.delete(e),this.events.emit(wt.expired,{target:e,expiration:r})}checkExpirations(){this.core.relayer.connected&&this.expirations.forEach((e,r)=>this.checkExpiry(r,e))}registerEventListeners(){this.core.heartbeat.on(fi.pulse,()=>this.checkExpirations()),this.events.on(wt.created,e=>{const r=wt.created;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.expired,e=>{const r=wt.expired;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()}),this.events.on(wt.deleted,e=>{const r=wt.deleted;this.logger.info(`Emitting ${r}`),this.logger.debug({type:"event",event:r,data:e}),this.persist()})}isInitialized(){if(!this.initialized){const{message:e}=M("NOT_INITIALIZED",this.name);throw new Error(e)}}}var JD=Object.defineProperty,XD=(t,e,r)=>e in t?JD(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ye=(t,e,r)=>XD(t,typeof e!="symbol"?e+"":e,r);class QD extends BS{constructor(e,r,i){super(e,r,i),this.core=e,this.logger=r,this.store=i,ye(this,"name",X$),ye(this,"abortController"),ye(this,"isDevEnv"),ye(this,"verifyUrlV3",e6),ye(this,"storagePrefix",Wt),ye(this,"version",Vg),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(!Mi()||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=ii(),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=I=>{if(I.data&&typeof I.data=="string")try{const C=JSON.parse(I.data);if(C.type==="verify_attestation"){if(Pa(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(Pa(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 t6.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=OI(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(r,this.name),this.abortController=new AbortController,this.isDevEnv=jc(),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 e4=Object.defineProperty,t4=(t,e,r)=>e in t?e4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,rf=(t,e,r)=>t4(t,typeof e!="symbol"?e+"":e,r);class r4 extends TS{constructor(e,r){super(e,r),this.projectId=e,this.logger=r,rf(this,"context",r6),rf(this,"registerDeviceToken",async i=>{const{clientId:n,token:s,notificationType:o,enableEncrypted:a=!1}=i,c=`${i6}/${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(r,this.context)}}var i4=Object.defineProperty,nf=Object.getOwnPropertySymbols,n4=Object.prototype.hasOwnProperty,s4=Object.prototype.propertyIsEnumerable,oc=(t,e,r)=>e in t?i4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,nn=(t,e)=>{for(var r in e||(e={}))n4.call(e,r)&&oc(t,r,e[r]);if(nf)for(var r of nf(e))s4.call(e,r)&&oc(t,r,e[r]);return t},$e=(t,e,r)=>oc(t,typeof e!="symbol"?e+"":e,r);class o4 extends RS{constructor(e,r,i=!0){super(e,r,i),this.core=e,this.logger=r,$e(this,"context",s6),$e(this,"storagePrefix",Wt),$e(this,"storageVersion",n6),$e(this,"events",new Map),$e(this,"shouldPersist",!1),$e(this,"init",async()=>{if(!jc())try{const n={eventId:Pu(),timestamp:Date.now(),domain:this.getAppDomain(),props:{event:"INIT",type:"",properties:{client_id:await this.core.crypto.getClientId(),user_agent:Pp(this.core.relayer.protocol,this.core.relayer.version,Xa)}}};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=Pu(),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(fi.pulse,async()=>{this.shouldPersist&&await this.persist(),this.events.forEach(n=>{L.fromMiliseconds(Date.now())-L.fromMiliseconds(n.timestamp)>o6&&(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(`${a6}?projectId=${this.core.projectId}&st=events_sdk&sv=js-${Xa}${s}`,{method:"POST",body:JSON.stringify(n)})}),$e(this,"getAppDomain",()=>Ap().url),this.logger=dt(r,this.context),this.telemetryEnabled=i,i?this.restore().then(async()=>{await this.submit(),this.setEventListeners()}):this.persist()}get storageKey(){return this.storagePrefix+this.storageVersion+this.core.customStoragePrefix+"//"+this.context}}var a4=Object.defineProperty,sf=Object.getOwnPropertySymbols,c4=Object.prototype.hasOwnProperty,l4=Object.prototype.propertyIsEnumerable,ac=(t,e,r)=>e in t?a4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,of=(t,e)=>{for(var r in e||(e={}))c4.call(e,r)&&ac(t,r,e[r]);if(sf)for(var r of sf(e))l4.call(e,r)&&ac(t,r,e[r]);return t},le=(t,e,r)=>ac(t,typeof e!="symbol"?e+"":e,r);let u4=class s0 extends ES{constructor(e){var r;super(e),le(this,"protocol",zg),le(this,"version",Vg),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 i=this.getGlobalCore(e==null?void 0:e.customStoragePrefix);if(i)try{return this.customStoragePrefix=i.customStoragePrefix,this.logger=i.logger,this.heartbeat=i.heartbeat,this.crypto=i.crypto,this.history=i.history,this.expirer=i.expirer,this.storage=i.storage,this.relayer=i.relayer,this.pairing=i.pairing,this.verify=i.verify,this.echoClient=i.echoClient,this.linkModeSupportedApps=i.linkModeSupportedApps,this.eventClient=i.eventClient,this.initialized=i.initialized,this.logChunkController=i.logChunkController,i}catch(a){console.warn("Failed to copy global core",a)}this.projectId=e==null?void 0:e.projectId,this.relayUrl=(e==null?void 0:e.relayUrl)||Kg,this.customStoragePrefix=e!=null&&e.customStoragePrefix?`:${e.customStoragePrefix}`:"";const n=c3({level:typeof(e==null?void 0:e.logger)=="string"&&e.logger?e.logger:D$.logger,name:Us}),{logger:s,chunkLoggerController:o}=Op({opts:n,maxSizeInBytes:e==null?void 0:e.maxLogBlobSizeInBytes,loggerOverride:e==null?void 0:e.logger});this.logChunkController=o,(r=this.logChunkController)!=null&&r.downloadLogsBlobInBrowser&&(window.downloadLogsBlobInBrowser=async()=>{var a,c;(a=this.logChunkController)!=null&&a.downloadLogsBlobInBrowser&&((c=this.logChunkController)==null||c.downloadLogsBlobInBrowser({clientId:await this.crypto.getClientId()}))}),this.logger=dt(s,this.name),this.heartbeat=new k8,this.crypto=new UO(this,this.logger,e==null?void 0:e.keychain),this.history=new WD(this,this.logger),this.expirer=new ZD(this,this.logger),this.storage=e!=null&&e.storage?e.storage:new mS(of(of({},A$),e==null?void 0:e.storageOptions)),this.relayer=new uD({core:this,logger:this.logger,relayUrl:this.relayUrl,projectId:this.projectId}),this.pairing=new VD(this,this.logger),this.verify=new QD(this,this.logger,this.storage),this.echoClient=new r4(this.projectId||"",this.logger),this.linkModeSupportedApps=[],this.eventClient=new o4(this,this.logger,e==null?void 0:e.telemetryEnabled),this.setGlobalCore(this)}static async init(e){const r=new s0(e);await r.initialize();const i=await r.crypto.getClientId();return await r.storage.setItem(z$,i),r}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(Uh,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(Uh)||[],this.initialized=!0,this.logger.info("Core Initialization Success")}catch(e){throw this.logger.warn(e,`Core Initialization Failure at epoch ${Date.now()}`),this.logger.error(e.message),e}}getGlobalCore(e=""){try{if(this.isGlobalCoreDisabled())return;const r=`_walletConnectCore_${e}`,i=`${r}_count`;return globalThis[i]=(globalThis[i]||0)+1,globalThis[i]>1&&console.warn(`WalletConnect Core is already initialized. This is probably a mistake and can lead to unexpected behavior. Init() was called ${globalThis[i]} times.`),globalThis[r]}catch(r){console.warn("Failed to get global WalletConnect core",r);return}}setGlobalCore(e){var r;try{if(this.isGlobalCoreDisabled())return;const i=`_walletConnectCore_${((r=e.opts)==null?void 0:r.customStoragePrefix)||""}`;globalThis[i]=e}catch(i){console.warn("Failed to set global WalletConnect core",i)}}isGlobalCoreDisabled(){try{return typeof xt<"u"&&{}.DISABLE_GLOBAL_CORE==="true"}catch{return!0}}};const h4=u4,o0="wc",a0=2,c0="client",el=`${o0}@${a0}:${c0}:`,sa={name:c0,logger:"error",controller:!1,relayUrl:"wss://relay.walletconnect.org"},af="WALLETCONNECT_DEEPLINK_CHOICE",f4="proposal",cf="Proposal expired",d4="session",_i=L.SEVEN_DAYS,p4="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}}},oa={min:L.FIVE_MINUTES,max:L.SEVEN_DAYS},kt={idle:"IDLE",active:"ACTIVE"},g4={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:""}},y4="request",w4=["wc_sessionPropose","wc_sessionRequest","wc_authRequest","wc_sessionAuthenticate"],m4="wc",b4="auth",v4="authKeys",E4="pairingTopics",x4="requests",lo=`${m4}@${1.5}:${b4}:`,ws=`${lo}:PUB_KEY`;var _4=Object.defineProperty,I4=Object.defineProperties,S4=Object.getOwnPropertyDescriptors,lf=Object.getOwnPropertySymbols,$4=Object.prototype.hasOwnProperty,O4=Object.prototype.propertyIsEnumerable,cc=(t,e,r)=>e in t?_4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,oe=(t,e)=>{for(var r in e||(e={}))$4.call(e,r)&&cc(t,r,e[r]);if(lf)for(var r of lf(e))O4.call(e,r)&&cc(t,r,e[r]);return t},Re=(t,e)=>I4(t,S4(e)),k=(t,e,r)=>cc(t,typeof e!="symbol"?e+"":e,r);class D4 extends kS{constructor(e){super(e),k(this,"name",p4),k(this,"events",new dc),k(this,"initialized",!1),k(this,"requestQueue",{state:kt.idle,queue:[]}),k(this,"sessionRequestQueue",{state:kt.idle,queue:[]}),k(this,"emittedSessionRequests",new j3({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 r=>{var i;this.isInitialized(),await this.confirmOnlineStateOrThrow();const n=Re(oe({},r),{requiredNamespaces:r.requiredNamespaces||{},optionalNamespaces:r.optionalNamespaces||{}});await this.isValidConnect(n),n.optionalNamespaces=ZI(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=((i=h==null?void 0:h[0])==null?void 0:i.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 I=await this.client.core.crypto.generateKeyPair(),C=we(d),b=oe(Re(oe(oe({requiredNamespaces:o,optionalNamespaces:a,relays:u??[{protocol:Hg}],proposer:{publicKey:I,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:_,exp:O,nbf:m,type:y,statement:x,requestId:$,resources:E,signatureTypes:S}=A;return{domain:U,chains:j,nonce:B,type:y??"caip122",aud:_,version:"1",iat:new Date().toISOString(),exp:O,nbf:m,statement:x,requestId:$,resources:E,signatureTypes:S}}),walletPay:f}}),v=ae("session_connect",b.id),{reject:D,resolve:P,done:T}=Kr(d,cf),R=({id:A})=>{A===b.id&&(this.client.events.off("proposal_expire",R),this.pendingSessions.delete(b.id),this.events.emit(v,{error:{message:cf,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?D(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 r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{return await this.client.core.pairing.pair(r)}catch(i){throw this.client.logger.error("pair() failed"),i}}),k(this,"approve",async r=>{var i,n,s;const o=this.client.core.eventClient.createEvent({properties:{topic:(i=r==null?void 0:r.id)==null?void 0:i.toString(),trace:[Dt.session_approve_started]}});try{this.isInitialized(),await this.confirmOnlineStateOrThrow()}catch(U){throw o.setError(zr.no_internet_connection),U}try{await this.isValidProposalId(r==null?void 0:r.id)}catch(U){throw this.client.logger.error(`approve() -> proposal.get(${r==null?void 0:r.id}) failed`),o.setError(zr.proposal_not_found),U}try{await this.isValidApprove(r)}catch(U){throw this.client.logger.error("approve() -> isValidApprove() failed"),o.setError(zr.session_approve_namespace_validation_failure),U}const{id:a,relayProtocol:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=r,p=this.client.proposal.get(a);this.client.core.eventClient.deleteEvent({eventId:o.eventId});const{pairingTopic:g,proposer:w,requiredNamespaces:I,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:Dt.session_approve_started,properties:{topic:g,trace:[Dt.session_approve_started,Dt.session_namespaces_validation_success]}}));const v=await this.client.core.crypto.generateKeyPair(),D=w.publicKey,P=await this.client.core.crypto.generateSharedKey(v,D),T=Re(oe(oe(oe({relay:{protocol:c??"irn"},namespaces:l,controller:{publicKey:v,metadata:this.client.metadata},expiry:we(_i)},u&&{sessionProperties:u}),h&&{scopedProperties:h}),f&&{sessionConfig:f}),{proposalRequestsResponses:d}),R=he.relay;b.addTrace(Dt.subscribing_session_topic);try{await this.client.core.relayer.subscribe(P,{transportType:R,internal:{skipSubscribe:!0}})}catch(U){throw b.setError(zr.subscribe_session_topic_failure),U}b.addTrace(Dt.subscribe_session_topic_success);const A=Re(oe({},T),{topic:P,requiredNamespaces:I,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(Dt.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(Dt.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(_i)),{topic:P,acknowledged:()=>Promise.resolve(this.client.session.get(P))}}),k(this,"reject",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidReject(r)}catch(o){throw this.client.logger.error("reject() -> isValidReject() failed"),o}const{id:i,reason:n}=r;let s;try{s=this.client.proposal.get(i).pairingTopic}catch(o){throw this.client.logger.error(`reject() -> proposal.get(${i}) failed`),o}s&&await this.sendError({id:i,topic:s,error:n,rpcOpts:Te.wc_sessionPropose.reject}),await this.deleteProposal(i)}),k(this,"update",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidUpdate(r)}catch(h){throw this.client.logger.error("update() -> isValidUpdate() failed"),h}const{topic:i,namespaces:n}=r,{done:s,resolve:o,reject:a}=Kr(L.FIVE_MINUTES,"Session update request expired without receiving any acknowledgement"),c=Lt(),l=Rr().toString(),u=this.client.session.get(i).namespaces;return this.events.once(ae("session_update",c),({error:h})=>{h?a(h):o()}),await this.client.session.update(i,{namespaces:n}),await this.sendRequest({topic:i,method:"wc_sessionUpdate",params:{namespaces:n},throwOnFailedPublish:!0,clientRpcId:c,relayRpcId:l}).catch(h=>{this.client.logger.error(h),this.client.session.update(i,{namespaces:u}),a(h)}),{acknowledged:s}}),k(this,"extend",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidExtend(r)}catch(c){throw this.client.logger.error("extend() -> isValidExtend() failed"),c}const{topic:i}=r,n=Lt(),{done:s,resolve:o,reject:a}=Kr(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(i,we(_i)),this.sendRequest({topic:i,method:"wc_sessionExtend",params:{},clientRpcId:n,throwOnFailedPublish:!0}).catch(c=>{a(c)}),{acknowledged:s}}),k(this,"request",async r=>{this.isInitialized();try{await this.isValidRequest(r)}catch(w){throw this.client.logger.error("request() -> isValidRequest() failed"),w}const{chainId:i,request:n,topic:s,expiry:o=Te.wc_sessionRequest.req.ttl}=r,a=this.client.session.get(s);(a==null?void 0:a.transportType)===he.relay&&await this.confirmOnlineStateOrThrow();const c=Lt(),l=Rr().toString(),{done:u,resolve:h,reject:f}=Kr(o,"Request expired. Please try again.");this.events.once(ae("session_request",c),({error:w,result:I})=>{w?f(w):h(I)});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:i},expiry:o,throwOnFailedPublish:!0,appLink:p}).catch(w=>f(w)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),await u();const g={request:Re(oe({},n),{expiryTimestamp:we(o)}),chainId:i};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(I=>f(I)),this.client.events.emit("session_request_sent",{topic:s,request:n,chainId:i,id:c}),w()}),new Promise(async w=>{var I;if(!((I=a.sessionConfig)!=null&&I.disableDeepLink)){const C=await R3(this.client.core.storage,af);await C3({id:c,topic:s,wcDeepLink:C})}w()}),u()]).then(w=>w[2])}),k(this,"respond",async r=>{var i,n;this.isInitialized();const s=this.client.core.eventClient.createEvent({properties:{topic:(r==null?void 0:r.topic)||((n=(i=r==null?void 0:r.response)==null?void 0:i.id)==null?void 0:n.toString()),trace:[Dt.session_request_response_started]}});try{await this.isValidRespond(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_validation_failure),h}s.addTrace(Dt.session_request_response_validation_success);const{topic:o,response:a}=r,{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(Dt.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(r)}catch(h){throw s.addTrace(h==null?void 0:h.message),s.setError(zr.session_request_response_publish_failure),h}}),k(this,"ping",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow();try{await this.isValidPing(r)}catch(n){throw this.client.logger.error("ping() -> isValidPing() failed"),n}const{topic:i}=r;if(this.client.session.keys.includes(i)){const n=Lt(),s=Rr().toString(),{done:o,resolve:a,reject:c}=Kr(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:i,method:"wc_sessionPing",params:{},throwOnFailedPublish:!0,clientRpcId:n,relayRpcId:s}),o()])}else this.client.core.pairing.pairings.keys.includes(i)&&(this.client.logger.warn("ping() on pairing topic is deprecated and will be removed in the next major release."),await this.client.core.pairing.ping({topic:i}))}),k(this,"emit",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidEmit(r);const{topic:i,event:n,chainId:s}=r,o=Rr().toString(),a=Lt();await this.sendRequest({topic:i,method:"wc_sessionEvent",params:{event:n,chainId:s},throwOnFailedPublish:!0,relayRpcId:o,clientRpcId:a})}),k(this,"disconnect",async r=>{this.isInitialized(),await this.confirmOnlineStateOrThrow(),await this.isValidDisconnect(r);const{topic:i}=r;if(this.client.session.keys.includes(i))await this.sendRequest({topic:i,method:"wc_sessionDelete",params:fe("USER_DISCONNECTED"),throwOnFailedPublish:!0}),await this.deleteSession({topic:i,emitEvent:!1});else if(this.client.core.pairing.pairings.keys.includes(i))await this.client.core.pairing.disconnect({topic:i});else{const{message:n}=M("MISMATCHED_TOPIC",`Session or pairing topic not found: ${i}`);throw new Error(n)}}),k(this,"find",r=>(this.isInitialized(),this.client.session.getAll().filter(i=>QI(i,r)))),k(this,"getPendingSessionRequests",()=>this.client.pendingRequest.getAll()),k(this,"authenticate",async(r,i)=>{var n;this.isInitialized(),this.isValidAuthenticate(r);const s=i&&this.client.core.linkModeSupportedApps.includes(i)&&((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}=r,I=[...r.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(),D=ds(v);if(await Promise.all([this.client.auth.authKeys.set(ws,{responseTopic:D,publicKey:v}),this.client.auth.pairingTopics.set(D,{topic:D,pairingTopic:C})]),await this.client.core.relayer.subscribe(D,{transportType:o}),this.client.logger.info(`sending request to new pairing topic: ${C}`),g.length>0){const{namespace:E}=ur(a[0]);let S=Xx(E,"request",g);fs(I)&&(S=e_(S,I.pop())),I.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:I},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}=Kr(P,"Request expired"),_=Lt(),O=ae("session_connect",A.id),m=ae("session_request",_),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(_,{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(O,y),B(E.error.message))}await this.deleteProposal(A.id),this.events.off(O,y);const{cacaos:H,responder:z}=E.result,q=[],K=[];for(const W of H){await Mu({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=[Na(Q.iss)],Ie=Cs(Q.iss);if(pe){const He=qu(pe),Gt=zu(pe);q.push(...He),ve.push(...Gt)}for(const He of ve)K.push(`${He}:${Ie}`)}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(_i),requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:C,namespaces:gh([...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&&i&&(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(O,y),this.events.once(m,x);let $;try{if(s){const E=Ct("wc_sessionAuthenticate",T,_);this.client.core.history.set(C,E);const S=await this.client.core.crypto.encode("",E,{type:Nn,encoding:Br});$=rs(i,C,S)}else await Promise.all([this.sendRequest({topic:C,method:"wc_sessionAuthenticate",params:T,expiry:r.expiry,throwOnFailedPublish:!0,clientRpcId:_}),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(O,y),this.events.off(m,x),E}return await this.setProposal(A.id,A),await this.setAuthRequest(_,{request:Re(oe({},T),{verifyContext:{}}),pairingTopic:C,transportType:o}),{uri:$??b,response:U}}),k(this,"approveSessionAuthenticate",async r=>{const{id:i,auths:n}=r,s=this.client.core.eventClient.createEvent({properties:{topic:i.toString(),trace:[Vr.authenticated_session_approve_started]}});try{this.isInitialized()}catch(w){throw s.setError(tn.no_internet_connection),w}const o=this.getPendingAuthRequest(i);if(!o)throw s.setError(tn.authenticated_session_pending_request_not_found),new Error(`Could not find pending auth request with id ${i}`);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:hr,receiverPublicKey:c,senderPublicKey:l},f=[],d=[];for(const w of n){if(!await Mu({cacao:w,projectId:this.client.core.projectId})){s.setError(tn.invalid_cacao);const D=fe("SESSION_SETTLEMENT_FAILED","Signature verification failed");throw await this.sendError({id:i,topic:u,error:D,encodeOpts:h}),new Error(D.message)}s.addTrace(Vr.cacaos_verified);const{p:I}=w,C=fs(I.resources),b=[Na(I.iss)],v=Cs(I.iss);if(C){const D=qu(C),P=zu(C);f.push(...D),b.push(...P)}for(const D of b)d.push(`${D}:${v}`)}const p=await this.client.core.crypto.generateSharedKey(l,c);s.addTrace(Vr.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(_i),authentication:n,requiredNamespaces:{},optionalNamespaces:{},relay:{protocol:"irn"},pairingTopic:o.pairingTopic,namespaces:gh([...new Set(f)],[...new Set(d)]),transportType:a},s.addTrace(Vr.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(Vr.subscribe_authenticated_session_topic_success),await this.client.session.set(p,g),s.addTrace(Vr.store_authenticated_session),await this.client.core.pairing.updateMetadata({topic:o.pairingTopic,metadata:o.requester.metadata})}s.addTrace(Vr.publishing_authenticated_session_approve);try{await this.sendResult({topic:u,id:i,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(i,{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 r=>{this.isInitialized();const{id:i,reason:n}=r,s=this.getPendingAuthRequest(i);if(!s)throw new Error(`Could not find pending auth request with id ${i}`);s.transportType===he.relay&&await this.confirmOnlineStateOrThrow();const o=s.requester.publicKey,a=await this.client.core.crypto.generateKeyPair(),c=ds(o),l={type:hr,receiverPublicKey:o,senderPublicKey:a};await this.sendError({id:i,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(i,{message:"rejected",code:0}),await this.deleteProposal(i)}),k(this,"formatAuthMessage",r=>{this.isInitialized();const{request:i,iss:n}=r;return Yp(i,n)}),k(this,"processRelayMessageCache",()=>{setTimeout(async()=>{if(this.relayMessageCache.length!==0)for(;this.relayMessageCache.length>0;)try{const r=this.relayMessageCache.shift();r&&await this.onRelayMessage(r)}catch(r){this.client.logger.error(r)}},50)}),k(this,"cleanupDuplicatePairings",async r=>{if(r.pairingTopic)try{const i=this.client.core.pairing.pairings.get(r.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)===r.peer.metadata.url&&s.topic&&s.topic!==i.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(i){this.client.logger.error(i)}}),k(this,"deleteSession",async r=>{var i;const{topic:n,expirerHasDeleted:s=!1,emitEvent:o=!0,id:a=0}=r,{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(af).catch(l=>this.client.logger.warn(l)),n===((i=this.sessionRequestQueue.queue[0])==null?void 0:i.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(r,i)=>{if(i)try{const n=this.client.proposal.get(r),s=this.client.core.eventClient.getEvent({topic:n.pairingTopic});s==null||s.setError(zr.proposal_expired)}catch{}await Promise.all([this.client.proposal.delete(r,fe("USER_DISCONNECTED")),i?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"proposal")}),k(this,"deletePendingSessionRequest",async(r,i,n=!1)=>{await Promise.all([this.client.pendingRequest.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)]),this.addToRecentlyDeleted(r,"request"),this.sessionRequestQueue.queue=this.sessionRequestQueue.queue.filter(s=>s.id!==r),n&&(this.sessionRequestQueue.state=kt.idle,this.client.events.emit("session_request_expire",{id:r}))}),k(this,"deletePendingAuthRequest",async(r,i,n=!1)=>{await Promise.all([this.client.auth.requests.delete(r,i),n?Promise.resolve():this.client.core.expirer.del(r)])}),k(this,"setExpiry",async(r,i)=>{this.client.session.keys.includes(r)&&(this.client.core.expirer.set(r,i),await this.client.session.update(r,{expiry:i}))}),k(this,"setProposal",async(r,i)=>{this.client.core.expirer.set(r,we(Te.wc_sessionPropose.req.ttl)),await this.client.proposal.set(r,i)}),k(this,"setAuthRequest",async(r,i)=>{const{request:n,pairingTopic:s,transportType:o=he.relay}=i;this.client.core.expirer.set(r,n.expiryTimestamp),await this.client.auth.requests.set(r,{authPayload:n.authPayload,requester:n.requester,expiryTimestamp:n.expiryTimestamp,id:r,pairingTopic:s,verifyContext:n.verifyContext,transportType:o})}),k(this,"setPendingSessionRequest",async r=>{const{id:i,topic:n,params:s,verifyContext:o}=r,a=s.request.expiryTimestamp||we(Te.wc_sessionRequest.req.ttl);this.client.core.expirer.set(i,a),await this.client.pendingRequest.set(i,{id:i,topic:n,params:s,verifyContext:o})}),k(this,"sendRequest",async r=>{const{topic:i,method:n,params:s,expiry:o,relayRpcId:a,clientRpcId:c,throwOnFailedPublish:l,appLink:u,tvf:h,publishOpts:f={}}=r,d=Ct(n,s,c);let p;const g=!!u;try{const C=g?Br:tt;p=await this.client.core.crypto.encode(i,d,{encoding:C})}catch(C){throw await this.cleanup(),this.client.logger.error(`sendRequest() -> core.crypto.encode() for topic ${i} failed`),C}let w;if(w4.includes(n)){const C=bt(JSON.stringify(d)),b=bt(p);w=await this.client.core.verify.register({id:b,decryptedId:C})}const I=oe(oe({},Te[n].req),f);if(I.attestation=w,o&&(I.ttl=o),a&&(I.id=a),this.client.core.history.set(i,d),g){const C=rs(u,i,p);await Y.Linking.openURL(C,this.client.name)}else I.tvf=Re(oe({},h),{correlationId:d.id}),l?(I.internal=Re(oe({},I.internal),{throwOnFailedPublish:!0}),await this.client.core.relayer.publish(i,p,I)):this.client.core.relayer.publish(i,p,I).catch(C=>this.client.logger.error(C));return d.id}),k(this,"sendProposeSession",async r=>{const{proposal:i,publishOpts:n}=r,s=Ct("wc_sessionPropose",i,i.id);this.client.core.history.set(i.pairingTopic,s);const o=await this.client.core.crypto.encode(i.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:i.pairingTopic,sessionProposal:o},opts:Re(oe({},n),{publishMethod:"wc_proposeSession",attestation:l})})}),k(this,"sendApproveSession",async r=>{const{sessionTopic:i,pairingProposalResponse:n,proposal:s,sessionSettleRequest:o,publishOpts:a}=r,c=$n(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(i,u,{encoding:tt});this.client.core.history.set(i,u),await this.client.core.relayer.publishCustom({payload:{sessionTopic:i,pairingTopic:s.pairingTopic,sessionProposalResponse:l,sessionSettlementRequest:h},opts:Re(oe({},a),{publishMethod:"wc_approveSession"})})}),k(this,"sendResult",async r=>{const{id:i,topic:n,result:s,throwOnFailedPublish:o,encodeOpts:a,appLink:c}=r,l=$n(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const p=h?Br: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,i);const p=f.request;try{d=this.getTVFParams(i,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}, ${i}) failed`),p}if(h){const p=rs(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:i}),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 r=>{const{id:i,topic:n,error:s,encodeOpts:o,rpcOpts:a,appLink:c}=r,l=oo(i,s);let u;const h=c&&typeof(Y==null?void 0:Y.Linking)<"u";try{const d=h?Br: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,i)}catch(d){throw this.client.logger.error(`sendError() -> history.get(${n}, ${i}) failed`),d}if(h){const d=rs(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 r=[],i=[];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&&r.push(n.topic)}),this.client.proposal.getAll().forEach(n=>{qt(n.expiryTimestamp)&&i.push(n.id)}),await Promise.all([...r.map(n=>this.deleteSession({topic:n})),...i.map(n=>this.deleteProposal(n))])}),k(this,"onProviderMessageEvent",async r=>{!this.initialized||this.relayMessageCache.length>0?this.relayMessageCache.push(r):await this.onRelayMessage(r)}),k(this,"onRelayEventRequest",async r=>{this.requestQueue.queue.push(r),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 r=this.requestQueue.queue.shift();if(r)try{await this.processRequest(r)}catch(i){this.client.logger.warn(i)}}this.requestQueue.state=kt.idle}),k(this,"processRequest",async r=>{const{topic:i,payload:n,attestation:s,transportType:o,encryptedId:a}=r,c=n.method;if(!this.shouldIgnorePairingRequest({topic:i,requestMethod:c}))switch(c){case"wc_sessionPropose":return await this.onSessionProposeRequest({topic:i,payload:n,attestation:s,encryptedId:a});case"wc_sessionSettle":return await this.onSessionSettleRequest(i,n);case"wc_sessionUpdate":return await this.onSessionUpdateRequest(i,n);case"wc_sessionExtend":return await this.onSessionExtendRequest(i,n);case"wc_sessionPing":return await this.onSessionPingRequest(i,n);case"wc_sessionDelete":return await this.onSessionDeleteRequest(i,n);case"wc_sessionRequest":return await this.onSessionRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});case"wc_sessionEvent":return await this.onSessionEventRequest(i,n);case"wc_sessionAuthenticate":return await this.onSessionAuthenticateRequest({topic:i,payload:n,attestation:s,encryptedId:a,transportType:o});default:return this.client.logger.info(`Unsupported request method ${c}`)}}),k(this,"onRelayEventResponse",async r=>{const{topic:i,payload:n,transportType:s}=r,o=(await this.client.core.history.get(i,n.id)).request.method;switch(o){case"wc_sessionPropose":return this.onSessionProposeResponse(i,n,s);case"wc_sessionSettle":return this.onSessionSettleResponse(i,n);case"wc_sessionUpdate":return this.onSessionUpdateResponse(i,n);case"wc_sessionExtend":return this.onSessionExtendResponse(i,n);case"wc_sessionPing":return this.onSessionPingResponse(i,n);case"wc_sessionRequest":return this.onSessionRequestResponse(i,n);case"wc_sessionAuthenticate":return this.onSessionAuthenticateResponse(i,n);default:return this.client.logger.info(`Unsupported response method ${o}`)}}),k(this,"onRelayEventUnknownPayload",r=>{const{topic:i}=r,{message:n}=M("MISSING_OR_INVALID",`Decoded payload on topic ${i} is not identifiable as a JSON-RPC request or a response.`);throw new Error(n)}),k(this,"shouldIgnorePairingRequest",r=>{const{topic:i,requestMethod:n}=r,s=this.expectedPairingMethodMap.get(i);return!s||s.includes(n)?!1:!!(s.includes("wc_sessionAuthenticate")&&this.client.events.listenerCount("session_authenticate")>0)}),k(this,"onSessionProposeRequest",async r=>{const{topic:i,payload:n,attestation:s,encryptedId:o}=r,{params:a,id:c}=n;try{const l=this.client.core.eventClient.getEvent({topic:i});this.client.events.listenerCount("session_proposal")===0&&(console.warn("No listener for session_proposal event"),l==null||l.setError(ir.proposal_listener_not_found)),this.isValidConnect(oe({},n.params));const u=a.expiryTimestamp||we(Te.wc_sessionPropose.req.ttl),h=oe({id:c,pairingTopic:i,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:i,error:l,rpcOpts:Te.wc_sessionPropose.autoReject}),this.client.logger.error(l)}}),k(this,"onSessionProposeResponse",async(r,i,n)=>{const{id:s}=i;if(Mt(i)){const{result:o}=i;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:r,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:r})}else if(vt(i)){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:i.error})}}),k(this,"onSessionSettleRequest",async(r,i)=>{const{id:n,params:s}=i;try{this.isValidSessionSettleRequest(s);const{relay:o,controller:a,expiry:c,namespaces:l,sessionProperties:u,scopedProperties:h,sessionConfig:f,proposalRequestsResponses:d}=i.params,p=[...this.pendingSessions.values()].find(I=>I.sessionTopic===r);if(!p)return this.client.logger.error(`Pending session not found for topic ${r}`);const g=this.client.proposal.get(p.proposalId),w=Re(oe(oe(oe({topic:r,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:i.id,topic:r,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:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionSettleResponse",async(r,i)=>{const{id:n}=i;Mt(i)?(await this.client.session.update(r,{acknowledged:!0}),this.events.emit(ae("session_approve",n),{})):vt(i)&&(await this.client.session.delete(r,fe("USER_DISCONNECTED")),this.events.emit(ae("session_approve",n),{error:i.error}))}),k(this,"onSessionUpdateRequest",async(r,i)=>{const{params:n,id:s}=i;try{const o=`${r}_session_update`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,s)){this.client.logger.warn(`Discarding out of sync request - ${s}`),this.sendError({id:s,topic:r,error:fe("INVALID_UPDATE_REQUEST")});return}this.isValidUpdate(oe({topic:r},n));try{Qi.set(o,s),await this.client.session.update(r,{namespaces:n.namespaces}),await this.sendResult({id:s,topic:r,result:!0})}catch(c){throw Qi.delete(o),c}this.client.events.emit("session_update",{id:s,topic:r,params:n})}catch(o){await this.sendError({id:s,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"isRequestOutOfSync",(r,i)=>i.toString().slice(0,-3)<r.toString().slice(0,-3)),k(this,"onSessionUpdateResponse",(r,i)=>{const{id:n}=i,s=ae("session_update",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_update",n),{}):vt(i)&&this.events.emit(ae("session_update",n),{error:i.error})}),k(this,"onSessionExtendRequest",async(r,i)=>{const{id:n}=i;try{this.isValidExtend({topic:r}),await this.setExpiry(r,we(_i)),await this.sendResult({id:n,topic:r,result:!0}),this.client.events.emit("session_extend",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionExtendResponse",(r,i)=>{const{id:n}=i,s=ae("session_extend",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_extend",n),{}):vt(i)&&this.events.emit(ae("session_extend",n),{error:i.error})}),k(this,"onSessionPingRequest",async(r,i)=>{const{id:n}=i;try{this.isValidPing({topic:r}),await this.sendResult({id:n,topic:r,result:!0,throwOnFailedPublish:!0}),this.client.events.emit("session_ping",{id:n,topic:r})}catch(s){await this.sendError({id:n,topic:r,error:s}),this.client.logger.error(s)}}),k(this,"onSessionPingResponse",(r,i)=>{const{id:n}=i,s=ae("session_ping",n);setTimeout(()=>{if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners 2176`);Mt(i)?this.events.emit(ae("session_ping",n),{}):vt(i)&&this.events.emit(ae("session_ping",n),{error:i.error})},500)}),k(this,"onSessionDeleteRequest",async(r,i)=>{const{id:n}=i;try{await this.isValidDisconnect({topic:r,reason:i.params}),this.cleanupPendingSentRequestsForTopic({topic:r,error:fe("USER_DISCONNECTED")}),await this.deleteSession({topic:r,id:n})}catch(s){this.client.logger.error(s)}}),k(this,"onSessionRequest",async r=>{var i,n,s;const{topic:o,payload:a,attestation:c,encryptedId:l,transportType:u}=r,{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&&(i=d.peer.metadata.redirect)!=null&&i.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",(r,i)=>{const{id:n}=i,s=ae("session_request",n);if(this.events.listenerCount(s)===0)throw new Error(`emitting ${s} without any listeners`);Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionEventRequest",async(r,i)=>{const{id:n,params:s}=i;try{const o=`${r}_session_event_${s.event.name}`,a=Qi.get(o);if(a&&this.isRequestOutOfSync(a,n)){this.client.logger.info(`Discarding out of sync request - ${n}`);return}this.isValidEmit(oe({topic:r},s)),this.client.events.emit("session_event",{id:n,topic:r,params:s}),Qi.set(o,n)}catch(o){await this.sendError({id:n,topic:r,error:o}),this.client.logger.error(o)}}),k(this,"onSessionAuthenticateResponse",(r,i)=>{const{id:n}=i;this.client.logger.trace({type:"method",method:"onSessionAuthenticateResponse",topic:r,payload:i}),Mt(i)?this.events.emit(ae("session_request",n),{result:i.result}):vt(i)&&this.events.emit(ae("session_request",n),{error:i.error})}),k(this,"onSessionAuthenticateRequest",async r=>{var i;const{topic:n,payload:s,attestation:o,encryptedId:a,transportType:c}=r;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&&(i=l.metadata.redirect)!=null&&i.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:hr,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",r=>{this.sessionRequestQueue.queue.push(r)}),k(this,"cleanupAfterResponse",r=>{this.deletePendingSessionRequest(r.response.id,{message:"fulfilled",code:0}),setTimeout(()=>{this.sessionRequestQueue.state=kt.idle,this.processSessionRequestQueue()},L.toMiliseconds(this.requestQueueDelay))}),k(this,"cleanupPendingSentRequestsForTopic",({topic:r,error:i})=>{const n=this.client.core.history.pending;n.length>0&&n.filter(s=>s.topic===r&&s.request.method==="wc_sessionRequest").forEach(s=>{this.events.emit(ae("session_request",s.request.id),{error:i})})}),k(this,"processSessionRequestQueue",()=>{if(this.sessionRequestQueue.state===kt.active){this.client.logger.info("session request queue is already active.");return}const r=this.sessionRequestQueue.queue[0];if(!r){this.client.logger.info("session request queue is empty.");return}try{this.emitSessionRequest(r)}catch(i){this.client.logger.error(i)}}),k(this,"emitSessionRequest",r=>{if(this.emittedSessionRequests.has(r.id)){this.client.logger.warn({id:r.id},`Skipping emitting \`session_request\` event for duplicate request. id: ${r.id}`);return}this.sessionRequestQueue.state=kt.active,this.emittedSessionRequests.add(r.id),this.client.events.emit("session_request",r)}),k(this,"onPairingCreated",r=>{if(r.methods&&this.expectedPairingMethodMap.set(r.topic,r.methods),r.active)return;const i=this.client.proposal.getAll().find(n=>n.pairingTopic===r.topic);i&&this.onSessionProposeRequest({topic:r.topic,payload:Ct("wc_sessionPropose",Re(oe({},i),{requiredNamespaces:i.requiredNamespaces,optionalNamespaces:i.optionalNamespaces,relays:i.relays,proposer:i.proposer,sessionProperties:i.sessionProperties,scopedProperties:i.scopedProperties}),i.id),attestation:i.attestation,encryptedId:i.encryptedId})}),k(this,"isValidConnect",async r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`connect() params: ${JSON.stringify(r)}`);throw new Error(l)}const{pairingTopic:i,requiredNamespaces:n,optionalNamespaces:s,sessionProperties:o,scopedProperties:a,relays:c}=r;if(_e(i)||await this.isValidPairingTopic(i),!h8(c,!0)){const{message:l}=M("MISSING_OR_INVALID",`connect() relays: ${c}`);throw new Error(l)}if(n&&!_e(n)&&Kt(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&&!_e(s)&&Kt(s)!==0&&this.validateNamespaces(s,"optionalNamespaces"),o&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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",(r,i)=>{const n=u8(r,"connect()",i);if(n)throw new Error(n.message)}),k(this,"isValidApprove",async r=>{if(!Xe(r))throw new Error(M("MISSING_OR_INVALID",`approve() params: ${r}`).message);const{id:i,namespaces:n,relayProtocol:s,sessionProperties:o,scopedProperties:a}=r;this.checkRecentlyDeleted(i),await this.isValidProposalId(i);const c=this.client.proposal.get(i),l=Jo(n,"approve()");if(l)throw new Error(l.message);const u=mh(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&&!_e(o)&&this.validateSessionProps(o,"sessionProperties"),a&&!_e(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 r=>{if(!Xe(r)){const{message:s}=M("MISSING_OR_INVALID",`reject() params: ${r}`);throw new Error(s)}const{id:i,reason:n}=r;if(this.checkRecentlyDeleted(i),await this.isValidProposalId(i),!d8(n)){const{message:s}=M("MISSING_OR_INVALID",`reject() reason: ${JSON.stringify(n)}`);throw new Error(s)}}),k(this,"isValidSessionSettleRequest",r=>{if(!Xe(r)){const{message:l}=M("MISSING_OR_INVALID",`onSessionSettleRequest() params: ${r}`);throw new Error(l)}const{relay:i,controller:n,namespaces:s,expiry:o}=r;if(!Tg(i)){const{message:l}=M("MISSING_OR_INVALID","onSessionSettleRequest() relay protocol should be a string");throw new Error(l)}const a=n8(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 r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`update() params: ${r}`);throw new Error(c)}const{topic:i,namespaces:n}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const s=this.client.session.get(i),o=Jo(n,"update()");if(o)throw new Error(o.message);const a=mh(s.requiredNamespaces,n,"update()");if(a)throw new Error(a.message)}),k(this,"isValidExtend",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`extend() params: ${r}`);throw new Error(n)}const{topic:i}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i)}),k(this,"isValidRequest",async r=>{if(!Xe(r)){const{message:c}=M("MISSING_OR_INVALID",`request() params: ${r}`);throw new Error(c)}const{topic:i,request:n,chainId:s,expiry:o}=r;this.checkRecentlyDeleted(i),await this.isValidSessionTopic(i);const{namespaces:a}=this.client.session.get(i);if(!wh(a,s)){const{message:c}=M("MISSING_OR_INVALID",`request() chainId: ${s}`);throw new Error(c)}if(!p8(n)){const{message:c}=M("MISSING_OR_INVALID",`request() ${JSON.stringify(n)}`);throw new Error(c)}if(!w8(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 r=>{var i;if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`respond() params: ${r}`);throw new Error(a)}const{topic:n,response:s}=r;try{await this.isValidSessionTopic(n)}catch(a){throw(i=r==null?void 0:r.response)!=null&&i.id&&this.cleanupAfterResponse(r),a}if(!g8(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 r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`ping() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidEmit",async r=>{if(!Xe(r)){const{message:a}=M("MISSING_OR_INVALID",`emit() params: ${r}`);throw new Error(a)}const{topic:i,event:n,chainId:s}=r;await this.isValidSessionTopic(i);const{namespaces:o}=this.client.session.get(i);if(!wh(o,s)){const{message:a}=M("MISSING_OR_INVALID",`emit() chainId: ${s}`);throw new Error(a)}if(!y8(n)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}if(!m8(o,s,n.name)){const{message:a}=M("MISSING_OR_INVALID",`emit() event: ${JSON.stringify(n)}`);throw new Error(a)}}),k(this,"isValidDisconnect",async r=>{if(!Xe(r)){const{message:n}=M("MISSING_OR_INVALID",`disconnect() params: ${r}`);throw new Error(n)}const{topic:i}=r;await this.isValidSessionOrPairingTopic(i)}),k(this,"isValidAuthenticate",r=>{const{chains:i,uri:n,domain:s,nonce:o}=r;if(!Array.isArray(i)||i.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(i.map(c=>ur(c).namespace))].length>1)throw new Error("Multi-namespace requests are not supported. Please request single namespace only.");const{namespace:a}=ur(i[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 r=>{const{attestationId:i,hash:n,encryptedId:s,metadata:o,transportType:a}=r,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:i,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",(r,i)=>{Object.values(r).forEach((n,s)=>{if(n==null){const{message:o}=M("MISSING_OR_INVALID",`${i} must contain an existing value for each key. Received: ${n} for key ${Object.keys(r)[s]}`);throw new Error(o)}})}),k(this,"getPendingAuthRequest",r=>{const i=this.client.auth.requests.get(r);return typeof i=="object"?i:void 0}),k(this,"addToRecentlyDeleted",(r,i)=>{if(this.recentlyDeletedMap.set(r,i),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",r=>{const i=this.recentlyDeletedMap.get(r);if(i){const{message:n}=M("MISSING_OR_INVALID",`Record was recently deleted - ${i}: ${r}`);throw new Error(n)}}),k(this,"isLinkModeEnabled",(r,i)=>{var n,s,o,a,c,l,u,h,f;return!r||i!==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=r==null?void 0:r.redirect)==null?void 0:u.universal)!==void 0&&((h=r==null?void 0:r.redirect)==null?void 0:h.universal)!==""&&((f=r==null?void 0:r.redirect)==null?void 0:f.linkMode)===!0&&this.client.core.linkModeSupportedApps.includes(r.redirect.universal)&&typeof(Y==null?void 0:Y.Linking)<"u"}),k(this,"getAppLinkIfEnabled",(r,i)=>{var n;return this.isLinkModeEnabled(r,i)?(n=r==null?void 0:r.redirect)==null?void 0:n.universal:void 0}),k(this,"handleLinkModeMessage",({url:r})=>{if(!r||!r.includes("wc_ev")||!r.includes("topic"))return;const i=Au(r,"topic")||"",n=decodeURIComponent(Au(r,"wc_ev")||""),s=this.client.session.keys.includes(i);s&&this.client.session.update(i,{transportType:he.link_mode}),this.client.core.dispatchEnvelope({topic:i,message:n,sessionExists:s})}),k(this,"registerLinkModeListeners",async()=>{var r;if(jc()||kr()&&(r=this.client.metadata.redirect)!=null&&r.linkMode){const i=Y==null?void 0:Y.Linking;if(typeof i<"u"){i.addEventListener("url",this.handleLinkModeMessage,this.client.name);const n=await i.getInitialURL();n&&setTimeout(()=>{this.handleLinkModeMessage({url:n})},50)}}}),k(this,"getTVFApproveParams",r=>{try{const i=Cg(r.namespaces),n=HI(r.namespaces),s=KI(r.namespaces),o=r.sessionProperties,a=r.scopedProperties;return{approvedChains:i,approvedMethods:n,approvedEvents:s,sessionProperties:o,scopedProperties:a}}catch(i){return this.client.logger.warn(i,"Error getting TVF approve params"),{}}}),k(this,"getTVFParams",(r,i,n)=>{var s,o,a;if(!((s=i.request)!=null&&s.method))return{};const c={correlationId:r,rpcMethods:[i.request.method],chainId:i.chainId};try{const l=this.extractTxHashesFromResult(i.request,n);c.txHashes=l,c.contractAddresses=this.isValidContractData(i.request.params)?[(a=(o=i.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",r=>{var i;if(!r)return!1;try{const n=(r==null?void 0:r.data)||((i=r==null?void 0:r[0])==null?void 0:i.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",(r,i)=>{var n;try{if(!i)return[];const s=r.method,o=g4[s];if(s==="sui_signTransaction")return[Tx(i.transactionBytes)];if(s==="near_signTransaction")return[Uu(i)];if(s==="near_signTransactions")return i.map(c=>Uu(c));if(s==="xrpl_signTransactionFor"||s==="xrpl_signTransaction")return[(n=i.tx_json)==null?void 0:n.hash];if(s==="polkadot_signTransaction")return[N8({transaction:r.params.transactionPayload,signature:i.signature})];if(s==="algo_signTxn")return _t(i)?i.map(c=>ku(c)):[ku(i)];if(s==="cosmos_signDirect")return[Fx(i)];if(s==="wallet_sendCalls")return Nx(i);if(typeof i=="string")return[i];const a=i[o.key];if(_t(a))return s==="solana_signAllTransactions"?a.map(c=>Bx(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,r=this.client.core.relayer.messages.getWithoutAck(e);for(const[i,n]of Object.entries(r))for(const s of n)try{await this.onProviderMessageEvent({topic:i,message:s,publishedAt:Date.now()})}catch{this.client.logger.warn(`Error processing pending message event for topic: ${i}, 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:r,message:i,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(r,i,{receiverPublicKey:o,encoding:s===he.link_mode?Br:tt});Xc(a)?(this.client.core.history.set(r,a),await this.onRelayEventRequest({topic:r,payload:a,attestation:n,transportType:s,encryptedId:bt(i)})):ao(a)?(await this.client.core.history.resolve(a),await this.onRelayEventResponse({topic:r,payload:a,transportType:s}),this.client.core.history.delete(r,a.id)):(this.client.logger.error(`onRelayMessage() -> unknown payload: ${JSON.stringify(a)}`),await this.onRelayEventUnknownPayload({topic:r,payload:a,transportType:s})),await this.client.core.relayer.messages.ack(r,i)}catch(a){this.client.logger.error(`onRelayMessage() -> failed to process an inbound message: ${i}`),this.client.logger.error(a)}}registerExpirerEvents(){this.client.core.expirer.on(wt.expired,async e=>{const{topic:r,id:i}=Bp(e.target);if(i&&this.client.pendingRequest.keys.includes(i))return await this.deletePendingSessionRequest(i,M("EXPIRED"),!0);if(i&&this.client.auth.requests.keys.includes(i))return await this.deletePendingAuthRequest(i,M("EXPIRED"),!0);r?this.client.session.keys.includes(r)&&(await this.deleteSession({topic:r,expirerHasDeleted:!0}),this.client.events.emit("session_expire",{topic:r})):i&&(await this.deleteProposal(i,!0),this.client.events.emit("proposal_expire",{id:i}))})}registerPairingEvents(){this.client.core.pairing.events.on(Yr.create,e=>this.onPairingCreated(e)),this.client.core.pairing.events.on(Yr.delete,e=>{this.addToRecentlyDeleted(e.topic,"pairing")})}isValidPairingTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`pairing topic should be a string: ${e}`);throw new Error(r)}if(!this.client.core.pairing.pairings.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`pairing topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.core.pairing.pairings.get(e).expiry)){const{message:r}=M("EXPIRED",`pairing topic: ${e}`);throw new Error(r)}}async isValidSessionTopic(e){if(!be(e,!1)){const{message:r}=M("MISSING_OR_INVALID",`session topic should be a string: ${e}`);throw new Error(r)}if(this.checkRecentlyDeleted(e),!this.client.session.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`session topic doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.session.get(e).expiry)){await this.deleteSession({topic:e});const{message:r}=M("EXPIRED",`session topic: ${e}`);throw new Error(r)}if(!this.client.core.crypto.keychain.has(e)){const{message:r}=M("MISSING_OR_INVALID",`session topic does not exist in keychain: ${e}`);throw await this.deleteSession({topic:e}),new Error(r)}}async isValidSessionOrPairingTopic(e){if(this.checkRecentlyDeleted(e),this.client.session.keys.includes(e))await this.isValidSessionTopic(e);else if(this.client.core.pairing.pairings.keys.includes(e))this.isValidPairingTopic(e);else if(be(e,!1)){const{message:r}=M("NO_MATCHING_KEY",`session or pairing topic doesn't exist: ${e}`);throw new Error(r)}else{const{message:r}=M("MISSING_OR_INVALID",`session or pairing topic should be a string: ${e}`);throw new Error(r)}}async isValidProposalId(e){if(!f8(e)){const{message:r}=M("MISSING_OR_INVALID",`proposal id should be a number: ${e}`);throw new Error(r)}if(!this.client.proposal.keys.includes(e)){const{message:r}=M("NO_MATCHING_KEY",`proposal id doesn't exist: ${e}`);throw new Error(r)}if(qt(this.client.proposal.get(e).expiryTimestamp)){await this.deleteProposal(e);const{message:r}=M("EXPIRED",`proposal id: ${e}`);throw new Error(r)}}validateRequestExpiry(e){if(e&&!E8(e,oa)){const{message:r}=M("MISSING_OR_INVALID",`request() expiry: ${e}. Expiry must be a number (in seconds) between ${oa.min} and ${oa.max}`);throw new Error(r)}}}class A4 extends pi{constructor(e,r){super(e,r,f4,el),this.core=e,this.logger=r}}let P4=class extends pi{constructor(e,r){super(e,r,d4,el),this.core=e,this.logger=r}};class C4 extends pi{constructor(e,r){super(e,r,y4,el,i=>i.id),this.core=e,this.logger=r}}class B4 extends pi{constructor(e,r){super(e,r,v4,lo,()=>ws),this.core=e,this.logger=r}}class T4 extends pi{constructor(e,r){super(e,r,E4,lo),this.core=e,this.logger=r}}class R4 extends pi{constructor(e,r){super(e,r,x4,lo,i=>i.id),this.core=e,this.logger=r}}var F4=Object.defineProperty,N4=(t,e,r)=>e in t?F4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,aa=(t,e,r)=>N4(t,typeof e!="symbol"?e+"":e,r);class U4{constructor(e,r){this.core=e,this.logger=r,aa(this,"authKeys"),aa(this,"pairingTopics"),aa(this,"requests"),this.authKeys=new B4(this.core,this.logger),this.pairingTopics=new T4(this.core,this.logger),this.requests=new R4(this.core,this.logger)}async init(){await this.authKeys.init(),await this.pairingTopics.init(),await this.requests.init()}}var k4=Object.defineProperty,j4=(t,e,r)=>e in t?k4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,te=(t,e,r)=>j4(t,typeof e!="symbol"?e+"":e,r);class tl extends US{constructor(e){super(e),te(this,"protocol",o0),te(this,"version",a0),te(this,"name",sa.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",(i,n)=>this.events.on(i,n)),te(this,"once",(i,n)=>this.events.once(i,n)),te(this,"off",(i,n)=>this.events.off(i,n)),te(this,"removeListener",(i,n)=>this.events.removeListener(i,n)),te(this,"removeAllListeners",i=>this.events.removeAllListeners(i)),te(this,"connect",async i=>{try{return await this.engine.connect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"pair",async i=>{try{return await this.engine.pair(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approve",async i=>{try{return await this.engine.approve(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"reject",async i=>{try{return await this.engine.reject(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"update",async i=>{try{return await this.engine.update(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"extend",async i=>{try{return await this.engine.extend(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"request",async i=>{try{return await this.engine.request(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"respond",async i=>{try{return await this.engine.respond(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"ping",async i=>{try{return await this.engine.ping(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"emit",async i=>{try{return await this.engine.emit(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"disconnect",async i=>{try{return await this.engine.disconnect(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"find",i=>{try{return this.engine.find(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"getPendingSessionRequests",()=>{try{return this.engine.getPendingSessionRequests()}catch(i){throw this.logger.error(i.message),i}}),te(this,"authenticate",async(i,n)=>{try{return await this.engine.authenticate(i,n)}catch(s){throw this.logger.error(s.message),s}}),te(this,"formatAuthMessage",i=>{try{return this.engine.formatAuthMessage(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"approveSessionAuthenticate",async i=>{try{return await this.engine.approveSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),te(this,"rejectSessionAuthenticate",async i=>{try{return await this.engine.rejectSessionAuthenticate(i)}catch(n){throw this.logger.error(n.message),n}}),this.name=(e==null?void 0:e.name)||sa.name,this.metadata=S3(e==null?void 0:e.metadata),this.signConfig=e==null?void 0:e.signConfig;const r=Zc({logger:(e==null?void 0:e.logger)||sa.logger,name:this.name});this.logger=r,this.core=(e==null?void 0:e.core)||new h4(e),this.session=new P4(this.core,this.logger),this.proposal=new A4(this.core,this.logger),this.pendingRequest=new C4(this.core,this.logger),this.engine=new D4(this),this.auth=new U4(this.core,this.logger)}static async init(e){const r=new tl(e);return await r.initialize(),r}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 L4=tl;var M4=Object.defineProperty,q4=Object.defineProperties,z4=Object.getOwnPropertyDescriptors,uf=Object.getOwnPropertySymbols,V4=Object.prototype.hasOwnProperty,H4=Object.prototype.propertyIsEnumerable,hf=(t,e,r)=>e in t?M4(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ff=(t,e)=>{for(var r in e||(e={}))V4.call(e,r)&&hf(t,r,e[r]);if(uf)for(var r of uf(e))H4.call(e,r)&&hf(t,r,e[r]);return t},df=(t,e)=>q4(t,z4(e));const K4={Accept:"application/json","Content-Type":"application/json"},W4="POST",pf={headers:K4,method:W4},gf=10;let l0=class{constructor(e,r=!1){if(this.url=e,this.disableProviderPing=r,this.events=new St.EventEmitter,this.isAvailable=!1,this.registering=!1,!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);this.url=e,this.disableProviderPing=r}get connected(){return this.isAvailable}get connecting(){return this.registering}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}off(e,r){this.events.off(e,r)}removeListener(e,r){this.events.removeListener(e,r)}async open(e=this.url){await this.register(e)}async close(){if(!this.isAvailable)throw new Error("Connection already closed");this.onClose()}async send(e){this.isAvailable||await this.register();try{const r=oi(e),i=await(await dl(this.url,df(ff({},pf),{body:r}))).json();this.onPayload({data:i})}catch(r){this.onError(e.id,r)}}async register(e=this.url){if(!Ch(e))throw new Error(`Provided URL is not compatible with HTTP connection: ${e}`);if(this.registering){const r=this.events.getMaxListeners();return(this.events.listenerCount("register_error")>=r||this.events.listenerCount("open")>=r)&&this.events.setMaxListeners(r+1),new Promise((i,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"));i()})})}this.url=e,this.registering=!0;try{if(!this.disableProviderPing){const r=oi({id:1,jsonrpc:"2.0",method:"test",params:[]});await dl(e,df(ff({},pf),{body:r}))}this.onOpen()}catch(r){const i=this.parseError(r);throw this.events.emit("register_error",i),this.onClose(),i}}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 r=typeof e.data=="string"?si(e.data):e.data;this.events.emit("payload",r)}onError(e,r){const i=this.parseError(r),n=i.message||i.toString(),s=oo(e,n);this.events.emit("payload",s)}parseError(e,r=this.url){return kg(e,r,"HTTP")}resetMaxListeners(){this.events.getMaxListeners()>gf&&this.events.setMaxListeners(gf)}};function rl(t){return t==null||typeof t!="object"&&typeof t!="function"}function u0(t){return Object.getOwnPropertySymbols(t).filter(e=>Object.prototype.propertyIsEnumerable.call(t,e))}function h0(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const G4="[object RegExp]",f0="[object String]",d0="[object Number]",p0="[object Boolean]",g0="[object Arguments]",Y4="[object Symbol]",Z4="[object Date]",J4="[object Map]",X4="[object Set]",Q4="[object Array]",eA="[object ArrayBuffer]",tA="[object Object]",rA="[object DataView]",iA="[object Uint8Array]",nA="[object Uint8ClampedArray]",sA="[object Uint16Array]",oA="[object Uint32Array]",aA="[object Int8Array]",cA="[object Int16Array]",lA="[object Int32Array]",uA="[object Float32Array]",hA="[object Float64Array]";function il(t){return ArrayBuffer.isView(t)&&!(t instanceof DataView)}function fA(t,e){return Di(t,void 0,t,new Map,e)}function Di(t,e,r,i=new Map,n=void 0){const s=n==null?void 0:n(t,e,r,i);if(s!=null)return s;if(rl(t))return t;if(i.has(t))return i.get(t);if(Array.isArray(t)){const o=new Array(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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;i.set(t,o);for(const[a,c]of t)o.set(a,Di(c,a,r,i,n));return o}if(t instanceof Set){const o=new Set;i.set(t,o);for(const a of t)o.add(Di(a,void 0,r,i,n));return o}if(typeof re<"u"&&re.isBuffer(t))return t.subarray();if(il(t)){const o=new(Object.getPrototypeOf(t)).constructor(t.length);i.set(t,o);for(let a=0;a<t.length;a++)o[a]=Di(t[a],a,r,i,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 i.set(t,o),Zr(o,t,r,i,n),o}if(typeof File<"u"&&t instanceof File){const o=new File([t],t.name,{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Blob){const o=new Blob([t],{type:t.type});return i.set(t,o),Zr(o,t,r,i,n),o}if(t instanceof Error){const o=new t.constructor;return i.set(t,o),o.message=t.message,o.name=t.name,o.stack=t.stack,o.cause=t.cause,Zr(o,t,r,i,n),o}if(typeof t=="object"&&dA(t)){const o=Object.create(Object.getPrototypeOf(t));return i.set(t,o),Zr(o,t,r,i,n),o}return t}function Zr(t,e,r=t,i,n){const s=[...Object.keys(e),...u0(e)];for(let o=0;o<s.length;o++){const a=s[o],c=Object.getOwnPropertyDescriptor(t,a);(c==null||c.writable)&&(t[a]=Di(e[a],a,r,i,n))}}function dA(t){switch(h0(t)){case g0:case Q4:case eA:case rA:case p0:case Z4:case uA:case hA:case aA:case cA:case lA:case J4:case d0:case tA:case G4:case X4:case f0:case Y4:case iA:case nA:case sA:case oA:return!0;default:return!1}}function pA(t,e){return fA(t,(r,i,n,s)=>{const o=e==null?void 0:e(r,i,n,s);if(o!=null)return o;if(typeof t=="object")switch(Object.prototype.toString.call(t)){case d0:case f0:case p0:{const a=new t.constructor(t==null?void 0:t.valueOf());return Zr(a,t),a}case g0:{const a={};return Zr(a,t),a.length=t.length,a[Symbol.iterator]=t[Symbol.iterator],a}default:return}})}function yf(t){return pA(t)}function wf(t){return t!==null&&typeof t=="object"&&h0(t)==="[object Arguments]"}function mf(t){return typeof t=="object"&&t!==null}function gA(){}function yA(t){return il(t)}function wA(t){var r;if(typeof t!="object"||t==null)return!1;if(Object.getPrototypeOf(t)===null)return!0;if(Object.prototype.toString.call(t)!=="[object Object]"){const i=t[Symbol.toStringTag];return i==null||!((r=Object.getOwnPropertyDescriptor(t,Symbol.toStringTag))!=null&&r.writable)?!1:t.toString()===`[object ${i}]`}let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}function mA(t){if(rl(t))return t;if(Array.isArray(t)||il(t)||t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer)return t.slice(0);const e=Object.getPrototypeOf(t),r=e.constructor;if(t instanceof Date||t instanceof Map||t instanceof Set)return new r(t);if(t instanceof RegExp){const i=new r(t);return i.lastIndex=t.lastIndex,i}if(t instanceof DataView)return new r(t.buffer.slice(0));if(t instanceof Error){const i=new r(t.message);return i.stack=t.stack,i.name=t.name,i.cause=t.cause,i}if(typeof File<"u"&&t instanceof File)return new r([t],t.name,{type:t.type,lastModified:t.lastModified});if(typeof t=="object"){const i=Object.create(e);return Object.assign(i,t)}return t}function bA(t,...e){const r=e.slice(0,-1),i=e[e.length-1];let n=t;for(let s=0;s<r.length;s++){const o=r[s];n=lc(n,o,i,new Map)}return n}function lc(t,e,r,i){if(rl(t)&&(t=Object(t)),e==null||typeof e!="object")return t;if(i.has(e))return mA(i.get(e));if(i.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),...u0(e)];for(let s=0;s<n.length;s++){const o=n[s];let a=e[o],c=t[o];if(wf(a)&&(a={...a}),wf(c)&&(c={...c}),typeof re<"u"&&re.isBuffer(a)&&(a=yf(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=r(c,a,o,t,e,i);l!=null?t[o]=l:Array.isArray(a)||mf(c)&&mf(a)?t[o]=lc(c,a,r,i):c==null&&wA(a)?t[o]=lc({},a,r,i):c==null&&yA(a)?t[o]=yf(a):(c===void 0||a!==void 0)&&(t[o]=a)}return t}function vA(t,...e){return bA(t,...e,gA)}const bf="error",EA="wss://relay.walletconnect.org",xA="wc",y0="universal_provider",ss=`${xA}@2:${y0}:`,w0="https://rpc.walletconnect.org/v1/",m0="generic",_A=`${w0}bundler`,Ti="call_status",IA=86400,nl={DEFAULT_CHAIN_CHANGED:"default_chain_changed"};var SA=Object.defineProperty,$A=Object.defineProperties,OA=Object.getOwnPropertyDescriptors,vf=Object.getOwnPropertySymbols,DA=Object.prototype.hasOwnProperty,AA=Object.prototype.propertyIsEnumerable,Ef=(t,e,r)=>e in t?SA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,os=(t,e)=>{for(var r in e||(e={}))DA.call(e,r)&&Ef(t,r,e[r]);if(vf)for(var r of vf(e))AA.call(e,r)&&Ef(t,r,e[r]);return t},PA=(t,e)=>$A(t,OA(e));function b0(t,e,r){var i;const n=ur(t);return((i=e.rpcMap)==null?void 0:i[n.reference])||`${w0}?chainId=${n.namespace}:${n.reference}&projectId=${r}`}function CA(t){return t.includes(":")?t.split(":")[1]:t}function v0(t){return t.map(e=>`${e.split(":")[0]}:${e.split(":")[1]}`)}function BA(t,e){const r=Object.keys(e.namespaces).filter(n=>n.includes(t));if(!r.length)return[];const i=[];return r.forEach(n=>{const s=e.namespaces[n].accounts;i.push(...s)}),i}function xf(t){return Object.fromEntries(Object.entries(t).filter(([e,r])=>{var i,n;return((i=r==null?void 0:r.chains)==null?void 0:i.length)&&((n=r==null?void 0:r.chains)==null?void 0:n.length)>0}))}function as(t={},e={}){const r=xf(_f(t)),i=xf(_f(e));return vA(r,i)}function _f(t){var e,r,i,n,s;const o={};if(!Kt(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=Oi(a);o[d]=PA(os(os({},o[d]),c),{chains:Ht(l,(e=o[d])==null?void 0:e.chains),methods:Ht(u,(r=o[d])==null?void 0:r.methods),events:Ht(h,(i=o[d])==null?void 0:i.events)}),(Kt(f)||Kt(((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 If(t){return t.includes(":")?t.split(":")[2]:t}function Sf(t){const e={};for(const[r,i]of Object.entries(t)){const n=i.methods||[],s=i.events||[],o=i.accounts||[],a=so(r)?[r]:i.chains?i.chains:v0(i.accounts);e[r]={chains:a,methods:n,events:s,accounts:o}}return e}function ca(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 TA(t){try{const e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)}catch{return!1}}const E0={},Ri=t=>E0[t],la=(t,e)=>{E0[t]=e};var RA=Object.defineProperty,$f=Object.getOwnPropertySymbols,FA=Object.prototype.hasOwnProperty,NA=Object.prototype.propertyIsEnumerable,Of=(t,e,r)=>e in t?RA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Df=(t,e)=>{for(var r in e||(e={}))FA.call(e,r)&&Of(t,r,e[r]);if($f)for(var r of $f(e))NA.call(e,r)&&Of(t,r,e[r]);return t};const Af="eip155",UA=["atomic","flow-control","paymasterService","sessionKeys","auxiliaryFunds"],kA=t=>t&&t.startsWith("0x")?BigInt(t).toString(10):t,ua=t=>t&&t.startsWith("0x")?t:`0x${BigInt(t).toString(16)}`,Pf=t=>Object.keys(t).filter(e=>UA.includes(e)).reduce((e,r)=>(e[r]=jA(t[r]),e),{}),jA=t=>typeof t=="string"&&TA(t)?JSON.parse(t):t,LA=(t,e,r)=>{const{sessionProperties:i={},scopedProperties:n={}}=t,s={};if(!Kt(n)&&!Kt(i))return;const o=Pf(i);for(const a of r){const c=kA(a);if(!c)continue;s[ua(c)]=o;const l=n==null?void 0:n[`${Af}:${c}`];if(l){const u=l==null?void 0:l[`${Af}:${c}:${e}`];s[ua(c)]=Df(Df({},s[ua(c)]),Pf(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 MA=Object.defineProperty,qA=(t,e,r)=>e in t?MA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,zA=(t,e,r)=>qA(t,typeof e!="symbol"?e+"":e,r);let ha,VA=class x0{constructor(e){zA(this,"storage"),this.storage=e}async getItem(e){return await this.storage.getItem(e)}async setItem(e,r){return await this.storage.setItem(e,r)}async removeItem(e){return await this.storage.removeItem(e)}static getStorage(e){return ha||(ha=new x0(e)),ha}};var HA=Object.defineProperty,KA=Object.defineProperties,WA=Object.getOwnPropertyDescriptors,Cf=Object.getOwnPropertySymbols,GA=Object.prototype.hasOwnProperty,YA=Object.prototype.propertyIsEnumerable,Bf=(t,e,r)=>e in t?HA(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,ZA=(t,e)=>{for(var r in e||(e={}))GA.call(e,r)&&Bf(t,r,e[r]);if(Cf)for(var r of Cf(e))YA.call(e,r)&&Bf(t,r,e[r]);return t},JA=(t,e)=>KA(t,WA(e));async function XA(t,e){const r=ur(t.result.capabilities.caip345.caip2),i=t.result.capabilities.caip345.transactionHashes,n=await Promise.allSettled(i.map(h=>QA(r.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 QA(t,e,r){return await r(parseInt(t)).request(Ct("eth_getTransactionReceipt",[e]))}async function eP({sendCalls:t,storage:e}){const r=await e.getItem(Ti);await e.setItem(Ti,JA(ZA({},r),{[t.result.id]:{request:t.request,result:t.result,expiry:we(IA)}}))}async function tP({resultId:t,storage:e}){const r=await e.getItem(Ti);if(r){delete r[t],await e.setItem(Ti,r);for(const i in r)qt(r[i].expiry)&&delete r[i];await e.setItem(Ti,r)}}async function rP({resultId:t,storage:e}){const r=await e.getItem(Ti),i=r==null?void 0:r[t];if(i&&!qt(i.expiry))return i;await tP({resultId:t,storage:e})}var iP=Object.defineProperty,nP=Object.defineProperties,sP=Object.getOwnPropertyDescriptors,Tf=Object.getOwnPropertySymbols,oP=Object.prototype.hasOwnProperty,aP=Object.prototype.propertyIsEnumerable,uc=(t,e,r)=>e in t?iP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,fa=(t,e)=>{for(var r in e||(e={}))oP.call(e,r)&&uc(t,r,e[r]);if(Tf)for(var r of Tf(e))aP.call(e,r)&&uc(t,r,e[r]);return t},da=(t,e)=>nP(t,sP(e)),Hr=(t,e,r)=>uc(t,typeof e!="symbol"?e+"":e,r);class cP{constructor(e){Hr(this,"name","eip155"),Hr(this,"client"),Hr(this,"chainId"),Hr(this,"namespace"),Hr(this,"httpProviders"),Hr(this,"events"),Hr(this,"storage"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("client"),this.httpProviders=this.createHttpProviders(),this.chainId=parseInt(this.getDefaultChain()),this.storage=VA.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,r){this.httpProviders[e]||this.setHttpProvider(parseInt(e),r);const i=this.chainId;this.chainId=parseInt(e),this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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,r){const i=r||b0(`${this.name}:${e}`,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProviders(){const e={};return this.namespace.chains.forEach(r=>{var i;const n=parseInt(CA(r));e[n]=this.createHttpProvider(n,(i=this.namespace.rpcMap)==null?void 0:i[r])}),e}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}getHttpProvider(e){const r=e||this.chainId;return this.httpProviders[r]||(this.httpProviders=da(fa({},this.httpProviders),{[r]:this.createHttpProvider(r)}),this.httpProviders[r])}async handleSwitchChain(e){var r,i;let n=e.request.params?(r=e.request.params[0])==null?void 0:r.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:(i=this.namespace.chains)==null?void 0:i[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 r,i,n,s,o;const a=(i=(r=e.request)==null?void 0:r.params)==null?void 0:i[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=LA(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:da(fa({},l.sessionProperties||{}),{capabilities:da(fa({},u||{}),{[h]:p})})})}catch(g){console.warn("Failed to update session with capabilities",g)}return p}async getCallStatus(e){var r,i,n;const s=this.client.session.get(e.topic),o=(r=s.sessionProperties)==null?void 0:r.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=(i=s.sessionProperties)==null?void 0:i.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 rP({resultId:(n=e.request.params)==null?void 0:n[0],storage:this.storage});if(c)try{return await XA(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,r){var i;const n=new URL(e),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(Ct("eth_getUserOperationReceipt",[(i=r.request.params)==null?void 0:i[0]]))});if(!s.ok)throw new Error(`Failed to fetch user operation receipt - ${s.status}`);return await s.json()}getBundlerUrl(e,r){return`${_A}?projectId=${this.client.core.projectId}&chainId=${e}&bundler=${r}`}async sendCalls(e){var r,i,n;const s=await this.client.request(e),o=(r=e.request.params)==null?void 0:r[0],a=s==null?void 0:s.id,c=(s==null?void 0:s.capabilities)||{},l=(i=c==null?void 0:c.caip345)==null?void 0:i.caip2,u=(n=c==null?void 0:c.caip345)==null?void 0:n.transactionHashes;return!a||!l||!(u!=null&&u.length)||await eP({sendCalls:{request:o,result:s},storage:this.storage}),s}}var lP=Object.defineProperty,uP=(t,e,r)=>e in t?lP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Ii=(t,e,r)=>uP(t,typeof e!="symbol"?e+"":e,r);class hP{constructor(e){Ii(this,"name",m0),Ii(this,"client"),Ii(this,"httpProviders"),Ii(this,"events"),Ii(this,"namespace"),Ii(this,"chainId"),this.namespace=e.namespace,this.events=Ri("events"),this.client=Ri("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,r){this.httpProviders[e]||this.setHttpProvider(e,r);const i=this.chainId;this.chainId=e,this.events.emit(nl.DEFAULT_CHAIN_CHANGED,{currentCaipChainId:`${this.name}:${e}`,previousCaipChainId:`${this.name}:${i}`})}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 ur(e).namespace}getAccounts(){const e=this.namespace.accounts;return e?[...new Set(e.filter(r=>r.split(":")[1]===this.chainId.toString()).map(r=>r.split(":")[2]))]:[]}createHttpProviders(){var e,r;const i={};return(r=(e=this.namespace)==null?void 0:e.accounts)==null||r.forEach(n=>{var s,o;const a=ur(n),c=(o=(s=this.namespace)==null?void 0:s.rpcMap)==null?void 0:o[`${a.namespace}:${a.reference}`];i[a.reference]=this.createHttpProvider(n,c)}),i}getHttpProvider(e){const r=ur(e).reference,i=this.httpProviders[r];if(typeof i>"u")throw new Error(`JSON-RPC provider for ${e} not found`);return i}setHttpProvider(e,r){const i=this.createHttpProvider(e,r);i&&(this.httpProviders[e]=i)}createHttpProvider(e,r){const i=r||b0(e,this.namespace,this.client.core.projectId);if(!i)throw new Error(`No RPC url provided for chainId: ${e}`);return new Qc(new l0(i,Ri("disableProviderPing")))}}var fP=Object.defineProperty,dP=Object.defineProperties,pP=Object.getOwnPropertyDescriptors,Rf=Object.getOwnPropertySymbols,gP=Object.prototype.hasOwnProperty,yP=Object.prototype.propertyIsEnumerable,hc=(t,e,r)=>e in t?fP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,sn=(t,e)=>{for(var r in e||(e={}))gP.call(e,r)&&hc(t,r,e[r]);if(Rf)for(var r of Rf(e))yP.call(e,r)&&hc(t,r,e[r]);return t},cs=(t,e)=>dP(t,pP(e)),at=(t,e,r)=>hc(t,typeof e!="symbol"?e+"":e,r);class sl{constructor(e){at(this,"client"),at(this,"namespaces"),at(this,"optionalNamespaces"),at(this,"sessionProperties"),at(this,"scopedProperties"),at(this,"events",new dc),at(this,"rpcProviders",{}),at(this,"session"),at(this,"providerOpts"),at(this,"logger"),at(this,"uri"),at(this,"disableProviderPing",!1),at(this,"connectParams");var r,i;this.providerOpts=e,this.logger=Zc({logger:(r=e.logger)!=null?r:bf,name:(i=this.providerOpts.name)!=null?i:y0}),this.disableProviderPing=(e==null?void 0:e.disableProviderPing)||!1}static async init(e){const r=new sl(e);return await r.initialize(),r}async request(e,r,i){const[n,s]=this.validateChain(r);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:i})}sendAsync(e,r,i,n){const s=new Date().getTime();this.request(e,i,n).then(o=>r(null,$n(s,o))).catch(o=>r(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,r){if(!this.client)throw new Error("Sign Client not initialized");this.setNamespaces(e),await this.cleanupPendingPairings();const{uri:i,response:n}=await this.client.authenticate(e,r);i&&(this.uri=i,this.events.emit("display_uri",i));const s=await n();if(this.session=s.session,this.session){const o=Sf(this.session.namespaces);this.namespaces=as(this.namespaces,o),await this.persist("namespaces",this.namespaces),this.onConnect()}return s}on(e,r){this.events.on(e,r)}once(e,r){this.events.once(e,r)}removeListener(e,r){this.events.removeListener(e,r)}off(e,r){this.events.off(e,r)}get isWalletConnect(){return!0}async pair(e){var r,i;const{uri:n,approval:s}=await this.client.connect({pairingTopic:e,requiredNamespaces:this.namespaces,optionalNamespaces:this.optionalNamespaces,sessionProperties:this.sessionProperties,scopedProperties:this.scopedProperties,authentication:(r=this.connectParams)==null?void 0:r.authentication,walletPay:(i=this.connectParams)==null?void 0:i.walletPay});n&&(this.uri=n,this.events.emit("display_uri",n));const o=await s();this.session=o;const a=Sf(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,r){try{if(!this.session)return;const[i,n]=this.validateChain(e);this.getProvider(i).setDefaultChain(n,r)}catch(i){if(!/Please call connect/.test(i.message))throw i}}async cleanupPendingPairings(e={}){try{this.logger.info("Cleaning up inactive pairings...");const r=this.client.pairing.getAll();if(!_t(r))return;for(const i of r)e.deletePairings?this.client.core.expirer.set(i.topic,0):await this.client.core.relayer.subscriber.unsubscribe(i.topic);this.logger.info(`Inactive pairings cleared: ${r.length}`)}catch(r){this.logger.warn(r,"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,r;if(this.client=this.providerOpts.client||await L4.init({core:this.providerOpts.core,logger:this.providerOpts.logger||bf,relayUrl:this.providerOpts.relayUrl||EA,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(i){throw this.logger.error(i,"Failed to get session"),new Error(`The provided session: ${(r=(e=this.providerOpts)==null?void 0:e.session)==null?void 0:r.topic} doesn't exist in the Sign client`)}else{const i=this.client.session.getAll();this.session=i[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(r=>Oi(r)))];la("client",this.client),la("events",this.events),la("disableProviderPing",this.disableProviderPing),e.forEach(r=>{if(!this.session)return;const i=BA(r,this.session);if((i==null?void 0:i.length)===0)return;const n=v0(i),s=as(this.namespaces,this.optionalNamespaces),o=cs(sn({},s[r]),{accounts:i,chains:n});switch(r){case"eip155":this.rpcProviders[r]=new cP({namespace:o});break;default:this.rpcProviders[r]=new hP({namespace:o})}})}registerEventListeners(){if(typeof this.client>"u")throw new Error("Sign Client is not initialized");this.client.on("session_ping",e=>{var r;const{topic:i}=e;i===((r=this.session)==null?void 0:r.topic)&&this.events.emit("session_ping",e)}),this.client.on("session_event",e=>{var r;const{params:i,topic:n}=e;if(n!==((r=this.session)==null?void 0:r.topic))return;const{event:s}=i;if(s.name==="accountsChanged"){const o=s.data;o&&_t(o)&&this.events.emit("accountsChanged",o.map(If))}else if(s.name==="chainChanged"){const o=i.chainId,a=i.event.data,c=Oi(o),l=ca(o)!==ca(a)?`${c}:${ca(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:r})=>{var i,n;if(e!==((i=this.session)==null?void 0:i.topic))return;const{namespaces:s}=r,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:r})}),this.client.on("session_delete",async e=>{var r;e.topic===((r=this.session)==null?void 0:r.topic)&&(await this.cleanup(),this.events.emit("session_delete",e),this.events.emit("disconnect",cs(sn({},fe("USER_DISCONNECTED")),{data:e.topic})))}),this.on(nl.DEFAULT_CHAIN_CHANGED,e=>{this.onChainChanged(cs(sn({},e),{internal:!0}))})}getProvider(e){return this.rpcProviders[e]||this.rpcProviders[m0]}onSessionUpdate(){Object.keys(this.rpcProviders).forEach(e=>{var r;this.getProvider(e).updateNamespace((r=this.session)==null?void 0:r.namespaces[e])})}setNamespaces(e){const{namespaces:r={},optionalNamespaces:i={},sessionProperties:n,scopedProperties:s}=e;this.optionalNamespaces=as(r,i),this.sessionProperties=n,this.scopedProperties=s}validateChain(e){const[r,i]=(e==null?void 0:e.split(":"))||["",""];if(!this.namespaces||!Object.keys(this.namespaces).length)return[r,i];if(r&&!Object.keys(this.namespaces||{}).map(o=>Oi(o)).includes(r))throw new Error(`Namespace '${r}' is not configured. Please call connect() first with namespace config.`);if(r&&i)return[r,i];const n=Oi(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:r,internal:i=!1}){if(!this.namespaces)return;const[n,s]=this.validateChain(e);s&&(this.updateNamespaceChain(n,s),i?(this.events.emit("chainChanged",s),this.emitAccountsChangedOnChainChange({namespace:n,currentCaipChainId:e,previousCaipChainId:r})):this.getProvider(n).setDefaultChain(s),await this.persist("namespaces",this.namespaces))}emitAccountsChangedOnChainChange({namespace:e,currentCaipChainId:r,previousCaipChainId:i}){var n,s;try{if(i===r)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(`${r}:`)).map(If);if(!_t(a))return;this.events.emit("accountsChanged",a)}catch(o){this.logger.warn(o,"Failed to emit accountsChanged on chain change")}}updateNamespaceChain(e,r){if(!this.namespaces)return;const i=this.namespaces[e]?e:`${e}:${r}`,n={chains:[],methods:[],events:[],defaultChain:r};this.namespaces[i]?this.namespaces[i]&&(this.namespaces[i].defaultChain=r):this.namespaces[i]=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,r){var i;const n=((i=this.session)==null?void 0:i.topic)||"";await this.client.core.storage.setItem(`${ss}/${e}${n}`,r)}async getFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";return await this.client.core.storage.getItem(`${ss}/${e}${i}`)}async deleteFromStore(e){var r;const i=((r=this.session)==null?void 0:r.topic)||"";await this.client.core.storage.removeItem(`${ss}/${e}${i}`)}async cleanupStorage(){var e;try{if(((e=this.client)==null?void 0:e.session.length)>0)return;const r=await this.client.core.storage.getKeys();for(const i of r)i.startsWith(ss)&&await this.client.core.storage.removeItem(i)}catch(r){this.logger.warn(r,"Failed to cleanup storage")}}}const wP=sl,mP="wc",bP="ethereum_provider",vP=`${mP}@2:${bP}:`,EP="https://rpc.walletconnect.org/v1/",ks=["eth_sendTransaction","personal_sign"],_0=["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"],I0=["chainChanged","accountsChanged","message","disconnect","connect"],xP=async()=>{const{createAppKit:t}=await T0(()=>import("./core-0c13d1dd.js").then(e=>e.$),["assets/core-0c13d1dd.js","assets/index-726bc846.js","assets/index-a5cbd387.css","assets/index-c2e969f4.js"]);return t};var _P=Object.defineProperty,IP=Object.defineProperties,SP=Object.getOwnPropertyDescriptors,Ff=Object.getOwnPropertySymbols,$P=Object.prototype.hasOwnProperty,OP=Object.prototype.propertyIsEnumerable,fc=(t,e,r)=>e in t?_P(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Wr=(t,e)=>{for(var r in e||(e={}))$P.call(e,r)&&fc(t,r,e[r]);if(Ff)for(var r of Ff(e))OP.call(e,r)&&fc(t,r,e[r]);return t},on=(t,e)=>IP(t,SP(e)),ct=(t,e,r)=>fc(t,typeof e!="symbol"?e+"":e,r);function Ls(t){return Number(t[0].split(":")[1])}function ls(t){return`0x${t.toString(16)}`}function DP(t){const{chains:e,optionalChains:r,methods:i,optionalMethods:n,events:s,optionalEvents:o,rpcMap:a}=t;if(!_t(e))throw new Error("Invalid chains");const c={chains:e,methods:i||ks,events:s||js,rpcMap:Wr({},e.length?{[Ls(e)]:a[Ls(e)]}:{})},l=s==null?void 0:s.filter(d=>!js.includes(d)),u=i==null?void 0:i.filter(d=>!ks.includes(d));if(!r&&!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)||!r,f={chains:[...new Set(h?c.chains.concat(r||[]):r)],methods:[...new Set(c.methods.concat(n!=null&&n.length?n:_0))],events:[...new Set(c.events.concat(o!=null&&o.length?o:I0))],rpcMap:a};return{required:e.length?c:void 0,optional:r.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",vP),ct(this,"on",(e,r)=>(this.events.on(e,r),this)),ct(this,"once",(e,r)=>(this.events.once(e,r),this)),ct(this,"removeListener",(e,r)=>(this.events.removeListener(e,r),this)),ct(this,"off",(e,r)=>(this.events.off(e,r),this)),ct(this,"parseAccount",e=>this.isCompatibleChainId(e)?this.parseAccountId(e).address:e),this.signer={},this.rpc={}}static async init(e){const r=new uo;return await r.initialize(e),r}async request(e,r){return await this.signer.request(e,this.formatChainId(this.chainId),r)}sendAsync(e,r,i){this.signer.sendAsync(e,r,this.formatChainId(this.chainId),i)}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 r;if(!this.signer.client)throw new Error("Provider not initialized. Call init() first");this.loadConnectOpts(e);const{required:i,optional:n}=DP(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(Wr({namespaces:Wr({},i&&{[this.namespace]:i})},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=Iu(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{(r=this.modal)==null||r.close()}}async authenticate(e,r){var i;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(Wr({},e),{chains:this.rpc.chains}),r).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=Iu(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{(i=this.modal)==null||i.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:r}=e,{event:i}=r;i.name==="accountsChanged"?(this.accounts=this.parseAccounts(i.data),this.events.emit("accountsChanged",this.accounts)):i.name==="chainChanged"?this.setChainId(this.formatChainId(i.data)):this.events.emit(i.name,i.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 r=parseInt(e);this.chainId=r,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(Wr({},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 r=e.filter(i=>this.isCompatibleChainId(i)).map(i=>this.parseChainId(i));r.length&&(this.chainId=r[0],this.events.emit("chainChanged",ls(this.chainId)),this.persist())}setChainId(e){if(this.isCompatibleChainId(e)){const r=this.parseChainId(e);this.chainId=r,this.switchEthereumChain(r)}}parseAccountId(e){const[r,i,n]=e.split(":");return{chainId:`${r}:${i}`,address:n}}setAccounts(e){this.accounts=e.filter(r=>this.parseChainId(this.parseAccountId(r).chainId)===this.chainId).map(r=>this.parseAccountId(r).address),this.events.emit("accountsChanged",this.accounts)}getRpcConfig(e){var r,i;const n=(r=e==null?void 0:e.chains)!=null?r:[],s=(i=e==null?void 0:e.optionalChains)!=null?i:[],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,r){const i={};return e.forEach(n=>{i[n]=this.getRpcUrl(n,r)}),i}async initialize(e){var r;if(this.rpc=this.getRpcConfig(e),this.chainId=this.rpc.chains.length?Ls(this.rpc.chains):Ls(this.rpc.optionalChains),this.signer=await wP.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 i;try{const n=await xP(),{convertWCMToAppKitOptions:s}=await Promise.resolve().then(function(){return jP}),o=s(on(Wr({},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");i=n(on(Wr({},o),{universalProvider:this.signer,manualWCControl:!0,enableMobileFullScreen:((r=this.rpc.qrModalOptions)==null?void 0:r.enableMobileFullScreen)===!0}))}catch(n){throw console.warn(n),new Error("To use QR modal, please install @reown/appkit package")}if(i)try{this.modal=i}catch(n){throw this.signer.logger.error(n),new Error("Could not generate WalletConnectModal Instance")}}}loadConnectOpts(e){if(!e)return;const{chains:r,optionalChains:i,rpcMap:n}=e;r&&_t(r)&&(this.rpc.chains=r.map(s=>this.formatChainId(s)),r.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)})),i&&_t(i)&&(this.rpc.optionalChains=[],this.rpc.optionalChains=i==null?void 0:i.map(s=>this.formatChainId(s)),i.forEach(s=>{this.rpc.rpcMap[s]=(n==null?void 0:n[s])||this.getRpcUrl(s)}))}getRpcUrl(e,r){var i;return((i=this.rpc.rpcMap)==null?void 0:i[e])||`${EP}?chainId=eip155:${e}&projectId=${r||this.rpc.projectId}`}async loadPersistedSession(){if(this.session)try{const e=await this.signer.client.core.storage.getItem(`${this.STORAGE_KEY}/chainId`),r=this.session.namespaces[`${this.namespace}:${e}`]?this.session.namespaces[`${this.namespace}:${e}`]:this.session.namespaces[this.namespace];this.setChainIds(e?[this.formatChainId(e)]:r==null?void 0:r.accounts),this.setAccounts(r==null?void 0:r.accounts)}catch(e){this.signer.logger.error("Failed to load persisted session, clearing state..."),this.signer.logger.error(e),await this.disconnect().catch(r=>this.signer.logger.warn(r))}}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(r=>this.parseAccount(r))}}const AP=uo;var PP=Object.defineProperty,CP=Object.defineProperties,BP=Object.getOwnPropertyDescriptors,Nf=Object.getOwnPropertySymbols,TP=Object.prototype.hasOwnProperty,RP=Object.prototype.propertyIsEnumerable,Uf=(t,e,r)=>e in t?PP(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,S0=(t,e)=>{for(var r in e||(e={}))TP.call(e,r)&&Uf(t,r,e[r]);if(Nf)for(var r of Nf(e))RP.call(e,r)&&Uf(t,r,e[r]);return t},FP=(t,e)=>CP(t,BP(e));function NP(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 UP=t=>{const[e,r]=t.split(":");return $0({id:r,caipNetworkId:t,chainNamespace:e,name:"",nativeCurrency:{name:"",symbol:"",decimals:8},rpcUrls:{default:{http:["https://rpc.walletconnect.org/v1"]}}})};function kP(t){var e,r,i,n,s,o,a;const c=(e=t.chains)==null?void 0:e.map(UP).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:NP(t.themeVariables),chainImages:t.chainImages,connectorImages:t.walletImages,defaultNetwork:l,metadata:FP(S0({},t.metadata),{name:((r=t.metadata)==null?void 0:r.name)||"WalletConnect",description:((i=t.metadata)==null?void 0:i.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 $0(t){return S0({formatters:void 0,fees:void 0,serializers:void 0},t)}var jP=Object.freeze({__proto__:null,convertWCMToAppKitOptions:kP,defineChain:$0});const A5=Object.freeze(Object.defineProperty({__proto__:null,EthereumProvider:AP,OPTIONAL_EVENTS:I0,OPTIONAL_METHODS:_0,REQUIRED_EVENTS:js,REQUIRED_METHODS:ks,default:uo},Symbol.toStringTag,{value:"Module"}));export{O$ as A,Xc as B,hE as C,ao as D,$n as E,fi as F,Ct as G,p2 as H,hi as I,Rr as J,oo as K,Mt as L,vt as M,Lt as N,l0 as O,du as P,sp as Q,A5 as R,iS as a,nS as b,Fg as c,is as d,sS as e,si as f,Ih as g,qf as h,L as i,Et as j,aS as k,ii as l,pc as m,An as n,E1 as o,f1 as p,Fm as q,_E as r,oi as s,nt as t,q0 as u,Mf as v,fn as w,Pa as x,k8 as y,Qc as z};
|